def virus_scan(input_file): try: cd = pyclamd.ClamdUnixSocket() # test if server is reachable cd.ping() except pyclamd.ConnectionError: # if failed, test for network socket cd = pyclamd.ClamdNetworkSocket() try: cd.ping() except pyclamd.ConnectionError: raise ValueError( 'could not connect to clamd server either by unix or network socket' ) scan_results = cd.scan_file(input_file) if scan_results is not None: send_mail('Django Virus Found', 'Virus found in file uploaded', '*****@*****.**', ['*****@*****.**'], fail_silently=False) return True else: return False
def file_check(self, bucketname, object_key): s3_res = boto3.resource('s3') obj = s3_res.Object(bucketname, object_key) data = obj.get() log.info("Scanning: {type} {length} {key}".format( key=object_key, type=data['ContentType'], length=data['ContentLength'])) clamd = pyclamd.ClamdNetworkSocket(host=self.clamd_host, port=int(self.clamd_port), timeout=None) result = clamd.scan_stream(data['Body'].read()) if result != None: print( "\x1b[31;21mALERT: Malware found: {type} {length} {key} {malware}\x1b[0m" .format(key=object_key, type=data['ContentType'], length=data['ContentLength'], malware=result['stream'][1])) self._tag_result(bucketname, object_key, self.tags['infected']) else: log.info("result: File {key} is OK".format(key=object_key)) self._tag_result(bucketname, object_key, self.tags['clean'])
def run(self): try: cd = pyclamd.ClamdNetworkSocket(self.agent_ip, 3310) if cd.ping(): self.connstr = self.agent_ip + ' connection [ok]' self.status = 'success' self.version = cd.version() # if self.isReload: # 需要重载 # # load vrius'databases # cd.reload() if self.scan_type == "contscan_file": self.scanresult = "{0}".format(cd.contscan_file(self.file)) elif self.scan_type == "multiscan_file": self.scanresult = "{0}".format(cd.multiscan_file( self.file)) elif self.scan_type == "scan_file": self.scanresult = "{0}".format(cd.scan_file(self.file)) else: self.connstr = self.agent_ip + 'Ping Error, Exit.' self.status = 'failed' return except Exception as e: self.connstr = self.agent_ip + ' ' + str(e) self.status = 'failed'
def each(self, target): self.results = {'analysis': []} if self._clam is None: if len(self.filename) > 0: self._clam = pyclamd.ClamdUnixSocket(filename=self.filename) elif len(self.server) > 0 and self.port > 0: try: self._clam = pyclamd.ClamdNetworkSocket(host=self.server, port=self.port) except: return False else: return False if not self._clam.ping(): return False res = None with open(target) as f: res = self._clam.scan_stream(f.read()) if not res: return False status, name = res['stream'] self.add_tag(self._tag) self.results['analysis'].append((self._MALWARE_KEYWORD, name)) self.add_probable_name(name) return True
def virus_scan(input_file): try: cd = pyclamd.ClamdUnixSocket() # test if server is reachable cd.ping() except pyclamd.ConnectionError: # if failed, test for network socket cd = pyclamd.ClamdNetworkSocket() try: cd.ping() except pyclamd.ConnectionError: raise ValueError( 'could not connect to clamd server either by unix or network socket' ) scan_results = cd.scan_stream(input_file.read()) if scan_results is not None: #print 'Virus found:', scan_results send_mail('Django Virus Scanner Results', 'Virus scanner returned - {0}'.format(scan_results, ), '*****@*****.**', ['*****@*****.**'], fail_silently=False) raise ValidationError( 'Virus scanner returned %(value)s', params={'value': scan_results}, )
def run(self): """多进程 run 方法""" try: cd = pyclamd.ClamdNetworkSocket(self.IP, 3310, timeout=3) # 创建网络套接字连接对象 # void = open(r'D:/EICAR', 'w') # void.write(cd.EICAR()) # void.close() if cd.ping(): # 探测连通性 self.connstr = self.IP + " connection [OK]" # 重载 clamd 病毒特征库,建议更新病毒库后做 reload() 操作 # cd.reload() # 选择不同的扫描模式 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) # 线程挂起 1 秒 else: self.connstr = self.IP + " ping error,exit" return except Exception as e: self.connstr = self.IP + " " + str(e)
def clean_file(self): file = self.cleaned_data.get('file', '') #check a file in form for viruses if file and settings.ANTI_VIRUS: from tempfile import mkstemp import pyclamd import os #Raise an error if ANTI_VIRUS server not reachable try: cd = pyclamd.ClamdUnixSocket() # test if server is reachable cd.ping() except pyclamd.ConnectionError: # if failed, test for network socket cd = pyclamd.ClamdNetworkSocket() try: cd.ping() except pyclamd.ConnectionError: raise forms.ValidationError('Could not connect to clamd server either by unix or network socket.') #The AV is working so scan the file. #Create a temporary file name tmp_fn = str(uuid.uuid4()) #get the data from the file. data = self.files['file'] #Save the temp file. path = default_storage.save(tmp_fn, ContentFile(data.read())) #Uncommenting the next line will write a test virus instead of file in form. #path = default_storage.save(tmp_fn, ContentFile(cd.EICAR())) tmp_path = str(os.path.join(settings.MEDIA_ROOT, path)) #scan for viruses if cd.scan_file(tmp_path) is not None: #A virus was found. #Delete the tmp file os.remove(tmp_path) #Raise Validation Error raise forms.ValidationError("A virus was detected in this file and therefore it was rejected.") #remove the temp file since this is just a clean os.remove(tmp_path) #Make sure the file is a valid SSA DMF if not valid_dmf(file): raise forms.ValidationError("The files does not appear to be a valid DMF.") return file
def _connect_clam(): try: clamScanner = pyclamd.ClamdUnixSocket() clamScanner.ping() except ConnectionError: clamScanner = pyclamd.ClamdNetworkSocket() try: clamScanner.ping() except ConnectionError: raise ValueError("Unable to connect to clamd") return clamScanner
def version(): """ Displays the version of ClamAV """ try: cd = pyclamd.ClamdNetworkSocket() cd.ping() except pyclamd.ConnectionError: print("Could not connect locally to clamd !") return print(cd.version())
def run(): try: i = pyclamd.ClamdNetworkSocket(IP,3310) if i.ping(): self.message = self.IP + " connection ok" i.reload() if self.scan_type = "contscan_file": self.scanresult = "{0}\n".format(i.contscan_file) elif self.scan_type = "multiscan_file": self.scanresult = "{0}\n".format(i.multiscan_file) elif self.scan_type = "scan_file": self.scanresult = "{0}\n".format(i.scan_file)
def main(myblob: func.InputStream): logging.info(f"Python blob trigger function processed blob \n" f"Name: {myblob.name}\n" f"Blob Size: {myblob.length} bytes") cd = pyclamd.ClamdNetworkSocket() result = cd.scan_stream(myblob.read()) logging.info(f'{result}') try: if (result['stream'][0] == 'FOUND'): virus = str(result['stream'][1]) deleteBlob(myblob.uri) return f'blobname:{myblob.name}, blobsize:{myblob.length}, uri:{myblob.uri}, virus:{virus}' except TypeError: return f'novirus'
def _connect(self): """ Connect to clam server """ self.clamd_lock.acquire() if self.daemon == 'network': self.clamd = pyclamd.ClamdNetworkSocket(host=self.host, port=self.port, timeout=self.timeout) else: self.clamd = pyclamd.ClamdUnixSocket(filename=self.socket, timeout=self.timeout) self.clamd_lock.release()
def save(self, *args, **kwargs): super(Document, self).save(*args, **kwargs) try: cd = pyclamd.ClamdUnixSocket() # test if server is reachable cd.ping() except pyclamd.ConnectionError: # if failed, test for network socket cd = pyclamd.ClamdNetworkSocket() try: cd.ping() except pyclamd.ConnectionError: raise ValueError( 'could not connect to clamd server either by unix or network socket' ) scan_results = cd.scan_file(self.file.path) if scan_results is not None: send_mail('Django Virus Found', 'Virus found in file uploaded', '*****@*****.**', ['*****@*****.**'], fail_silently=False) return True # super(photo, self).save(*args, **kwargs) # have to save object first to get the file in the right place try: im = Image.open(self.file.path) if im.verify() == True: self.is_photo = True # image rotation code from http://stackoverflow.com/a/11543365/2731298 e = None if hasattr(im, '_getexif'): # only present in JPEGs for orientation in list(ExifTags.TAGS.keys()): if ExifTags.TAGS[orientation] == 'Orientation': break e = im._getexif() # returns None if no EXIF data if e is not None: exif = dict(list(e.items())) orientation = exif.get(orientation, None) if orientation == 3: im = im.transpose(Image.ROTATE_180) elif orientation == 6: im = im.transpose(Image.ROTATE_270) elif orientation == 8: im = im.transpose(Image.ROTATE_90) # im.thumbnail((1024,1024)) im.save(self.file.path) except: return False
def process (self, parameters={}, data={} ): verbose = False if 'verbose' in parameters: if parameters['verbose']: verbose = True filename = parameters['filename'] if 'clamd_host' in parameters: host = parameters['clamd_host'] else: host = '127.0.0.1' if 'clamd_port' in parameters: port = parameters['clamd_port'] else: port = 3310 if 'clamd_timeout' in parameters: timeout = parameters['clamd_timeout'] else: timeout = None #get clamd result try: cd = pyclamd.ClamdNetworkSocket(host, port, timeout) except pyclamd.ConnectionError as e: print('Exception connecting to ' + host+':' + str(port)+ ' error' + str(e)) return parameters, data if verbose: print(host+':' + str(port) +' '+cd.version().split()[0]) try: r = cd.scan_stream(open(filename,'rb',buffering=0)) except Exception as e: print('Exception CLAMAV scanning ' + host+':' + str(port)+' file '+ filename + ' error' + str(e)) return parameters, data if r != None: # see https://bitbucket.org/xael/pyclamd/src/2089daa540e1343cf414c4728f1322c96a615898/pyclamd/pyclamd.py?at=default&fileviewer=file-view-default#pyclamd.py-593 status, reason = r['stream'] if status == 'FOUND': data['clam_s'] = reason else: print('ERROR CLAMAV scanning ' + host+':' + str(port)+' file '+ filename + ' status ' + status + ' reason ' + reason) if verbose: print ("ClamAV: {}".format( data['clam_s'] )) return parameters, data
def run(self): try: cd = pyclamd.ClamdNetworkSocket(self.ip,self.port) if cd.ping(): print(self.ip+" "+"connection ok...") else: print(self.ip+" "+"connection error...") return cd.reload() ''' 若检测对象为多个,可使用multiscan_file多线程扫描方法 print(cd.multiscan_file(self.path)) ''' print(cd.contscan_file(self.path)) except Exception as e: print(self.ip+" "+str(e))
def _clamd_scan(stream): ''' Checks for malware in the given stream using a ClamAV daemon. Inspired by the example code in pyclamd. Scanning consumes the input stream. :param stream: the input stream to scan :type stream: file-like object :return: True if the file is clean and False if there is a detection. :rtype: bool :raises MalwareCheckError: if connecting to the ClamAV daemon fails or there is another error ''' log.debug("Running malware scan on input stream") try: daemon = pyclamd.ClamdNetworkSocket() daemon.ping() except pyclamd.ConnectionError: raise MalwareCheckError("Connection to ClamAV daemon failed") try: result = daemon.scan_stream(stream.read()) if result: # scan_stream only returns a non-None result on error or detection passed = False status = result['stream'] log.debug("Scan status: {s}".format(s=status)) if status[0] == 'FOUND': log.warn('Malware detected in upload: {s}'.format(s=status)) else: log.error('Malware scan failed: {s}'.format(s=status)) raise MalwareCheckError( "ClamAV scan produced an error: {s}".format(s=status)) else: passed = True except pyclamd.BufferTooLongError: raise MalwareCheckError("Uploaded file is too large for malware scan") except pyclamd.ConnectionError: raise MalwareCheckError("Connection to ClamAV daemon failed") return passed
def run(self): try: cd = pyclamd.ClamdNetworkSocket(self.IP, 3310) if cd.ping(): self.connstr = self.IP + "connection [OK]" cd.reload() 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)) else: self.connstr = self.IP + 'ping error' except Exception as e: self.connstr = self.IP + "" + str(e)
def reloadDB(agent_ip): data = dict() data['agent'] = agent_ip data['version'] = 'service not found.' data['status'] = 'failed' try: cd = pyclamd.ClamdNetworkSocket(agent_ip, 3310) if cd.ping(): data['connstr'] = agent_ip + ' connection [ok]' data['status'] = 'success' data['version'] = cd.version() cd.reload() else: data['connstr'] = agent_ip + 'Ping Error, Exit.' except Exception as e: data['connstr'] = agent_ip + ' ' + str(e) return data
def get_clam(): try: clam = pyclamd.ClamdUnixSocket() # test if server is reachable clam.ping() return clam except pyclamd.ConnectionError: # if failed, test for network socket try: cd = pyclamd.ClamdNetworkSocket() cd.ping() return cd except pyclamd.ConnectionError: raise ValueError( 'could not connect to clamd server either by unix or network socket' )
def table(table=None, session=None): """ Scan a full table for viruses Scan a full table performing full table scan and check for known virues using ClamAV Args: table (string): The name of the table to be scanned session (object): The optional session object used to query the database. If omitted the MySQL Shell's current session will be used. """ import mysqlsh shell = mysqlsh.globals.shell if session is None: session = shell.get_session() if session is None: print("No session specified. Either pass a session object to this " "function or connect the shell to a database") return if table is None: print("No table name was specified.") return try: cd = pyclamd.ClamdNetworkSocket() cd.ping() except pyclamd.ConnectionError: print("ERROR: impossible to connect to clamd!") return stmt = "SELECT * FROM {}".format(table) result = session.run_sql(stmt) record = result.fetch_one() while record: to_scan = ','.join(str(x) for x in record) out = cd.scan_stream(str.encode(to_scan)) if out: status, virusname = out['stream'] print("VIRUS FOUND in {} : {} !!".format(table, virusname)) return record = result.fetch_one() print("No known virus found in {}".format(table))
def run(self, obj, config): clamd_sock_path = str(config['clamd_sock_path']) clamd_host_name = str(config['clamd_host_name']) clamd_host_port = int(config['clamd_host_port']) clamd_force_reload = config['clamd_force_reload'] try: self._debug('Attempting Unix socket connection to clamd') cd = pyclamd.ClamdUnixSocket(clamd_sock_path) cd.ping() except pyclamd.ConnectionError: try: self._debug('Attempting Network connection to clamd') cd = pyclamd.ClamdNetworkSocket(clamd_host_name, clamd_host_port) cd.ping() except pyclamd.ConnectionError: logger.error( "clamd: Can\'t connect to Clamd\'s network socket.") self._error( "clamd: Can\'t connect to Clamd\'s network socket.") return if clamd_force_reload: self._debug(cd.reload()) cd_version = cd.version() self._debug(cd_version) try: output = cd.scan_stream(obj.filedata.read()) except pyclamd.BufferTooLongError: logger.error("clamd: BufferTooLongError.") self._error("clamd: BufferTooLongError.") return except pyclamd.ConnectionError: logger.error("clamd: Can\'t connect to Clamd\'s socket.") self._error("clamd: Can\'t connect to Clamd\'s socket.") return if output: out = output['stream'] self._add_result('clamd', out[1], {'Status': out[0]}) obj.add_bucket_list(out[1], self.current_task.user) obj.save(self.current_task.user) obj.reload()
def virus_scan(input_file): try: cd = pyclamd.ClamdUnixSocket() # test if server is reachable cd.ping() except pyclamd.ConnectionError: # if failed, test for network socket cd = pyclamd.ClamdNetworkSocket() try: cd.ping() except pyclamd.ConnectionError: raise ValueError('could not connect to clamd server either by unix or network socket') scan_results = cd.scan_file(input_file) if scan_results is not None: print 'Virus found:', scan_results[0] return True else: return False
def run(self): """多进程run方法""" try: cd = pyclamd.ClamdNetworkSocket(self.IP, 3310) # 创建网络套接字连接对象 if cd.ping(): self.connstr = self.IP + " connection [OK]" cd.reload() if self.scan_type == "contscan_file": # 选择不同的扫描模式 self.scan_result = f"{cd.contscan_file(self.file)}\n" elif self.scan_type == "multiscan_file": self.scan_result = f"{cd.multiscan_file(self.file)}\n" elif self.scan_type == "scan_file": self.scan_result = f"{cd.scan_file(self.file)}\n" time.sleep(1) # 线程挂起1秒 else: self.connstr = self.IP + " ping error, exit" return False except Exception as e: self.connstr = self.IP + " " + str(e)
def scan_file_for_viruses(file): """Varre ``file`` em busca de vírus, utilizando ClamAV. Pode levantar as exceções: - pyclamd.BufferTooLongError(ValueError) - pyclamd.ConnectionError(socket.error) Essa função traduz exceções a fim de isolar a dependência ``pyclamd``, portanto, para aumentar o isolamento é recomendado que sejam tratadas as exceções ``utils.AntivirusConnectionError`` e ``utils.AntivirusBufferTooLongError``. Exemplo: try: is_infected, details = scan_file_for_viruses(fileobject) except (AntivirusBufferTooLongError, AntivirusConnectionError): # ``fileobject`` excede o limite do buffer do ClamAV ou a instância # do ClamAV não pode ser contactada. pass :param file: Objeto do tipo arquivo. """ try: antivirus = pyclamd.ClamdNetworkSocket( host=CLAMAV_HOST, port=CLAMAV_PORT) except pyclamd.ConnectionError as exc: raise AntivirusConnectionError() from exc try: result = antivirus.scan_stream(file.read()) except pyclamd.ConnectionError as exc: raise AntivirusConnectionError() from exc except pyclamd.BufferTooLongError as exc: raise AntivirusBufferTooLongError() from exc finally: # O método ``antivirus.scan_stream`` não garante o fechamento da # socket em caso de exceções. antivirus._close_socket() if result: return True, result['stream'] else: return False, ''
def scan(filelist, conf=DEFAULTCONF): results = [] try: clamScanner = pyclamd.ClamdUnixSocket() clamScanner.ping() except: clamScanner = pyclamd.ClamdNetworkSocket() try: clamScanner.ping() except: raise ValueError("Unable to connect to clamd") # Scan each file from filelist for virus for f in filelist: output = clamScanner.scan_file(f) if output is None: continue if list(output.values())[0][0] == 'ERROR': with open(f, 'rb') as file_handle: try: output = clamScanner.scan_stream(file_handle.read()) except pyclamd.BufferTooLongError: continue if output is None: continue if list(output.values())[0][0] == 'FOUND': results.append((f, list(output.values())[0][1])) elif list(output.values())[0][0] == 'ERROR': print('ClamAV: ERROR:', list(output.values())[0][1]) # Set metadata tags metadata = { 'Name': "ClamAV", 'Type': "Antivirus", 'Version': clamScanner.version() } return (results, metadata)
def run(self): try: cd = pyclamd.ClamdNetworkSocket(self.IP, 22) # 创建忘了套接字连接对象 if cd.ping(): # 探测连通性 self.connstr = self.IP + " connection [OK]" cd.reload() # 重载clamd病毒特征库,建议更新病毒库后座reload()操作 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) # 线程挂起1秒 else: self.connstr = self.IP + " ping error.exit" return except Exception, e: self.constr = self.IP + " " + str(e)
def run(self): try: cd = pyclamd.ClamdNetworkSocket(self.IP, 3310) if cd.ping(): self.connstr = self.IP + " connection [OK]" cd.reload() 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.constr = self.IP + " ping error,exit" return except Exception as e: self.connstr = self.IP + " " + str(e)
def run(self): """多线程run方法""" try: cd = pyclamd.ClamdNetworkSocket(self.IP, 3310) #创建网络套接字连接对象 if cd.ping(): #检测连通性 self.connstr = self.IP + " connection [OK]" cd.reload() 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.contscan_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 + " connect error ,exit!" return except Exception, e: self.connstr = self.IP + " " + str(e)
def run(self): """多进程run方法""" try: cd = pyclamd.ClamdNetworkSocket(self.IP, 3310) #创建网络套接字连接对象 if cd.ping(): #探测连通性 self.connstr = self.IP + " connection {OK] " cd.reload() #重载clamd病毒特征库,建议更新病毒库后reload 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 as e: self.connstr = self.IP + " " + str(e)
def conn(self): connected = False try: self.clamObj = pyclamd.ClamdUnixSocket() self.clamObj.ping() connected = True except pyclamd.ConnectionError as e: print(e) print("trying ClamdNetworkSocket") try: self.clamObj = pyclamd.ClamdNetworkSocket() self.clamObj.ping() connected = True except pyclamd.ConnectionError as e: # todo: can chain an email here print(e) print( "could not connect to clamd server either by unix or network socket" ) return connected