ClamAV - ArchWiki

Jump to content

# ClamAV

From ArchWiki

Clam AntiVirus is an open source (GPL) anti-virus toolkit for UNIX. 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. Because ClamAV's main use is on file/mail servers, it primarily detects malware with its built-in signatures and is not a traditional endpoint security suite.

The current situation of anti-malware products on Linux is inadequate due to several factors:

1. Limited Variety: Compared to Windows, there are fewer users/clients resulting in limited interest for companies to develop products for Linux.
2. Complacency: Many believe Linux is inherently secure, leading to a lack of awareness and focus on malware protection. This creates a gap in proactive defense mechanisms.
3. Lack of Features: Existing tools often lack advanced features which are common in Windows anti-malware products, making them less effective on Linux.

This is especially bad because the amount of malware on Linux is increasing just as the possible attack surface due to the increasing number of Linux-based servers and IoT devices.

Currently on Linux one of the few existing and actively developed anti-malware solutions is ClamAV.

## Installation

Install the clamav package.

This will install the following tools:

    clamd: ClamAV Daemon
    clamonacc: On-Access real-time protection
    clamdscan: A simple scanning client
    clamdtop: A resource monitoring interface for clamd
    freshclam: Daemon for virus signature updates
    clamconf: Tool to create and check configuration files

All ClamAV related tools, services and daemons communicate with clamd via a socket.

By default this is done via a local socket, "LocalSocket."

ClamAV also provides the possibility to enable communication via remote locations by using a network socket which is configured and names as "TCPSocket".

Another important thing to note is that when using LocalSocket, then clamd will need to be run under a user with the right permissions to scan the files you plan on including in your monitoring.

## Configuration

Default configuration files should already exist. Otherwise, you can manually create them by using clamconf:

    # clamconf -g freshclam.conf > freshclam.conf
    # clamconf -g clamd.conf > clamd.conf
    # clamconf -g clamav-milter.conf > clamav-milter.conf

The following files contain the relevant configuration options.

- freshclam: `/etc/clamav/freshclam.conf`
- clamd: `/etc/clamav/clamd.conf`
- clamd mail filtering: `/etc/clamav/clamav-milter.conf`

Last but not least you can check your config files by running `clamconf`

The default installation will create "sane" default configurations such as: a clamav system user, a clamav group, and the required clamd configuration files.

Additional recommended configurations can be set:

    /etc/clamav/clamd.conf

    # Log time with each message.
    # Default: no
    LogTime yes

    # Log additional information about the infected file, such as its
    # size and hash, together with the virus name.
    ExtendedDetectionInfo yes

    # Run as another user (clamd must be started by root for this option to work)
    # Default: don't drop privileges
    User clamav

    # Maximum depth directories are scanned at.
    # Default: 15
    MaxDirectoryRecursion 20

    DetectPUA yes
    HeuristicAlerts yes
    ScanPE yes
    ScanELF yes
    ScanOLE2 yes
    ScanPDF yes
    ScanSWF yes
    ScanXMLDOCS yes
    ScanHWP3 yes
    ScanOneNote yes
    ScanMail yes
    ScanHTML yes
    ScanArchive yes
    Bytecode yes
    AlertBrokenExecutables yes
    AlertBrokenMedia yes
    AlertEncrypted yes
    AlertEncryptedArchive yes
    AlertEncryptedDoc yes
    AlertOLE2Macros yes
    AlertPartitionIntersection yes

### Enabling real-time protection OnAccessScan

On-access scanning is the real-time protection daemon which will scan the file while reading, writing or executing it. It can be configured to either notify on detection or prevent/block on detection.

Configuration OnAccessScan is done via editing the `/etc/clamav/clamd.conf` configuration file.

The following changes are required for OnAccessScan to work:

    /etc/clamav/clamd.conf

    # Exclude the UID of the scanner itself from checking, to prevent loops
    OnAccessExcludeUname clamav

The following additional changes are recommended and will put the On-Access Scanner into notify-only mode:

    /etc/clamav/clamd.conf

    # Set the mount point where to recursively perform the scan,
    # this could be every path or multiple path (one line for path)
    OnAccessMountPath /

    # Alternatively, add some directories instead of mount points
    # OnAccessIncludePath /home

    # Prevention doesn't work with OnAccessMountPath.
    # It works with OnAccessIncludePath, as long as /usr and /etc are not included.
    # Including /var while activating prevention is also not recommended, because
    # this would slow down package installation by a factor of 1000.
    OnAccessPrevention no

    # Perform scans on newly created, moved, or renamed files
    OnAccessExtraScanning yes

    # Optionallyexclude root-owned processes
    # OnAccessExcludeRootUID true

#### Creating desktop notifications for alerts

So far ClamAV will silently log any detection but not alert the user. A pop-up to alert the user on any detection can be added.

