michealAtmi michealAtmi - 1 year ago 88
Java Question

Uploaded file has virus how to validate it?

It happened that someone filled form and attached file with virus. Our application only checks file extension and size and nothing else is validated. Uploaded files could be checked with some antivirus or something...

What is the best solution here?

Answer Source

I'm using https://github.com/philvarner/clamavj. Download ClamScan.java and ScanResult.java.

and then I have somelike this this to call it (untested):

protected ScanResult.Status virusScanFile(File file) {
    ClamScan clamScan = new ClamScan(clamAVHost, clamAVPort, clamAVTimeout);
    ScanResult scanResult = null;
    if (clamScan.ping()) {
        try (InputStream inputStream = new FileInputStream(file)) {
            scanResult = clamScan.scan(inputStream);
        } catch (FileNotFoundException | IOException e) {
    } else {
        throw new RuntimeException("Could not scan file as ClamD did not respond to ping request!");
    ScanResult.Status scanResultStatus = null;
    if (scanResult != null) {
        scanResultStatus = scanResult.getStatus();
    return scanResultStatus;

If you need to install ClamAV on windows for development purposes then this may work for you:

  1. Download http://oss.netfarm.it/clamav/ which contains clamd.exe;
  2. Download http://www.clamwin.com/ which is the Windows version of ClamAV and contains the virus definitions updater (freshclam.exe);
  3. Install both applications as normal;
  4. Copy clamd.conf to C:/Clamav and edit as follows:

    LogFile C:\Program Files (x86)\ClamWin\bin\clamd.log
    DatabaseDirectory C:\ProgramData\.clamwin\db
  5. Open a cmd prompt with Administrator priviledges and 'cd' to the Clamav folder where you will find clamd.exe;

  6. type "clamd.exe --install" (no quotes);

  7. Open the Windows services and set "ClamWin Free Antivirus Scanner Servce" to autostart.

Otherwise just connect to a Linux install via the clamAVHost and clamAVPort parameters, the values of which you will need to define.