Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check size of uploaded file safely in bottlepy?

Tags:

python

bottle

I'm really afraid of that read() operation because it uses memory. For instance, anybody could DDoS my server by uploading a 1gb file, correct?

name = request.forms.get('name')
data = request.files.get('data')
if name and data.file:
    raw = data.file.read() # This is dangerous for big files
    filename = data.filename
    return "Hello %s! You uploaded %s (%d bytes)." % (name, filename, len(raw))

Is there any safe solution to get the uploaded file size? One guess would be to get file size from the file system; request.files.get('data') is probably stored somewhere in temp file right?

like image 567
holms Avatar asked Jun 27 '12 02:06

holms


1 Answers

Can you check if you can read chunks of data, one at a time.

If this is possible then:

name = request.forms.get('name')
data = request.files.get('data')
raw = ""
if name and data.file:
    while True:
        datachunk = data.file.read(1024)
        if not datachunk:
            break
        raw = raw + datachunk

    filename = data.filename
    return "Hello %s! You uploaded %s (%d bytes)." % (name, filename, len(raw))

If this is possible, then you should be able to also add a tracking mechanism on how large a file you want to read and if exceeded abort this operation.

How ever this solves only one of the possible ways of DDOS.

like image 52
pyfunc Avatar answered Oct 21 '22 00:10

pyfunc