Django - check the downloaded file

I need to check the file type of the downloaded file and allow only PDF, simple test and MS word files. Here is my model and form with a validation function. But I can upload files even without the extension.

class Section(models.Model):
    content = models.FileField(upload_to="documents")

class SectionForm(forms.ModelForm):
    class Meta:
        model = Section
    FILE_EXT_WHITELIST = ['pdf','text','msword']

    def clean_content(self):
        content = self.cleaned_data['content']
        if content:
            file_type = content.content_type.split('/')[0]
            print file_type
            if len(content.name.split('.')) == 1:
                raise forms.ValidationError("File type is not supported.")
            if content.name.split('.')[-1] in self.FILE_EXT_WHITELIST:
                return content
            else:
                raise forms.ValidationError("Only '.txt' and '.pdf' files are allowed.")

Here is an idea

def section_update(request, object_id):
    section = models.Section.objects.get(pk=object_id)
    if 'content' in request.FILES:
            if request.FILES['content'].name.split('.')[-1] == "pdf":
                content_file = ContentFile(request.FILES['content'].read())
                content_type = "pdf"
                section.content.save("test"+'.'+content_type , content_file)
                section.save()

In my opinion, I just save the file from request.FILE. I thought that during save () it would call clean_content and do a content check. I think clean_content does not require verification at all.

+5
source share
1 answer

You won’t work: as an attacker, I can just fake the HTML header to send you something with the mime type text/plain.

- Unix , file(1), , , . , , - . 16- Unicode, " " 0 .

. , : mime python?

+5

All Articles