Clamav (русский)
Содержание:
- Clamav
- Status
- Steps for Clamav Backport
- Steps for copying Clamav to -updates/ -security
- Packages
- Using the milter
- ClamAV Clam AntiVirus
- OPTIONS
- OnAccessScan
- Зачем нужен антивирус ClamAV?
- Troubleshooting
- Best practices for resolving freshclam issues
- Freshclam.exe file information
- Коммерческие и некоммерческие аналоги
- Adding more databases/signatures repositories
- Платформы
Clamav
Contents |
Status
Cleared matrix for clamav-0.97.5 testing. No SO version change, so it’s still libclamav6, no major problems anticipated.
The libclamav6 transition is done for Hardy.
Note: Starting with 0.94, clamav now has an apparmor profile, so these backports may have issues related to apparmor. Starting with 0.97.5, upstream doesn’t ship signatures in the tarball, so clamd mail fail to start if the signatures aren’t available yet. This is not a test failure.
clamav-0.96.5 is in lucid-updates.
clamav-0.97 is in natty. 0.97.2 is in oneiric. clamav-0.97.3 is in precise and lucid-backports. 0.97.5 is in quantal and natty/oneiric/precise-security and updates (no more testing needed) and in lucid/hardy backports, more testing would be good to see if we might get it promoted to updates. No clamav packages in the PPA at the moment as the current versions are all in the archive..
Steps for Clamav Backport
-
Step one is to publish a draft package for a clamav <version> backport to older releases out for people to use. The draft source package can be found in the PPA.
- Step two is to prepare backports of the libclamav rdepends, upload them to the PPA, and then work on patching packages that don’t build.
- Step three is testing the backports from the PPA. Indicate test results below. All libclamav rdepends must be tested. Unless there are documented changes in the clamav-dameon (clamd) protocol, only a sampling of clamav-daemon rdepends need to be tested.
- Step four is massive backport of all of the needed updates at the same time so nothing (promise) breaks.
- Step five: Move to another release, rinse, repeat.
Testing procedures can be found here or by clicking on the package names in the matrix below. Feel free to complete missing testing procedures.
Steps for copying Clamav to -updates/ -security
Once clamav and any needed rdepends are in *-backports, a close watch on bug reports for all related packages must be maintained. The step to *-backports brings the new clamav version to a wider audience for testing. The purpose if using *-backports is to enable wide testing and early access to users that require it while leaving -proposed open for any urgent fixes that need to be pushed on through.
Once the package set has aged sufficiently (generally a week without new bug reports is generally sufficient) then it should be copied to either *-security or *-updates. Virtually all clamav releases include security fixes, so it is likely that *-security will be the initial target and then the packages will be automatically copied to *-updates. The Ubuntu security team will rebuild all the packages in the Ubuntu security PPA if the target is *-security. If the target is *-updates, the Ubuntu SRU can pocket copy the packages from *-backports.
Packages
The following matrices indicate the testing phase for every package which depends/uses clamav. Packages which can use multiple methods of scanning (ie. clamd, clamdscan, clamscan) will be listed in each matrix and have to be tested accordingly. Matrix values:
-
X — package n/a in that particular release, or cannot be tested
-
OK — package was tested and it works without problems
-
<blank> — package is being tested / was not tested yet
-
any other short comment…
Packages built with libclamav (libclamav rdepends), these need to be tested before any other package:
testing libclamav6/clamav0.97.5
Packages |
Hardy |
Lucid |
Natty |
Oneiric |
Precise |
Quantal |
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
X
Note1: php-clamav is NOT in any release yet, only in the clamav-ppa
Packages which integrate with clamav through clamscan/clamdscan:
testing libclamav6/clamav0.97.5
Packages |
Hardy |
Lucid |
Natty |
Oneiric |
Precise |
Quantal |
moodle (suggests) |
||||||
Note1: problems using clamscan in ALL releases, only works with backported package in Hardy; clamdscan works (https://bugs.launchpad.net/bugs/829649)
Packages which integrate with clamav via the clamav-daemon socket protocol:
testing libclamav6/clamav0.97.5
Packages |
Hardy |
Lucid |
Natty |
Oneiric |
Precise |
Quantal |
X |
||||||
dtc/dtc-cyrus |
X |
X |
X |
|||
dtc/dtc-postfix-courier |
X |
X |
X |
|||
linkchecker (suggests) |
||||||
mahara |
||||||
Using the milter
Copy to and adjust it to your needs. For example:
/etc/clamav/clamav-milter.conf
MilterSocket /run/clamav/clamav-milter.sock MilterSocketMode 660 FixStaleSocket yes User clamav PidFile /run/clamav/clamav-milter.pid TemporaryDirectory /tmp ClamdSocket unix:/var/lib/clamav/clamd.sock LogSyslog yes LogInfected Basic
Create :
/etc/systemd/system/clamav-milter.service
Description='ClamAV Milter' After=clamd.service Type=forking ExecStart=/usr/bin/clamav-milter --config-file /etc/clamav/clamav-milter.conf WantedBy=multi-user.target
Enable and start the service.
ClamAV Clam AntiVirus
ClamAV Свободный Антивирус с открытым кодом для сканирования вирусов. Свободный Антивирус для Windows, Linux.
Homepage: ClamAV
Clam AntiVirus — пакет антивирусного ПО. Главная цель Clam AntiVirus — интеграция с серверами электронной почты для проверки файлов, прикреплённых к сообщениям. В пакет входит масштабируемый многопоточный демон clamd, управляемый из командной строки сканер clamscan, а также модуль обновления сигнатур по Интернету freshclam.
Использования консольного ClamAV (clamscan) для Debian, Ubuntu
aptitude install clamav clamav-freshclam clamav-daemon
Обновляем вирусные базы
freshclam
Сканирование производится командой clamscan. Для эффективности можно вводить дополнительные параметры, например:
clamscan -r /directory – рекурсивное сканирование, т.е. сканирование в подкаталогах; clamscan -i – показывать только инфицированные файлы; clamscan -move=/infected_files_dir – перемещение инфицированных файлов в отдельную директорию; clamscan -remove – удаление инфицированных файлов. clamscan --log=pach_to_file - выводить информацию в лог - файл --file-list=FILE -f FILE Сканировать файлы из файла FILE --archive-verbose -a Показать имена файлов внутри проверенных архивов --debug Включить отладочные сообщения(libclamav) --quiet Выводить только сообщения об ошибках --stdout Вывод на stdout вместо stderr --no-summary Отключить вывод сумарного результата в конце сканирования --infected -i Выводить только инфицированные файлы --suppress-ok-results -o Не инфицированные файлы не выводить --bell Звуковое сообщение при обнаружении вируса
Проверить работу ClamAV можно скачав сигнатуру вируса с сайта http://eicar.org/anti_virus_test_file.htm
# wget https://secure.eicar.org/eicar.com.txt # clamscan -r /home/test/ /home/test/eicar.com.txt: Eicar-Test-Signature FOUND ...
Варианты запуска clamscan через cron
crontab -e @daily root usrbinclamscan -r -i homesambafs #or @daily root usrbinclamscan --recursive --infected --log=varlogclamscan_smb.log homesambafs
Иногда нужно задать несколько директорий, для этого можно создать файл со списком файлов и/или директорий и указать его при помощи ключа -f
@daily root usrbinclamscan --recursive --infected --log=varlogclamavclamscan.log -f etcclamavcheckdirs
Файл checkdirs не долже содержать пустых строк
- checkdirs
-
varwww varlibroundcube
OPTIONS
Freshclam reads its configuration from freshclam.conf. The settings can be overwritten with command line options.
- -h, —help
- Output help information and exit.
- -V, —version
- Print version number and exit.
- -v, —verbose
- Be verbose. This option causes freshclam to print much additional information.
- —debug
- Enable debug messages from LibClamAV.
- —quiet
- Be quiet — output only error messages.
- —no-warnings
- Don’t print and log warnings.
- —stdout
- Write all messages to stdout.
- —config-file=FILE
Read configuration from FILE.
-l FILE, —log=FILE
Log report to FILE.
-d, —daemon
Run in a daemon mode. Defaults to 12 checks per day unless otherwise specified by —checks or freshclam.conf.
-p FILE, —pid=FILE
Write daemon’s pid to FILE.
-u USER, —user USER
Run as USER. By default (when started by root) freshclam drops privileges and operates as the » user.
—no-dns
This option forces old non-DNS verification method (without a TTL delay).
-c #n, —checks=#n
Check #n times per day for a new database. #n must be between 1 and 50.
—datadir=DIRECTORY
Install new database in DIRECTORY. The directory must be writable for the » user or unprivileged user running freshclam.
—daemon-notify=/path/to/clamd.conf
Notify the daemon about the new database. By default it reads a hardcoded config file but you can use a different one. Both local and TCP sockets are supported.
-a IP, —local-address=IP
Use (local) IP for HTTP downloads. Useful for multi-homed systems. If binding fails for whatever reason, a warning is issued and freshclam behaves like without this flag.
—on-update-execute=COMMAND
Execute COMMAND after successful update.
—on-error-execute=COMMAND
Execute COMMAND if error occurred. Remember, that virus database freshness is the most important thing in anti-virus system. With this option freshclam can alert you (eg. send SMS) when something is going wrong.
—on-outdated-execute=COMMAND
Execute COMMAND when freshclam reports outdated version. In the command string %v will be replaced by the new version number.
—list-mirrors
Print mirror details from mirrors.dat (cache file for the mirror manager).
—submit-stats[=/path/to/clamd.conf]
Upload detection statistics to the ClamAV Project (see freshclam.conf(5):SubmitDetectionStats for more details). No database update will be performed. This option only works in the interactive mode.
—update-db=DBNAME
With this option you can limit updates to a subset of database files. The DBNAME should be «main», «daily», «bytecode», «safebrowsing» or one of the 3rd party database names. This option can be used multiple times and only works with the official and 3rd party databases distrubuted through the ClamAV mirrors, your custom databases (specified with DatabaseCustomURL in freshclam.conf) will not be ignored.
—enable-stats
Enable submission of statistical data.
—stats-host-id=UUID
HostID in the form of an UUID to use when submitting statistical information.
OnAccessScan
On-access scanning require the kernel to be compiled with fanotify (kernel >= 3.8).
On-access scanning will scan the file while reading, writing or executing it.
Is it possibile to enable the OnAccessScan editing the :
/etc/clamav/clamd.conf
# Enable son-access scan, required clamd service running ScanOnAccess true # Set the mount point where to recursively perform the scan, # this could be every path or multiple path (one line for path) OnAccessMountPath /usr OnAccessMountPath /home/ OnAccessExcludePath /var/log/ # flag fanotify to block any events on monitored files to perform the scan OnAccessPrevention false # perform scans on newly created, moved, or renamed files OnAccessExtraScanning true # check the UID from the event of fanotify OnAccessExcludeUID 0 # action to perform when clamav detects a malicious file # it is possibile to specify ad inline command too VirusEvent /etc/clamav/detected.zsh # WARNING: clamd should run as root User root
Create:
/etc/clamav/detected.zsh
#!/usr/bin/env zsh alert="Signature detected: $CLAM_VIRUSEVENT_VIRUSNAME in $CLAM_VIRUSEVENT_FILENAME" echo "$(date) - $CLAM_VIRUSEVENT_VIRUSNAME > $CLAM_VIRUSEVENT_FILENAME" >> /var/log/clamav/infected.log if ]; then echo "$alert" {{!}} wall -n else notify-send "$alert" fi
If you are using AppArmor it is necessary to allow clamd to run as root:
# aa-complain clamd
Restart/start the service with .
Зачем нужен антивирус ClamAV?
Основное предназначение ClamAV — защита компьютера от почтовых вирусов. Данный антивирус может быть встроен в любой почтовый клиент (The Bat, Outlook и т.д.), после чего все приходящие пользователю письма будут автоматически сканироваться ClamAV и изолироваться при обнаружении угроз. Кроме того, данное антивирусное средство применяется и для защиты почтовых серверов, работающих в среде Windows (как правило, серверных версиях).
Второе предназначение антивируса ClamAV — поиск вирусных программ на компьютере (жестких дисках и любых внешних накопителях). Однако функция сканирования ПК запускается вручную.
Troubleshooting
Error: Clamd was NOT notified
If you get the following messages after running freshclam:
WARNING: Clamd was NOT notified: Cannot connect to clamd through /var/lib/clamav/clamd.sock connect(): No such file or directory
Add a sock file for ClamAV:
# touch /run/clamav/clamd.ctl # chown clamav:clamav /run/clamav/clamd.ctl
Then, edit — uncomment this line:
LocalSocket /run/clamav/clamd.ctl
Save the file and restart .
Error: No supported database files found
If you get the next error when starting the daemon:
LibClamAV Error: cli_loaddb(): No supported database files found in /var/lib/clamav ERROR: Not supported data format
This happens because of mismatch between setting and setting . pointing to , but (default directory) pointing to , or other directory. Edit in and replace with the same DatabaseDirectory like in . After that clamav will start up successfully.
Error: Can’t create temporary directory
If you get the following error, along with a ‘HINT’ containing a UID and a GID number:
# can't create temporary directory
Correct permissions:
# chown UID:GID /var/lib/clamav && chmod 755 /var/lib/clamav
Best practices for resolving freshclam issues
A clean and tidy computer is the key requirement for avoiding problems with freshclam. This means running a scan for malware, cleaning your hard drive using 1cleanmgr and 2sfc /scannow, 3uninstalling programs that you no longer need, checking for Autostart programs (using 4msconfig) and enabling Windows’ 5Automatic Update. Always remember to perform periodic backups, or at least to set restore points.
Should you experience an actual problem, try to recall the last thing you did, or the last thing you installed before the problem appeared for the first time. Use the 6resmon command to identify the processes that are causing your problem. Even for serious problems, rather than reinstalling Windows, you are better off repairing of your installation or, for Windows 8 and later versions, executing the 7DISM.exe /Online /Cleanup-image /Restorehealth command. This allows you to repair the operating system without losing data.
To help you analyze the freshclam.exe process on your computer, the following programs have proven to be helpful: ASecurity Task Manager displays all running Windows tasks, including embedded hidden processes, such as keyboard and browser monitoring or Autostart entries. A unique security risk rating indicates the likelihood of the process being potential spyware, malware or a Trojan. BMalwarebytes Anti-Malware detects and removes sleeping spyware, adware, Trojans, keyloggers, malware and trackers from your hard drive.
Freshclam.exe file information
The process known as ClamWin Antivirus belongs to software ClamWin Free Antivirus or ClamWin Antivirus by unknown.
Description: Freshclam.exe is not essential for the Windows OS and causes relatively few problems. The file freshclam.exe is located in a subfolder of «C:\Program Files».
Known file sizes on Windows 10/8/7/XP are 126,976 bytes (33% of all occurrences), 147,456 bytes or 53,760 bytes.
The application has no file description. The program is not visible. The program uses ports to connect to or from a LAN or the Internet. The freshclam.exe file is not a Windows core file.
Therefore the technical security rating is 60% dangerous.
Uninstalling this variant:
In case of problems with freshclam.exe, you can also do the following: 1) uninstall ClamWin Free Antivirus software via Windows Control Panel/Add or Remove Programs (Windows XP) or Programs and Features (Windows 10/8/7) 2) search the support area on the Clamwin website 3) make sure that you have installed the latest version.
Recommended: Identify freshclam.exe related errors
External information from Paul Collins:
«freshclam» is not required to run at start up.
Коммерческие и некоммерческие аналоги
Как упоминалось выше, разработчики антивирусного ПО предпринимают попытки «застолбить» перспективный Linux-рынок, поэтому сейчас у пользователей Linux есть возможность получить антивирусное ПО от почти всех известных производителей: Avira, Avast! Antivirus, AVG, Bitdefender, ClamAV, Kaspersky Linux Security, McAfee VirusScan Enterprise fοr Linux, Panda Security fοr Linux и т.д.
Для Linux-систем доступен и один из самых известных антивирусов — Dr. Web, который можно загрузить по адресу. Полученный .run-файл необходимо запустить, однако для этого может потребоваться изменить его атрибуты командой chmod +x имя_файла.run. Это самый сложный момент в установке Dr. Web, так как дальше установка проходит в интерактивном полуавтоматическом режиме. Dr. Web предлагает 30-дневную пробную лицензию, но для ее получения потребуется доступ к Интернет.
После проделанных манипуляций в меню появится соответствующий пункт, из которого можно будет запустить Центр Управления Dr.Web для Linux. Если вдруг этот пункт по непонятным причинам оттуда исчезнет, то центр управления можно вызвать из командной строки — drweb-cc. Основные компоненты антивируса — это сканер Dr.Web и SpIDer Guard. Назначение сканера очевидно, а SpIDer Guard — «это резидентный антивирусный компонент, проверяющий все используемые файлы в режиме реального времени». У программы есть очень простой пользовательский интерфейс, с помощью которого можно включить/отключить резидентную защиту, запустить сканирование системы, посмотреть статистику и количество файлов на карантине и обновить базы. Настройки находятся в меню Инструменты -> Настройки.
Кроме графического интерфейса Dr. Web позволяет также выполнять сканирование из командной строки с помощью команды drweb. Для сканирования домашнего каталога пользователя необходимо ввести команду:
$ drweb -path=~
После задания пути (их может быть несколько) можно задать некоторые параметры: как поступать с зараженными файлами, спрашивать ли пользователя при очистке файла, проверять ли архивы, использовать ли эвристику и т.д. Большинству пользователей подойдут значения по умолчанию, их можно просмотреть по команде drweb -help.
Удалить Dr.Web можно через меню: Приложения -> Dr.Web -> Удаление Dr.Web для Linux, или командой:
#/opt/drweb/remove.sh
После удаления в каталоге пользователя все равно остается каталог .drweb, который можно удалить вручную. Рекомендуется сохранить файл drweb.key, так как ключ выдается раз в 4 месяца. Также можно заглянуть в файл /etc/crontab, так как там тоже могут остаться изменения.
Как альтернативу коммерческому Dr.Web можно рассмотреть ограниченно-бесплатный Avast Antivirus. Для домашнего использования можно бесплатно получить годовой ключ. Загрузить программу для целевой ОС можно по адресу. После загрузки .deb архива его можно установить командой:
# dpkg -i avast4workstation_1.3.0-2_i386.deb
После первого запуска Avast потребует ключ, который можно будет получить в режиме online. С точки зрения пользователя антивирус состоит из трех исполняемых файлов: avast, avastgui и avast-update. Никакой резидентной защиты он не предоставляет. В Avast входит только сканирующий модуль, которого при специфике использования антивируса в Linux вполне достаточно. Для запуска сканера из командной строки достаточно ввести:
$ avast /
Команда avast-update используется для обновления баз, а avastgui для запуска графического интерфейса пользователя. Графический интерфейс позволяет просканировать определенные каталоги, обновить базы, просмотреть отчеты и задать уровень сканирования. Этот антивирус может оказаться весьма полезным при необходимости регулярно проверять какие-нибудь архивы.
Adding more databases/signatures repositories
ClamAV can use databases/signature from other repositories or security vendors.
Option #1: Set up Fangfrisch
Most importantly, Fangfrisch never needs to be run with root permissions, unlike clamav-unofficial-sigs.
Create database structure by running:
# sudo -u clamav /usr/bin/fangfrisch --conf /etc/fangfrisch/fangfrisch.conf initdb
Enable the .
Option #2: Set up clamav-unofficial-sigs
Enable the .
This will regularly update the unofficial signatures based on the configuration files in the directory .
To update signatures manually, run the following:
# clamav-unofficial-sigs.sh
To change any default settings, refer and modify .
Note: You still must have the started in order to have official signature updates from ClamAV mirrors.
MalwarePatrol database
In , change the following to enable this functionality:
malwarepatrol_receipt_code="YOUR-RECEIPT-NUMBER" # enter your receipt number here malwarepatrol_product_code="8" # Use 8 if you have a Free account or 15 if you are a Premium customer. malwarepatrol_list="clamav_basic" # clamav_basic or clamav_ext malwarepatrol_free="yes" # Set to yes if you have a Free account or no if you are a Premium customer.
Платформы
Linux, BSD
ClamAV является доступной для Linux и BSD-разрядных операционных систем. В большинстве случаев она доступна через репозитории дистрибутива для установки.
На серверах Linux ClamAV можно запускать в режиме демона, обслуживая запросы на сканирование файлов, отправляемых из других процессов. Они могут включать почты, программы обмена, файлы на Samba акций или пакетов данных, проходящих через прокси-сервер.
На Linux и BSD компьютерах ClamAV обеспечивает сканирование по требованию отдельных файлов, каталогов или всего ПК.
macOS
Apple macOS Server поддерживается антивирусом clamAV, начиная с версии 10.4. Он используется в службе электронной почты операционной системы. Платный графический пользовательский интерфейс доступен из Canimaan Software Ltd в виде ClamXav. Кроме того, Fink, Homebrew и MacPorts портировали ClamAV.
Другой программой, которая использует ClamAV на MacOS, является Counteragent. Работая вместе с программой Eudora Internet Mail Server, Counteragent сканирует электронную почту на наличие вирусов с помощью ClamAV, а также дополнительно обеспечивает фильтрацию спама через SpamAssassin.
OpenVMS
ClamAV для OpenVMS является доступной для платформ DEC Alpha и Itanium. Процесс сборки прост и предоставляет базовые функциональные возможности, в том числе: библиотека, утилита Clamscan, демон Clamd и Freshclam для обновления.
Windows
ClamAV для Windows сейчас является частью Immunet, разработанного Sourcefire. Immunet — это облачное программное обеспечение обнаружения вирусов в режиме реального времени, обслуживаемое Sourcefire, которое включает ClamAV и Immunet.
eComStation
ClamAV для eComStation (OS/2) доступен в (OS/2) Power Wiki. Основной целью данного программного обеспечения является интеграция с почтовыми серверами (сканирование вложений). Пакет предоставляет гибкий и масштабируемый многопоточный демон, сканер командной строки и инструмент для автоматического обновления через Интернет. Программы основаны на общей библиотеке, распространяемой вместе с антивирусным пакетом Clam, который можно использовать с собственным программным обеспечением. Самое главное, вирусная база постоянно обновляется.