2013-10-19 100 views
-1

我正在構建一個允許用戶上傳PDF文件以供其他用戶下載的Web應用程序(python和Django)。如何防止用戶上傳嵌入在pdf中的病毒?PDF和Django中的病毒

更新: 我在使用clamcv的django片段中發現了此代碼。這會做這份工作嗎?

def clean_file(self): 
    file = self.cleaned_data.get('file', '') 
    #check a file in form for viruses 
    if file: 
     from tempfile import mkstemp 
     import pyclamav 
     import os 
     tmpfile = mkstemp()[1] 
     f = open(tmpfile, 'wb') 
     f.write(file.read()) 
     f.close() 
     isvirus, name = pyclamav.scanfile(tmpfile) 
     os.unlink(tmpfile) 
     if isvirus: 
      raise forms.ValidationError(\ 
      "WARNING! Virus \"%s\" was detected in this file. \ 
      Check your system." % name) 

    return file 
+2

安裝了病毒掃描和上傳後,以及在存儲之前掃描的文件... –

回答

1

好,一般可以使用任何病毒掃描軟件來完成這個任務:只是

  • 產生這就要求你的文件
  • 使用病毒掃描程序的命令行字符串蟒蛇子進程運行命令行字符串像這樣:

    try: 
        command_string = 'my_virusscanner -parameters ' + uploaded_file 
        result = subprocess.check_output(command_string,stderr=subprocess.STDOUT,shell=True) 
        #if needed, do something with "result"    
    except subprocess.CalledProcessError as e: 
        #if your scanner gives an error code when detecting a virus, you'll end up here 
        pass 
    except: 
        #something else went wrong 
        #check sys.exc_info() for info 
        pass 
    

如果不檢查源代碼,我認爲pyclamav.scanfile或多或少都是一樣的 - 所以如果你信任clamav,你應該會很好。如果您不信任ist,請使用您選擇的病毒掃描程序的上述方法。

0

您可以使用django-safe-filefield包來驗證上傳的文件擴展名與MIME類型匹配。例如:

settings.py

CLAMAV_SOCKET = 'unix://tmp/clamav.sock' # or tcp://127.0.0.1:3310 

CLAMAV_TIMEOUT = 30 # 30 seconds timeout, None by default which means infinite 

forms.py

from safe_filefield.forms import SafeFileField 

class MyForm(forms.Form): 
    attachment = SafeFileField(
     scan_viruses=True, 
    )