Giter Club home page Giter Club logo

clamav-client's Introduction

Java ClamAV Client Library

Build Status Maven Central

A simple yet efficient Java client library for the ClamAV antivirus daemon.

Pre-requisites

This library requires a JDK version 8.

Installing

With Maven

Add this dependency to the <dependencies> section of your pom.xml file:

<dependency>
    <groupId>xyz.capybara</groupId>
    <artifactId>clamav-client</artifactId>
    <version>2.1.3</version>
</dependency>

With Gradle

Add this dependency to the dependencies section of your build.gradle file:

compile 'xyz.capybara:clamav-client:2.1.3'

Manually

Alternatively, you can download the jar file of this library directly from the Maven Central Repository website and add it to the classpath of your application: Download page.

Usage

After the library has been added to your build, start by creating an instance:

ClamavClient client = new ClamavClient("localhost");

By default, the client will try to connect to the port 3310 which is the default ClamAV daemon port.

If your ClamAV daemon listens to another port, you can indicate it with:

ClamavClient client = new ClamavClient("localhost", 3311);

Be careful if you intend to use the functionality of scan of a file/directory on the server filesystem and if the ClamAV daemon is running on an OS having a different path separator than the OS on which your Java application is running. (for example, if your Java application is running on a Windows platform but the ClamAV daemon is running on a remote UNIX platform)

You will then have to explicitly indicate the target server platform to the client library at instantiation:

ClamavClient client = new ClamavClient("localhost", Platform.UNIX);

// Or with an alternate port number:
ClamavClient client = new ClamavClient("localhost", 3311, Platform.UNIX);

By default, the chosen file separator will be the one of the platform your Java application is running on.

Commands

Scan commands

ScanResult scan(InputStream inputStream, Integer chunkSize)

Scans an InputStream and sends a response as soon as a virus has been found. The chunkSize can be used to control the size of the chunk sent to ClamAV. Defaults to 2048 bytes

ScanResult scan(Path path)

Scans a file/directory on the filesystem of the ClamAV daemon and sends a response as soon as a virus has been found.

ScanResult scan(Path path, boolean continueScan)

Scans a file/directory on the filesystem of the ClamAV daemon and may continue the scan to the end even if a virus has been found, depending on the continueScan argument.

ScanResult parallelScan(Path path)

Scans a file/directory on the filesystem of the ClamAV daemon and will continue the scan to the end even if a virus has been found. This method may improve performances on SMP systems by performing a multi-threaded scan.

Scan result

The ScanResult object returned by the scan commands can be of two types:

  1. OK: if no viruses have been found,
  2. VirusFound: if viruses have been found. Information about the infected files are stored in the foundViruses member map filled as following:
  • Key: infected file path
  • Value: list of viruses found in the file

Usage of the scan result

In Java:

if (scanResult instanceof ScanResult.OK) {
    // OK
} else if (scanResult instanceof ScanResult.VirusFound) {
    Map<String, Collection<String>> viruses = ((ScanResult.VirusFound) scanResult).getFoundViruses();
}

The same code in Kotlin would be much more readable, thanks to the when keyword and the smart-casting ability of the language:

when (scanResult) {
    is ScanResult.OK -> // OK
    is ScanResult.VirusFound -> scanResult.foundViruses
}

Admin commands

void reloadVirusDatabases()

Triggers the virus databases reloading by the ClamAV daemon.

void shutdownServer()

Immediately shutdowns the ClamAV daemon.

Other commands

void ping()

Pings the ClamAV daemon. If a correct response has been received, the method simply returns. Otherwise, a ClamavException exception is thrown.

String version()

Requests the version of the ClamAV daemon.

String stats()

Requests stats from the ClamAV daemon.

Building from sources

To build this library from its sources, an installation of Maven is required. Clone this repository and launch its build with the Maven command:

mvn clean package

If the build is successful, the jar file of the library will be found into the target directory.

Contributing

Feel free to fork this repository and submit pull requests :)

You can also submit issues in case of bugs or feature requests.

Licensing

The code in this project is licensed under MIT license. The content of the license can be found in the LICENSE file under the root of this repository.

clamav-client's People

Contributors

cdarras avatar dependabot[bot] avatar rasenderhase avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clamav-client's Issues

Thread safe

Is this library free threading? Or do I need to create an instance per thread?

FEATURE: Automatic connection failover

We are using this library within a container environment and it works great so far.
The problem is, it seems that the connection does not recover if the targeted ClamAV pod is down.

Is some kind of failover implemented and needs to be configured or is that just missing.

If so - it would be really cool to have that for production grade maturity.

πŸ™

Make stream scanning chunk size parametrizable

