Antivirus Uploads with Clamby

Episode #43 by Teacher's Avatar David Kimura

Summary

Using ClamAV, scan files uploaded to your application for viruses. In the event of a virus learn how to gracefully handle the infected file and notify the user.
rails security uploads 5:26

Resources

(Be sure to disable your antivirus when downloading the file and testing your application)

Summary

# /usr/local/etc/clamav/clamd.conf
## Around Line 8
# Comment or remove the line below.
# Example

## Around Line 101
# TCP port address.
# Default: no
TCPSocket 3310

# Gemfile
gem 'clamby'

# config/initializers/clamby.rb
Clamby.configure({
  :check => false,
  :daemonize => true,
  :error_clamscan_missing => false,
  :error_file_missing => false,
  :error_file_virus => false
})

If you are raising an error on viruses found, you can rescue from the error in your

# application.rb
  rescue_from Exceptions::VirusDetected do |exception|
    redirect_to root_url, alert: "Virus found on uploaded file."
  end 

# models/uploaded_file.rb
  mount_uploader :file, FileUploader
  validate :scan_for_viruses, :if => lambda { self.file_changed? }
  validates :file, presence: true
  private

  def scan_for_viruses
    path = self.file.path
    unless Clamby.safe?(path)
      File.delete(path)
      self.errors.add(:file, "Virus Found." )
    end
  end