1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
<?php
/**
* Abstraction for checking files with an external virus scanner.
* Supports connections via TCP or socket and is focused on using ClamAV at the moment.
* Derived from https://github.com/nextcloud/files_antivirus
*
* @author Thomas Hackl <hackl@data-quest.de>
* @author Sebastian Biller <s.biller@tu-braunschweig.de>
* @license GPL 2 or later
* @since 5.3
*/
class Virusscanner
{
// Contains the singleton used.
protected static $instance;
// Definitions for possible status.
public const SCANRESULT_UNCHECKED = -1;
public const SCANRESULT_CLEAN = 0;
public const SCANRESULT_INFECTED = 1;
/**
* Scans the given path for viruses.
*
* @param string $path
* @return array Contains the found virus signature, error message or is an empty array on successful scan
*/
public static function scan(string $path): array
{
// Get virus scanner singleton.
if (is_null(static::$instance)) {
static::$instance = new static();
}
$scanner = static::$instance;
try {
// Connect to scanner.
$handle = $scanner->connect();
// Read file.
$file = $scanner->readFile($path);
// ClamAV has a maximum stream length, so we need to track how much data has already been sent.
$bytesWritten = $scanner->sendContent($handle, "nINSTREAM\n");
// Send file chunks via socket or TCP.
while ($chunk = @fread($file, 8192)) {
$chunkLength = pack('N', strlen($chunk));
// Send next chunk.
if ($bytesWritten + strlen($chunk) <= Config::get()->VIRUSSCAN_MAX_STREAMLENGTH) {
$bytesWritten += $scanner->sendContent($handle, $chunkLength . $chunk);
// Stream limit will be reached: abort.
} else {
return [
'error' => _('Die Datei ist zu groß, um vom Virenscanner gelesen zu werden.')
];
}
}
fclose($file);
// All chunks have been sent - signal stream end and get scanner response.
$result = $scanner->finalize($handle);
// Nothing found.
if ($result['status'] == static::SCANRESULT_CLEAN) {
return [];
// Virus found or error.
} else if ($result['status'] == static::SCANRESULT_INFECTED) {
return [
'found' => $result['details']
];
} else {
return [
'error' => $result['details']
];
}
// There has been an error: send error message back.
} catch (Exception $e) {
return [
'error' => $e->getMessage()
];
}
return [];
}
/**
* Finalized constructor so that the instantition in scan() will never fail.
*/
protected final function __construct()
{
}
/**
* Establishes a connection to virus scanner via socket or TCP, depending on Stud.IP configuration.
*
* @return resource|null
*/
protected function connect()
{
$handle = false;
// Use socket connection.
if (Config::get()->VIRUSSCAN_SOCKET) {
$handle = @stream_socket_client('unix://' . Config::get()->VIRUSSCAN_SOCKET, $errno, $errstr, 5);
// use TCP connection.
} else if (Config::get()->VIRUSSCAN_HOST && Config::get()->VIRUSSCAN_PORT) {
$handle = @fsockopen(Config::get()->VIRUSSCAN_HOST, Config::get()->VIRUSSCAN_PORT);
}
if ($handle === false) {
throw new RuntimeException(_('Der Virenscanner ist nicht verfügbar.'));
}
return $handle;
}
/**
* Get contents of the file to scan.
*
* @param string $path
* @return resource
*/
protected function readFile(string $path)
{
$handle = fopen($path, 'r');
if ($handle === false) {
throw new RuntimeException(_('Die Datei kann nicht gelesen werden.'));
}
return $handle;
}
/**
* Send some content to the virus scanner.
*
* @param resource $handle
* @param string $content
* @return int
*/
protected function sendContent($handle, string $content): int
{
$written = @fwrite($handle, $content);
// An error has happened -> throw exception.
if ($written === false) {
throw new RuntimeException(_('Fehler bei der Kommunikation mit dem Virenscanner.'));
// Return written byte count.
} else {
return $written;
}
}
/**
* All file chunks have been sent: we now signal the end of the stream by sending a "0".
* Afterwarda, the response we got from virus scanner is parsed and (in case something was found)
* the name of the virus is returned.
*
* @param resource $handle
* @return array
*/
protected function finalize($handle): array
{
// End stream to socket or TCP endpoint.
$this->sendContent($handle, pack('N', 0));
// Fetch virus scanner response.
$response = fgets($handle);
fclose($handle);
// Parse response.
$matches = [];
// Possible response types.
$rules = [
[
'match' => '/.*: OK$/',
'status' => self::SCANRESULT_CLEAN
],
[
'match' => '/.*: (.*) FOUND$/',
'status' => self::SCANRESULT_INFECTED
],
[
'match' => '/.*: (.*) ERROR$/',
'status' => self::SCANRESULT_UNCHECKED
],
];
$status = static::SCANRESULT_UNCHECKED;
$details = _('Die Antwort des Virenscanners wurde nicht erkannt.');
foreach ($rules as $rule) {
if (preg_match($rule['match'], $response, $matches)) {
$status = (int) $rule['status'];
if ((int) $rule['status'] !== static::SCANRESULT_CLEAN) {
$details = $matches[1] ?? _('unbekannt');
} else {
$details = '';
}
break;
}
}
return [
'status' => $status,
'details' => $details
];
}
}
|