Currently the chunk size is fixed at 2048 bytes. For scanning large files this creates quite a bit of overhead (on our infrastructure e.g. a 70Mb file takes ~50 sec to scan with the default chunk size, where as with a 1Mb chunk size it takes about 15 sec.) Would a PR that makes this value parametrizable (with default left as is at 2048) be accepted ?

ClamavClient constructor is not recognized.

A simple constructor (following code):
ClamavClient clamClient = new ClamavClient('localhost', Platform.UNIX)
Throws this error:

groovy.lang.GroovyRuntimeException: Could not find matching constructor for: xyz.capybara.clamav.ClamavClient(java.lang.String, java.lang.Class)

In grails 3.2.11.

Encounter xyz.capybara.clamav.CommunicationException when scan file more than 25M

Hello,
When I scan some small files(10k, 10M), the code is ok.
when I scan some large files(25M, 50M, 56M), encounter below exceptions every time. Could you please help fix it? Thanks.

2022/03/08-18:14:40 [http-nio-9200-exec-2] INFO - scan start time: 2022-03-08 10:14:40.011, fileName: test.txt, fileSize: 10
2022/03/08-18:14:41 [http-nio-9200-exec-2] INFO - scan end time: 2022-03-08 10:14:41.433
2022/03/08-18:14:41 [http-nio-9200-exec-2] INFO - scan succeeded
2022/03/08-18:14:41 [http-nio-9200-exec-2] INFO - scan start time: 2022-03-08 10:14:41.435, fileName: 25m.pdf, fileSize: 26536474
2022/03/08-18:15:18 [http-nio-9200-exec-1] INFO - scan end time: 2022-03-08 10:15:18.583, with exception {}
xyz.capybara.clamav.ClamavException: xyz.capybara.clamav.CommunicationException: Error while communicating with the server
at xyz.capybara.clamav.ClamavClient.sendCommand(ClamavClient.kt:164)
at xyz.capybara.clamav.ClamavClient.scan(ClamavClient.kt:106)
......
Caused by: xyz.capybara.clamav.CommunicationException: Error while communicating with the server
at xyz.capybara.clamav.commands.scan.InStream.send(InStream.kt:50)
at xyz.capybara.clamav.commands.scan.InStream.send(InStream.kt:14)
at xyz.capybara.clamav.ClamavClient.sendCommand(ClamavClient.kt:160)
... 67 common frames omitted
Caused by: java.io.IOException: ????????????????????
at sun.nio.ch.SocketDispatcher.write0(Native Method)
at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
at sun.nio.ch.IOUtil.write(IOUtil.java:65)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
at xyz.capybara.clamav.commands.scan.InStream.send(InStream.kt:39)
... 69 common frames omitted

Result failed if scanned via Stream - INSTREAM Command

The Result looks something like this:
"stream: Eicar-Test-Signature FOUND"

The Pattern searches for a "filePath" Group but has none and throw a IllegalStateException -> Not Found Exception.

Pattern:
(.+: )?(?<filePath>.+): (?<virus>.+) FOUND$

Code Line:
return new VirusInfo(matcher.group("filePath"), matcher.group("virus"));

ClamAv Version: 0.99

ScanResult not having any properties (java environment)

Hi.

After upgrading from version 2.0.0 to 2.1.2, the ScanResult does not anymore have any fields.

In version 2.0.0, I could get use the "getStatus()" and the "getFoundViruses()" method.
Is there any workaround for version 2.1.2?

image

Compress file scan seems not working

The test viruses I downloaded from eicar site was compressed into a single zip file. My realtime protection (Antivirus was turned off all throughout). I tried scanning the compressed file but is seems it is returning OK result. Not sure though if I try a real virus compressed file. Btw, my clamd is updated.

Not sure if there is something I need to do in the code for it to scan the compressed files.

Thanks

Ping Timeout Issue - Destination Host Unreachable

This is a comment for improvement based on the following fairly common scenario.

User uploads a document to our web application, and the upload is BLOCKED if the file is flagged by Clam AV . HOWEVER if the ClamAV service is OFFLINE, we DONT BLOCK the upload operation, (bad user experience) we allow the upload to continue, and flag the file as requiring a seperate scan at a latter date

To achieve this we need a way of determining if ClamAV is available. The in built ping() command, unfortunately has a long timeout (> 1 minute) when the destination host is unreadable. To overcome this. the following code was used. It would be better if tis code was made part of (at least the function) the the ClamAV client library

fun ClamavClient.isReachable(timeout: Int) : Boolean {
    return try {
        // perform an independent socket connection with a connection timeout.
        return SelectorProvider.provider().openSocketChannel().use {
            it.configureBlocking(true)
            it.socket().use {
                it.connect(this.server, timeout)
                true
            }
        }
    } catch (e: SocketTimeoutException) {
        false
    }
}