First add the following line to your clamd configuration:

    /etc/clamav/clamd.conf

    VirusEvent /etc/clamav/virus-event.bash

Next, allow the clamav user to run notify-send as any user with custom environment variables via sudo:

    /etc/sudoers.d/clamav

    clamav ALL = (ALL) NOPASSWD: SETENV: /usr/bin/notify-send

Next, create the file `/etc/clamav/virus-event.bash`, make it executable and add the following:

    /etc/clamav/virus-event.bash

    #!/bin/bash
    PATH=/usr/bin
    ALERT="Signature detected by clamav: $CLAM_VIRUSEVENT_VIRUSNAME in $CLAM_VIRUSEVENT_FILENAME"

    # Send an alert to all graphical users.
    for ADDRESS in /run/user/*; do
        USERID=${ADDRESS#/run/user/}
        /usr/bin/sudo -u "#$USERID" DBUS_SESSION_BUS_ADDRESS="unix:path=$ADDRESS/bus" PATH=${PATH} \
            /usr/bin/notify-send -u critical -i dialog-warning "Virus found!" "$ALERT"
    done

This allows you to change/specify the message when a virus has been detected by clamd's on-access scanning service.

By default, clamonacc passes clamav the names of just-accessed files for scanning. This is a problem, because files inaccessible to the clamav user cannot be scanned this way. Instead, it is possible to instruct clamonacc (which always runs as root) to use file descriptor passing. Edit `clamav-clamonacc.service` with the following:

    [Service]
    ExecStart=
    ExecStart=/usr/sbin/clamonacc -F --fdpass --log=/var/log/clamav/clamonacc.log

Lastly, you will need to start/enable or restart the `clamav-clamonacc.service` as well as the `clamav-daemon.service`

See: #Starting the ClamAV + OnAccessScanning daemon

If you get AppArmor denials about clamd, set the profile to a complain-only mode:

    # aa-complain clamd

## Updating database

Update the virus definitions with:

    # freshclam

If you are behind a proxy, edit `/etc/clamav/freshclam.conf` and update HTTPProxyServer, HTTPProxyPort, HTTPProxyUsername and HTTPProxyPassword.

The database files are saved in:

    /var/lib/clamav/daily.cvd
    /var/lib/clamav/main.cvd
    /var/lib/clamav/bytecode.cvd

For automatic updates first create and set the required freshclam.log file:

    touch /var/log/clamav/freshclam.log
    chmod 600 /var/log/clamav/freshclam.log
    chown clamav /var/log/clamav/freshclam.log

Start/enable `clamav-freshclam.service` or `clamav-freshclam-once.timer` so that the virus definitions are kept recent.

The `clamav-freshclam.service` launches `freshclam` in daemon mode, defaulting to 12 checks per day (every 2 hours). The frequency can be changed in `/etc/clamav/freshclam.conf`.

The `clamav-freshclam-once.timer` launches the `freshclam` check once per day. The frequency can be changed in `/usr/lib/systemd/system/clamav-freshclam-once.timer`.

Note

- Freshclam in daemon mode checks on every (service) start.
- Over 1 check per hour results in being blocked by the CDN for 24 hours.
- The `.timer` unit follows the set schedule, regardless of reboots or service restarts.
- You can add additional virus signature databases by following #Adding more databases/signatures repositories.

## Starting the ClamAV + OnAccessScanning daemon

This will load all virus signatures in RAM. As of February 2024 these signatures require at least 1.6GB of free RAM. Twice that amount of RAM is used shortly, during the periodic update of the signatures.

Note

- You will need to run `freshclam` before starting the service for the first time or you will run into trouble/errors which will prevent ClamAV from starting correctly.
- The daemon is not needed if you only want to perform stand-alone scans. See Scan for viruses below.
- The daemon is required for On-Access Scanning (see: #Enabling real-time protection OnAccessScan) and for the `clamav-milter` (see: #Using the milter).

The service is called `clamav-daemon.service`. Start it and enable it to start at boot.

Additionally start and enable `clamav-clamonacc.service` for real-time on access protection.

## Testing the software

In order to make sure ClamAV and the definitions are installed correctly, scan the EICAR test file (a harmless signature with no virus code) with clamscan.

    $ curl https://secure.eicar.org/eicar.com.txt | clamscan -

The output must include:

    stdin: Eicar-Test-Signature FOUND

### Real-time protection

You can download and save the eicar file in one of the directories you configured clamonacc to monitor. For example:

    $ cd /home/user/Downloads/
    $ wget https://secure.eicar.org/eicar.com.txt
    $ cat eicar.com.txt

## Adding more databases/signatures repositories

ClamAV can use databases/signature from other repositories or security vendors.

To add the most important ones in a single step, install python-fangfrischAUR (see online documentation). It will add signatures/databases from popular providers, e.g. MalwarePatrol, SecuriteInfo, Yara, Linux Malware Detect, etc.

Note You still must have the `clamav-freshclam.service` or `clamav-freshclam-once.timer` started in order to have official signature updates from ClamAV mirrors.

### Set up Fangfrisch

As a replacement for the now abandoned `clamav-unofficial-sigs`, Fangfrisch is more secure, flexible and convenient and requires very little configuration (`/etc/fangfrisch/fangfrisch.conf`).

Most importantly, `Fangfrisch` never needs to be run with root permissions, unlike `clamav-unofficial-sigs`.

Create database structure by running:

    [clamav]$ /usr/bin/fangfrisch --conf /etc/fangfrisch/fangfrisch.conf initdb

Enable the `fangfrisch.timer` (system-level).

## Scan for viruses

There are two options for on-demand scanning:

### Using the stand-alone scanner

`clamscan` can be used to scan certain files, home directories, or an entire system:

    $ clamscan myfile
    $ clamscan --recursive --infected /home/$USER
    # clamscan --recursive --infected --exclude-dir='^/sys|^/dev' /

If you would like `clamscan` to remove the infected file add to the command the `--remove` option, or you can use `--move=/dir` to quarantine them.

You may also want `clamscan` to scan larger files. In this case, append the options `--max-filesize=4000M` and `--max-scansize=4000M` to the command. '4000M' is the largest possible value, and may be lowered as necessary.

Using the `-l /path/to/file` option will print the `clamscan` logs to a text file for locating reported infections.

### Using the daemon

`clamdscan` is similar to the above but utilizes the daemon, which must be running for the command to work. Most options are ignored since the daemon reads the settings specified in `/etc/clamav/clamd.conf`.

### Using the milter

Milter will scan your mail server for email containing virus. Adjust `/etc/clamav/clamav-milter.conf` to your needs. For example:

    /etc/clamav/clamav-milter.conf

    MilterSocket /var/spool/postfix/private/clamav-milter
    MilterSocketMode 660
    FixStaleSocket yes
    User clamav
    MilterSocketGroup clamav
    PidFile /run/clamav/clamav-milter.pid
    TemporaryDirectory /tmp
    ClamdSocket unix:/run/clamav/clamd.ctl
    LogSyslog yes
    LogInfected Basic

Create `/etc/systemd/system/clamav-milter.service`:

    /etc/systemd/system/clamav-milter.service

    [Unit]
    Description='ClamAV Milter'
    After=clamav-daemon.service

    [Service]
    Type=forking
    ExecStart=/usr/bin/clamav-milter --config-file /etc/clamav/clamav-milter.conf
    Restart=Always

    [Install]
    WantedBy=multi-user.target

Your system may require a different `Restart=` directive. It is needed, for example, when an automatism like logrotate stops the service.

Enable and start `clamav-milter.service`.

For Postfix, add the following lines to `/etc/postfix/main.cf`:

    /etc/postfix/main.cf

    smtpd_milters = unix:private/clamav-milter
    milter_default_action = shutdown

`postfix` user must be added to the `clamav` group in order to access the `clamav-milter` unix socket:

    # usermod -aG clamav postfix

## Tips and tricks

### Run in multiple threads

#### Using clamscan

When scanning a file or directory from the command line with `clamscan`, only a single CPU thread is used. Though this results in a lower resource load ― which is sometimes useful when running a scan in the background ― it also results in longer scan times, especially when scanning a large directory or an external drive. As such, you may wish to speed up this process by utilizing as many CPU threads as possible.

`clamscan` is designed to be single-threaded, so `xargs` can be used to run the scan in parallel:

    $ find /home/$USER -type f -print0 | xargs -0 -P $(nproc) clamscan

In this example, the `-P` parameter for `xargs` runs `clamscan` in as many processes as there are CPUs (reported by `nproc`) at the same time. `--max-lines` and `--max-args` options will allow even finer control of batching the workload across the threads.

This will consume loads of RAM as all processes are individual and will load the signature files. A single thread will consume around 1G (or more) of RAM, and may hang your computer unless OOM is clever enough. You may want to consider using clamdscan instead.

#### Using clamdscan

If you already have `clamd` daemon running `clamdscan` can be used instead (see #Starting the ClamAV + OnAccessScanning daemon):

    $ clamdscan --multiscan --fdpass /home/$USER

Here the `--multiscan` parameter enables `clamd` to scan the contents of the directory in parallel using available threads. `--fdpass` parameter is required to pass the file descriptor permissions to `clamd` as the daemon is running under `clamav` user and group.

The number of available threads for `clamdscan` is determined in `/etc/clamav/clamd.conf` via `MaxThreads` parameter clamd.conf(5). Even though you may see that the number of `MaxThreads` specified is more than one (current default is 10), when you start the scan using `clamdscan` from command line and do not specify `--multiscan` option, only one effective CPU thread will be used for scanning.

#### Enabling network access via TCPSocket

Warning The `clamd` TCP port provides no authentication and no encryption. Never expose it to untrusted networks. Restrict access strictly to localhost or a trusted local network interface using firewall rules. For background see the ClamAV security blog post and the official documentation.

By default `clamd` communicates via a Unix domain socket (`/run/clamav/clamd.ctl`), which is sufficient for local clients on the same host. Enabling a TCP socket allows remote clients on a local network to submit files for scanning—useful for centralised scanning infrastructures.

In order to enable a TCP socket, the recommended approach is to let `clamd` bind TCP itself via `clamd.conf`, rather than relying on systemd socket activation for the TCP socket. Socket activation for TCP introduces ordering problems when binding to a non-loopback address: systemd `sockets.target` starts before the network is available, causing the socket unit to fail with `Cannot assign requested address`. Any attempt to add `After=network-online.target` to the socket unit creates an ordering cycle through systemd `basic.target`.

The Unix domain socket continues to use socket activation as before. Only TCP is handled differently.

##### Configuration

Step 1 — Add TCP binding to `/etc/clamav/clamd.conf`:

For loopback (same host only):

    /etc/clamav/clamd.conf

    TCPSocket 3310
    TCPAddr 127.0.0.1

For a specific local network interface (e.g. a trusted LAN or management network):

    /etc/clamav/clamd.conf

    TCPSocket 3310
    TCPAddr 192.168.0.199

Replace `192.168.0.199` with the IP address of the interface you want clamd to listen on. Never use `0.0.0.0` unless all interfaces are protected by a firewall.

Note

When binding to a non-loopback address, restrict access at the firewall level to port 3310.

Step 2 — Create a systemd service drop-in:

    /etc/systemd/system/clamav-daemon.service.d/override.conf

    [Unit]
    After=network-online.target
    Wants=network-online.target
    Requires=

    [Service]
    UnsetEnvironment=LISTEN_FDS LISTEN_PID LISTEN_FDNAMES

The three directives serve distinct purposes:

- `After=` / `Wants=network-online.target`
  ensures `clamd` starts only after the network interface is fully up and the IP address is available.
- `Requires=`
  clears the hard dependency on `clamav-daemon.socket`, allowing `clamd` to start independently.
- `UnsetEnvironment=`
  suppresses systemd's socket passing protocol. Without this, `clamd` detects the environment variables `LISTEN_FDS`, `LISTEN_PID`, and `LISTEN_FDNAMES` set by systemd and enters socket-activation mode, silently ignoring `TCPSocket`/`TCPAddr` from `clamd.conf` and logging: `TCP: No tcp AF_INET/AF_INET6 SOCK_STREAM socket received from systemd.`

Step 3 — Reload the systemd manager configuration and restart the `clamav-daemon` service.

Step 4 — Verify the configuration with:

    $ ss -tlnp | grep 3310

The expected output is (`clamd` owns the socket, `systemd` is not listed):

    tcp   LISTEN 0   200   192.168.0.199:3310   0.0.0.0:*   users:(("clamd",...))

## Troubleshooting

Note Make sure the user from which you are running `clamscan` has read permissions for the database files (`/var/lib/clamav/*.c?d`)

### 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:

Warning See the warning in #TCPSocket — Enabling Network Access for clamd about clamd port security.

    # touch /run/clamav/clamd.ctl
    # chown clamav:clamav /run/clamav/clamd.ctl

Then, edit `/etc/clamav/clamd.conf` - uncomment this line:

    LocalSocket /run/clamav/clamd.ctl

Save the file and restart `clamav-daemon.service`.

### 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 `/etc/clamav/freshclam.conf` setting `DatabaseDirectory` and `/etc/clamav/clamd.conf` setting `DatabaseDirectory`. `/etc/clamav/freshclam.conf` pointing to `/var/lib/clamav`, but `/etc/clamav/clamd.conf` (default directory) pointing to `/usr/share/clamav`, or other directory. Edit in `/etc/clamav/clamd.conf` and replace with the same `DatabaseDirectory` as in `/etc/clamav/freshclam.conf`. 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

### ClamOnAcc logfile bloating up to insane sizes and filling up completely with access denied errors

This is happening because of a issue with the stock clamav-clamonacc systemd unit. Modify /lib/modules/systemd/system/clamav-clamonacc.service to read

    ExecStart=/usr/sbin/clamonacc --fdpass -F --log=/var/log/clamav/clamonacc.log --move=/root/quarantine

This instructs clamonacc to pass the file descriptior to clamd who will then do the scan on it's behalf.

## See also

- Wikipedia:ClamAV

Category:

- Security

ClamAV
Add topic