Monday 21 April 2014

Virus Scanning in Java Application using ClamAV Antivirus Engine

If you are looking for the options where you can perform virus scanning for given files and documents, this post may help you out. This post will walk you through the approach of scanning files to detect trojans, viruses, malware and other malicious threats using ClamAV

ClamAV is an open source antivirus engine. This engine can be used to detect Trojans, viruses, malware and other malicious threats. 

You can go through the instructions to install the ClamAV antivirus engine and integrate your JAVA application to detect virus in your files. 


Installing ClamAV on Linux Box:

Follow below instructions to install and run ClamAV services on a Linux box:

Note: C compiler must be installed on Linux box before installing ClamAV.

1.     Download ClamAV source
To: Linux box @ your desired location

2.     Extract the tar using below commands:
gzip -d clamav-0.97.tar.gz
tar –xvf clamav-0.97.tar

3.     Change command prompt to ‘clamav-0.97’ directory

4.     Run commands to define user and group
groupadd clamav

useradd -g clamav -s /bin/false -c "Clam AntiVirus" clamav


5.     Run command to configure ClamAV packages after replacing token install-root
./configure --prefix=install-root --disable-zlib-vcheck

 install-root is your own desired location to install ClamAV.


6.     Execute command to compile ClamAV source (written in c language) 

     make

7.     Execute command to install ClamAV

make install


8.     Update configuration files:

/etc/clamd.conf

·         Search ‘Example’ word and comment this line
·         Uncomment below lines:
LogTime: yes
LogSyslog yes
PidFile /var/run/clamav/clamd.pid
TemporaryDirectory /tmp
LocalSocket /var/run/clamav/clamd.socket
FixStaleSocket yes
User clamav

·         Configure and uncomment below lines. Ensure to replace token Linux_Box_IP with proper IP.

TCPAddr Linux_Box_IP
TCPSocket 3310

/etc/freshclam.conf

·         Search ‘Example’ word and comment this line
·         Uncomment below lines:
LogTime: yes

LogSyslog yes

PidFile /var/run/clamav/clamd.pid
DatabaseMirror database.clamav.net
NotifyClamd /etc/clamd.conf

9.     Start the base services to make sure they work  
  • Set command prompt to /sbin and run command
          ./configure &
  •  Set command prompt to /bin and run command
          ./freshclam –d &

10.  Perform manual testing to scan the file:

./clamdscan file_to_scan

Sample Output:

/home/infra/installs/clamav-0.97-installation/bin/../Party.docx: OK

----------- SCAN SUMMARY -----------
Infected files: 0
Time: 0.051 sec (0 m 0 s)


If you reached at this stage, you are done with the installation of ClamAV properly. Congratulations !!!. Now next step is to scan Virus in Java Application.

How to Scan Virus in JAVA Application

1.    Ensure to download required third party jars
2.     Use below class to plug ClamAV engine to your application. 
          
Package com.xxx.doc.utils;

import java.io.FileInputStream;
import java.io.InputStream;

import net.taldius.clamav.ClamAVScanner;
import net.taldius.clamav.ClamAVScannerFactory;

/**
 * Utility class to scan files using ClamAV antivirus APIs.
 */
public class ClamAVVirusHandler {

       // Host where 'clamd' process is running
       private String clamdHost;
      
       // Port on which 'clamd' process is listening
       private String clamdPort;
      
       // Connection time out to connect 'clamd' process
       private String connTimeOut;
      
       private ClamAVScanner scanner;
      
       public void setClamdHost(String clamdHost){
              this.clamdHost = clamdHost;
       }
      
       public String getClamdHost(){
              return this.clamdHost;
       }
      
       public void setClamdPort(String clamdPort){
              this.clamdPort = clamdPort;
       }
      
       public String getClamdPort(){
              return this.clamdPort;
       }
      
       public void setConnTimeOut(String connTimeOut){
              this.connTimeOut = connTimeOut;
       }
      
       public String getConnTimeOut(){
              return this.connTimeOut;
       }
      
       /**
        * Method to initialize clamAV scanner
        */
       public void initScanner(){
             
              ClamAVScannerFactory.setClamdHost(clamdHost);

              ClamAVScannerFactory.setClamdPort(Integer.parseInt(clamdPort));

              int connectionTimeOut = Integer.parseInt(connTimeOut);
             
              if (connectionTimeOut > 0) {
                   
                 ClamAVScannerFactory.setConnectionTimeout(connectionTimeOut);
              }
              this.scanner = ClamAVScannerFactory.getScanner();
       }

       public ClamAVScanner getClamAVScanner() {
              return scanner;
       }

       /**
        * Method scans files to check whether file is virus infected
        *
        * @param destFilePath file path
        * @return
        * @throws Exception
        */
       public boolean fileScanner(String destFilePath) throws Exception  {

              return fileScanner(new FileInputStream(destFilePath));
       }

       /**
        * Method scans files to check whether file is virus infected
        *
        * @param fileInputStream
        * @return
        * @throws Exception
        */
       public boolean fileScanner(InputStream fileInputStream) throws Exception        {

              boolean resScan = false;

              if (fileInputStream != null) {

                     resScan = scanner.performScan(fileInputStream);

              } else {

                     throw new Exception();
              }
              return resScan;
       }

}

3.     Configure below in applicationContext.xml file :

        <bean id="clamavutil" class="com.xxx.doc.utils.ClamAVVirusHandler" init-method="initScanner">
<property name="clamdHost" value=""/>
 <property name="clamdPort" value=""/>
 <property name="connTimeOut" value="90"/>  
        </bean>       


Note: To configure these property values, /etc/clamd.conf file should be referred. See the below configuration       that has been made in step-8 while installing ClamAV on Linux box

TCPAddr Linux_Box_IP
TCPSocket 3310

Property Description:

clamdHost
Host where 'clamd' service is running
clamdPort
Port on which 'clamd' service is listening
connTimeOut
Connection time out while connecting 'clamd' service

4.     Use ClamAVVirusHandler to scan the file:


   // Scan file to detect virus

   boolean noVirus;

   BeanFactory beanfactory = new  ClassPathXmlApplicationContext("applicationContext.xml");
                                               
   ClamAVUtil clamAVUtil = (ClamAVUtil) beanfactory.getBean("clamavutil");
                                               
   noVirus = clamAVUtil.fileScanner(doc);
                                               
               
   if(noVirus != true){

            System.out.println("Warning !! Virus detected");
   }



N   Now try to test virus infected file using above API. If you get "Warning !! Virus detected", that means you are successfully done with integrating ClamAV in your JAVA application. Congratulations !!!.

I hope this post helped you using ClamAV antivirus engine. Looking forward for your valuable comments and feedback.

3 comments:

  1. Nice post ..nice solution i have found through your blog
    feeling great!!

    ReplyDelete
  2. Any suggestions for this error. ?

    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at net.taldius.clamav.impl.NetworkScanner.openProtocolChannel(NetworkScanner.java:139)

    ReplyDelete
  3. I am always getting total errors: 1 what could be the issue?

    Example:
    clamdscan temp.txt

    ----------- SCAN SUMMARY -----------
    Infected files: 0
    Total errors: 1
    Time: 0.000 sec (0 m 0 s)

    ReplyDelete