CVE-2022-24329 - JetBrains Kotlin dependency of ClamAV-client

Hi Team,

We are seeing a security vulnerability (CVE-2022-24329 - JetBrains Kotlin dependency of ClamAV-client) on the clamav client library. Please let us know if this vulnerability issue has been fixed or not. If yes, please share the clamav-client library version to overcome this vulnerability.

image

Thanks in advance.

Nextcloud Snap Cannot connect to β€œ/var/run/clamav/clamd.ctl”: Permission denied (code 13)

Hallo liebe Community,

ich habe auf einem Ubuntu 22.04 per SNAP-Installation die Nextcloud installiert.
Jedoch bekomme ich ClamAV nicht korrekt zum laufen.

Fehler:
Cannot connect to β€œ/var/run/clamav/clamd.ctl”: Permission denied (code 13)
stream_socket_client(): Unable to connect to unix:///var/run/clamav/clamd.ctl (Permission denied) at /var/snap/nextcloud/39212/nextcloud/extra-apps/files_antivirus/lib/Scanner/ExternalClam.php#38

Meine /etc/clamav/clamd.conf:
LocalSocket /var/run/clamav/clamd.ctl
FixStaleSocket true
LocalSocketGroup clamav
LocalSocketMode 666
User clamav
…

systemctl status clamav-daemon:
clamav-daemon.service - Clam AntiVirus userspace daemon
Loaded: loaded (/lib/systemd/system/clamav-daemon.service; enabled; vendor preset: enabled)
Drop-In: /etc/systemd/system/clamav-daemon.service.d
└─extend.conf
Active: active (running) since Fri 2024-01-05 12:44:57 CET; 4min 40s ago
Docs: man:clamd(8)
man:clamd.conf(5)
https://docs.clamav.net/
Process: 1017 ExecStartPre=/bin/mkdir -p /run/clamav (code=exited, status=0/SUCCESS)
Process: 1049 ExecStartPre=/bin/chown clamav /run/clamav (code=exited, status=0/SUCCESS)
Main PID: 1051 (clamd)
Tasks: 2 (limit: 4558)
Memory: 1.6G
CPU: 19.715s
CGroup: /system.slice/clamav-daemon.service
└─1051 /usr/sbin/clamd --foreground=true

Jan 05 12:45:22 owncloud clamd[1051]: Portable Executable support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: ELF support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: Mail files support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: OLE2 support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: PDF support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: SWF support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: HTML support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: XMLDOCS support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: HWP3 support enabled.
Jan 05 12:45:22 owncloud clamd[1051]: Self checking every 300 seconds.

Nextcloud Antiviruseinstellungen sind auf:
Modus: ClamAV-Daemon-Socket
Socket: /var/run/clamav/clamd.ctl

ll /var/run/clamav/clamd.ctl
srw-rw-rw- 1 clamav clamav 0 Jan 5 12:45 /var/run/clamav/clamd.ctl=

Auch diese Anleitung bringt den gleichen Fehler.
Add /{,var/}snap/nextcloud/[0-9]/clamd.ctl w, to /etc/apparmor.d/usr.sbin.clamd like below.
32 /{,var/}run/clamav/clamd.ctl w,
33 /{,var/}snap/nextcloud/[0-9]/clamd.ctl w,
34 /{,var/}run/clamav/clamd.pid w,

then apply it to apparmor:
sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.clamd

edit /etc/clamav/clamd.conf and change it to this (LocalSocket, LocalSocketGroup, User):
…
4 LocalSocket /var/snap/nextcloud/current/clamd.ctl
5 FixStaleSocket true
6 #LocalSocketGroup clamav
7 LocalSocketGroup root
8 LocalSocketMode 666
9 # TemporaryDirectory is not set to its default /tmp here to make overriding
10 # the default with environment variables TMPDIR/TMP/TEMP possible
11 #User clamav
12 User root
13 ScanMail tr
…

restart clamav:
sudo systemctl restart clamav-daemon

sudo mv /var/run/clamav/clamd.ctl /var/snap/nextcloud/current/

Change LocalSocket option of /etc/clamav/clamd.conf and restart clamav-daemon:
LocalSocket /var/snap/nextcloud/current/clamd.ctl
sudo snap restart nextcloud

scan time different between the first scan time and after.

Hello,
Could you please tell me why the first time scan time is much longer than the second , third... scan time for the same file?
And do you have any suggestions to shorten the first time scan time?

(ps:The clamav service was not restarted, uploaded the same file(25m.pdf 47m.pptx) again ten hours later, there is still a gap between the first scan time and after.)

图片

Thanks.

Scanning across chunks

When a EICR text is spread across two chunks, how I can make sure it is scanning property? How to test this scenario please ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.