1

ファイルパスがサブディレクトリ内のファイルにアクセスすることをチェックするPythonのコードがあります。Webサーバーが静的フォルダー内のファイルにアクセスするためのものです。

次のコードスニペットを使用します。

path = 'static/' + path
try:
    if '/../' in path:
        raise RuntimeError('/../ in static file path')
    f = open(path)
except (RuntimeError, IOError):
    app.abort(404)
    return

パスがきれいであれば、それで十分です。

この簡単なテストでは検出されない親ディレクトリにアクセスするパスを作成する方法はありますか?

4

3 に答える 3

2

を使用することをお勧めしos.path.relpathます。これはパスを取り、指定されたディレクトリから最も簡潔な相対パスを計算します。そうすれば、パスがで始まるかどうかをテストするだけで済みます".."

例えば。

path = ...
relativePath = os.path.relpath(path)
if relativePath.startswith(".."):
    raise RuntimeError("path escapes static directory")
completePath = "static/" + relativePath

os.readlinkシンボリック リンクを気にする必要がある場合は、シンボリック リンクを実際のパスに置き換えるために使用することもできます。

于 2012-12-09T10:49:39.860 に答える
1

Flaskには、問題なくコードにコピーできると思うヘルパー関数がいくつかあります。推奨される構文は次のとおりです。

filename = secure_filename(dirty_filename)
path = os.path.join(upload_folder, filename)

Werkzeugsecure_filenameは、このコードを実装して使用し、ファイル名をクリーンアップします。

_filename_ascii_strip_re = re.compile(r'[^A-Za-z0-9_.-]')    
_windows_device_files = ('CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4', 'LPT1',
                         'LPT2', 'LPT3', 'PRN', 'NUL')

def secure_filename(filename):
    r"""Pass it a filename and it will return a secure version of it.  This
    filename can then safely be stored on a regular file system and passed
    to :func:`os.path.join`.  The filename returned is an ASCII only string
    for maximum portability.

    On windows system the function also makes sure that the file is not
    named after one of the special device files.

    >>> secure_filename("My cool movie.mov")
    'My_cool_movie.mov'
    >>> secure_filename("../../../etc/passwd")
    'etc_passwd'
    >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
    'i_contain_cool_umlauts.txt'

    The function might return an empty filename.  It's your responsibility
    to ensure that the filename is unique and that you generate random
    filename if the function returned an empty one.

    .. versionadded:: 0.5

    :param filename: the filename to secure
    """
    if isinstance(filename, unicode):
        from unicodedata import normalize
        filename = normalize('NFKD', filename).encode('ascii', 'ignore')
    for sep in os.path.sep, os.path.altsep:
        if sep:
            filename = filename.replace(sep, ' ')
    filename = str(_filename_ascii_strip_re.sub('', '_'.join(
                   filename.split()))).strip('._')

    # on nt a couple of special files are present in each folder.  We
    # have to ensure that the target file is not such a filename.  In
    # this case we prepend an underline
    if os.name == 'nt' and filename and \
       filename.split('.')[0].upper() in _windows_device_files:
        filename = '_' + filename

    return filename
于 2012-12-09T10:31:30.303 に答える
0
..//

これは基本的に同じことですが、文字列をすぐに一致させるため/../ 、追加した文字列は検出されず、親ディレクトリを取得します。

于 2012-12-09T10:30:23.513 に答える