clamav+pyClamad linux virus scanning

Posted by friday_13 on Mon, 20 Dec 2021 09:03:42 +0100

1, Background

Clam AntiVirus(Clam AV) is a free and open source anti-virus software. Software and virus library updates are released free of charge by the open source community. At present, ClamdAV mainly provides virus scanning and killing for Linux and Uinux systems. pyClamad is a third-party module of python, which allows Python to directly use ClamAV virus scanning daemon clamd to realize an efficient virus detection function.

2, Working principle

The management server sends multi-threaded instructions through python to connect to port 3310 of the business server, performs virus scanning, and then returns the results to the management server. The service server must install clamd related packages and start service listening to receive instructions normally at port 3310; Corresponding scanning strategies can be customized for different business environments, such as scanning object, description mode, scanning path, debugging frequency, etc.

3, clamav+pyClamad installation and scripting

3.1 machine preparation

Testing machine
​ 10.32.176.80
Tested machine
​ 10.32.176.86

3.2 operation of the tested machine

Create a clamav group, create a clamav user, and join the clamav group

groupadd clamav
useradd -g clamav clamav

Install the source code compilation tool and clamav dependencies

yum install -y \
  gcc gcc-c++ make python3 python3-pip valgrind \
  bzip2-devel check-devel json-c-devel libcurl-devel libxml2-devel \
  ncurses-devel openssl-devel pcre2-devel sendmail-devel zlib-devel

Download the source package of clamav:

wget https://www.clamav.net/downloads/production/clamav-0.103.3.tar.gz

Compile and install clamav

tar -zxvf clamav-0.103.3.tar.gz  (decompression)

cd clamav-0.103.3 (Enter directory)

./configure --prefix=/usr/local/clamav

make

make install    (Compile and install )

Start clamav

Create directory

mkdir /usr/local/clamav/logs      (Log storage directory)

mkdir /usr/local/clamav/updata   (clanav Virus library directory)

Modify profile

cp /usr/local/clamav/etc/clamd.conf.sample /usr/local/clamav/etc/clamd.conf

cp /usr/local/clamav/etc/freshclam.conf.sample /usr/local/clamav/etc/freshclam.conf
vim /usr/local/clamav/etc/clamd.conf 

#Example comment out this line Line 8

LogFile /usr/local/clamav/logs/clamd.log    Delete the previous notes and change the directory to logs below    Line 14

PidFile /usr/local/clamav/updata/clamd.pid     Delete the previous comment path and change it       Line 57

DatabaseDirectory /usr/local/clamav/updata      ditto                       Line 65
vi /usr/local/clamav/etc/freshclam.conf

#Example comment out this line Line 8

DatabaseDirectory /usr/local/clamav/updata

UpdateLogFile /usr/local/clamav/logs/freshclam.log

PidFile /usr/local/clamav/updata/freshclam.pid   


Create log files and authorize

touch /usr/local/clamav/logs/freshclam.logchown clamav:clamav /usr/local/clamav/logs/freshclam.logtouch /usr/local/clamav/logs/clamd.logchown clamav:clamav /usr/local/clamav/logs/clamd.logchown clamav:clamav /usr/local/clamav/updata

Install virus library offline

#cd /usr/local/clamav/updata Download the following virus libraries in advance and upload them to the machine:#wget http://database.clamav.net/main.cvd#wget http://database.clamav.net/daily.cvd#wget http://database.clamav.net/bytecode.cvd

Update virus library online

/usr/local/clamav/bin/freshclam        (Upgrade virus library)  ensure LINUX You can surf the Internet normally.

Open the listening port and start the service

sed -i -e '/^TCPAddr/{ s/127.0.0.1/0.0.0.0/;}' /usr/local/clamav/etc/clamd.conf Cancel TCPSocket The open listening port is 3310
/usr/local/clamv/sbin/clamd start start-up lsof -i:3310  Detect whether to listen

If the monitoring is successful, run the script on the detection machine...

3.3 testing machine operation

Environment where clapy clamad is installed

wget https://xael.org/pages/pyClamd-0.4.0.tar.gz

Decompression installation

tar -zxvf pyClamd-0.4.0.tar.gzpython setup.py install

Verify that clamav can be called in python

# pyhton>>> import pyclamd>>> cd = pyclamd. ClamdAgnostic()>>> cd. Ping() true returns true, which is ok

Write detection script

vim pyclamd.py#!/usr/bin/env python# -*- coding: utf-8 -*-import timeimport pyclamdfrom threading import Threadclass Scan(Thread): #Inheritance multithreading Thread class  def __init__ (self,IP,scan_type,file):    """Construction method"""    Thread.__init__(self)    self.IP = IP    self.scan_type=scan_type    self.file = file    self.connstr=""    self.scanresult=""  def run(self):    """Multi process run method"""    try:      cd = pyclamd.ClamdNetworkSocket(self.IP,3310)      """Probe connectivity"""      if cd.ping():        self.connstr=self.IP+" connection [OK]"        """heavy load clamd Virus signature Library"""        cd.reload()        """Judge scanning mode"""        if self.scan_type=="contscan_file":          self.scanresult="{0}\n".format(cd.contscan_file(self.file))        elif self.scan_type=="multiscan_file":          self.scanresult="{0}\n".format(cd.multiscan_file(self.file))        elif self.scan_type=="scan_file":          self.scanresult="{0}\n".format(cd.scan_file(self.file))        time.sleep(1)      else:        self.connstr=self.IP+" ping error,exit"        return    except Exception,e:      self.connstr=self.IP+" "+str(e)IPs=['10.32.176.86','xx.xx.xx.xx']   #List of scan hosts scantype="multiscan_file" #Specify scan mode,support multiscan_file,contscan_file,scan_filescanfile="/usr/local/bin" #Specify scan path i=1threadnum=2   #Specifies the number of threads to start scanlist = [] #storage Scan Class thread object list for ip in IPs:  """Bring the data value into the class and instantiate the object"""  currp = Scan(ip,scantype,scanfile)  scanlist.append(currp) #Append object to list  """When the specified number of threads is reached or IP Start thread after list count"""  if i%threadnum==0 or i==len(IPs):    for task in scanlist:      task.start() #Start thread    for task in scanlist:      task.join() #Wait for all child threads to exit and output the scan results      print task.connstr #Print server connection information      print task.scanresult #Print result information scanlist = [] I + = 1

4, Virus signature file generation

  1. After the pyclamd module is installed on the controlled end with clamav installed, a file with virus characteristics / tmp/EICAR is generated through the EICAR() method
  # python  >>> import pyclamd  >>> cd = pyclamd.ClamdAgnostic()  >>> void = open('/tmp/EICAR','w').write(cd.EICAR())

  1. Generate a string with virus characteristics. The contents are as follows. Copy the file / tmp/EICAR to the scanning directory of the target host for testing
# cat /tmp/EICARX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

5, Comparison of execution results

The detected machine performs the detection locally:

/usr/local/clamav/bin/clamdscan  -ri  /tmp   -l   /root/clamscan.logcat  /root/clamscan.log

Detect machine execution py script:

python simplel.py

be accomplished...

Topics: Python security security hole