3

为了确定附加文件的文件类型,我使用了操作系统“文件”实用程序:

class AttachedFileTypeValidator < ActiveModel::Validator
  def validate(record)
    file = record.resource.uploaded_file
    attached_file = Rails.root + file.path
    file_type = `file #{attached_file}`
    Rails.logger.info "Attached file type determined to be: #{file_type}"
    unless file_type.split(',').first =~ /ASCII|UTF/
      record.errors[:resource_content_type] << "Attachment does not appear to be a text CSV file, please ensure it was saved correctly."
    end
  end
end

不幸的是,brakeman建议它是一个命令行注入机会。我假设这意味着有人想出一个聪明的文件名称,例如:

; rm -rf /;

我们走了。什么是清理文件名的好方法?

4

1 回答 1

3

使用IO#popen调用外部命令:

file_type = IO.popen(['file', attached_file]).read

这将为您处理文件名中有趣字符的正确转义。

于 2012-06-23T03:14:06.970 回答