Cloud Pak for Business Automation

Cloud Pak for Business Automation

Come for answers. Stay for best practices. All we’re missing is you.

 View Only

Using ClamAV anti virus in your python micro service for malware scanning.

By GURUPRASAD BANGALORE SHIVANNA posted Wed March 30, 2022 09:30 AM

  

ClamAV is an open source anti-virus toolkit, designed especially for e-mail scanning on mail gateways. It provides a number of utilities including a flexible and scalable multi-threaded daemon, a command line scanner and advanced tool for automatic database updates. The core of the package is an anti-virus engine available in a form of shared library.

 

ClamAV is widely available from third party package managers for most operating systems.

But in this guide I will talk about installing Docker version of ClamAV which will be best way to use it in Cloud deployment, and connect ClamAV using python flask micro service.

PreRequesties:

  • Docker
  • Python 3
  • PyCharm

  1. Downloading and running ClamAV in docker
  • Official ClamAV docker image will be available here:- https://hub.docker.com/r/clamav/clamav 
  • Run ‘docker pull clamav/clamav’ to pull image into your docker
  • Run ‘docker run -p 3310:3310 clamav/clamav’ to run clamAV container
        Now ClamAV service will be accessible from 3310 port.

     

          2. Connecting ClamAV from python flask microservice and scanning files.
    • I will be using ‘clamd’ Python module for connecting to ClamAV.
    • Run ‘pip install clamd’ from root directory of python micro service.
            Following is the sample code snippet of an api, which accepts the file and scans it using ClamAV
         
    @app.route('/upload_file', methods=['POST'])
    def upload_file():
        status = 200
        response = {}
        try:
           
            file = request.files['testfile']
            cd = clamd.ClamdNetworkSocket()
            cd.__init__(host='localhost', port=3310, timeout=None)
            scan_result = cd.instream(file)
            
            if (scan_result['stream'][0] == 'OK'):
                message = 'file has no virus)
                print(scan_result['stream'])
    	        file.seek(0)
                # <write the code to save file in local or push file to remote storage>
            elif (scan_result['stream'][0] == 'FOUND'):
                message = 'file has virus'
                print(scan_result['stream'])
            else:
                message = 'Error occured while processing'
            response['message'] = message
        except Exception as exp:
            print(traceback.format_exc())
            status = 500
            response['code'] = 500
            response['message'] = str(exp)
        return response, status
    ​

            cd = clamd.ClamdNetworkSocket()
            cd.__init__(host='localhost', port=3310, timeout=None)
            clamd module connects to your local clamd deamon(change host name and port if its different in your case)

           scan_result = cd.instream(file)
           This code scans the file for any virus and returns the result.

           For normal file output will be like this,
           {'stream': ('OK', None)}
           If file has virus , then the result would be like this 
           {'stream': ('FOUND', 'Win.Test.EICAR_HDB-1')}

     

             In order to check your api is working you can download a standard EICAR test file that was developed by the European Institute for Computer Antivirus           Research (EICAR) and use it on your api.

           NOTE: By default ClamAV can scan a file wit size upto 25 MB, so if there is a requirement to scan bigger file , we have to change one config value in 'clamd.conf'
      file, for example if we need to set the max file size to 100 MB, then change the prop value to following.
     StreamMaxLength 100M
         In docker version of ClamAV this file location is '/etc/clamav/clamd.conf'.
    0 comments
    29 views

    Permalink