32 raise RuntimeError()
33 known_locations = []
34 tweets_with_known_location = []
35 with open(data_file_name, 'r', encoding="utf-8") as tweet_file:36 tweet_json = tweet_file.read()
37 tweet = json.loads(tweet_json)
38 with open("./data/cities", 'r', encoding="utf-8") as city_file:
Python's open()
function can take in a relative or absolute path and read its file contents.
If a user is provided direct access to the path that is opened, it can have serious security risks.
def read_file(path):
with open(os.path.join('some/path', path)) as f:
f.read()
# Someone can exploit `read_file` and see your secrets this way:
read_file('../../../secrets.txt')
Either use a static path:
def read_file(path):
with open('some/path/to/file.txt') as f:
f.read()
Or, do some kind of validation to make sure you're not allowing arbitrary file access:
def read_file(filename):
if filename not in ('x.txt', 'y.txt'):
return 'Invalid filename'
with open(os.path.join('some/path', path)) as f:
f.read()