开发者

Validating a file is what it claims to be by it's file extension

Is there a way to validate a file is what it claims to be according to it's file extension?

I have a large number of files that my application copies to a remote server. Before doing each file copy I would like to validate that the file is in fact what the file extension claims it to be.

Right now the user selects the files and/or directories of files using NSOpenPanel. Once I have an array of files I can validate each one physically exists before the copy commences. I have the validation that the source directory is writable working fine and开发者_Go百科 a copy using FSCopyObjectAsync with all the file cancellation in place is also working fine.

The last piece is this validation check. My users are limited in what they can upload, but the filter is done using the file extension. A malicious user could, for example, take a word document file (.doc by file extension) and change it to a .png in order for it to pass the initial open dialog box validation.

This is a rather simplistic example. The files are utilized by the server and I just want to make sure that files that won't work don't get uploaded.

I looked at NSFileManager attributeOfItems:atPath:, but it doesn't seem to offer any information for the real file type. The file type only returns that of a directory, symbolic link etc.

I would rather not attempt to open and load every file to validate, just read the file header and check it conforms to whatever file type spec it needs to.

This is not an iOS app.

Any and all help or pointers in the right direction much appreciated.


You could use libmagic or MagicKit, an Objective-C wrapper around libmagic. MagicKit can return the UTI or the MIME type of a given file.


You could try running /usr/bin/file --mime on it to get a MIME type.


Basically, no. The file system only knows a few very limited things about a file. There can be further metadata associated, but in many cases there won't be -- and in any case, metadata can lie. If you want to be certain that a file really contains what it claims, you need to open it and look.

Depending on the file type and level of trust, you may not have to look at the whole thing. For example, the file may have a magic number in its first bytes, or there may be other header info that's enough to convince you. But their presence does not guarantee that the file will "work".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