| 1 |
# Copyright 2024 Vsevolod Stakhov |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
# |
| 15 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 16 |
# you may not use this file except in compliance with the License. |
| 17 |
# You may obtain a copy of the License at |
| 18 |
# |
| 19 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 20 |
# |
| 21 |
# Unless required by applicable law or agreed to in writing, software |
| 22 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 23 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 24 |
# See the License for the specific language governing permissions and |
| 25 |
# limitations under the License. |
| 26 |
|
| 27 |
from urllib.request import urlopen |
| 28 |
import glob |
| 29 |
import grp |
| 30 |
import http.client |
| 31 |
import os |
| 32 |
import os.path |
| 33 |
import psutil |
| 34 |
import pwd |
| 35 |
import shutil |
| 36 |
import signal |
| 37 |
import socket |
| 38 |
import ssl |
| 39 |
import stat |
| 40 |
import subprocess |
| 41 |
import random |
| 42 |
import re |
| 43 |
import sys |
| 44 |
import tempfile |
| 45 |
|
| 46 |
from robot.api import logger |
| 47 |
from robot.libraries.BuiltIn import BuiltIn |
| 48 |
import json |
| 49 |
|
| 50 |
|
| 51 |
def Check_JSON(j): |
| 52 |
d = json.JSONDecoder(strict=True).decode(j.decode('utf-8')) |
| 53 |
logger.debug('got json %s' % d) |
| 54 |
assert len(d) > 0 |
| 55 |
assert 'error' not in d |
| 56 |
return d |
| 57 |
|
| 58 |
|
| 59 |
def check_json_log(fn): |
| 60 |
line_count = 0 |
| 61 |
f = open(fn, 'r', encoding="utf-8") |
| 62 |
for l in f.readlines(): |
| 63 |
d = json.JSONDecoder(strict=True).decode(l) |
| 64 |
assert len(d) > 0 |
| 65 |
line_count = line_count + 1 |
| 66 |
assert line_count > 0 |
| 67 |
|
| 68 |
|
| 69 |
def cleanup_temporary_directory(directory): |
| 70 |
shutil.rmtree(directory) |
| 71 |
|
| 72 |
|
| 73 |
def save_run_results(directory, filenames): |
| 74 |
current_directory = os.getcwd() |
| 75 |
suite_name = BuiltIn().get_variable_value("${SUITE_NAME}") |
| 76 |
test_name = BuiltIn().get_variable_value("${TEST NAME}") |
| 77 |
if os.path.exists(directory): |
| 78 |
onlyfiles = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] |
| 79 |
logger.debug('%s content before cleanup: %s' % (directory, onlyfiles)) |
| 80 |
if test_name is None: |
| 81 |
# this is suite-level tear down |
| 82 |
destination_directory = "%s/robot-save/%s" % (current_directory, suite_name) |
| 83 |
else: |
| 84 |
destination_directory = "%s/robot-save/%s/%s" % (current_directory, suite_name, test_name) |
| 85 |
if not os.path.isdir(destination_directory): |
| 86 |
os.makedirs(destination_directory) |
| 87 |
for file in filenames.split(' '): |
| 88 |
source_file = "%s/%s" % (directory, file) |
| 89 |
logger.debug('check if we can save %s' % source_file) |
| 90 |
if os.path.isfile(source_file): |
| 91 |
logger.debug('found %s, save it' % file) |
| 92 |
shutil.copy(source_file, "%s/%s" % (destination_directory, file)) |
| 93 |
shutil.copy(source_file, "%s/robot-save/%s.last" % (current_directory, file)) |
| 94 |
|
| 95 |
|
| 96 |
def encode_filename(filename): |
| 97 |
return "".join(['%%%0X' % ord(b) for b in filename]) |
| 98 |
|
| 99 |
|
| 100 |
def get_test_directory(): |
| 101 |
return os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "../../") |
| 102 |
|
| 103 |
|
| 104 |
def get_top_dir(): |
| 105 |
if os.environ.get('RSPAMD_TOPDIR'): |
| 106 |
return os.environ['RSPAMD_TOPDIR'] |
| 107 |
|
| 108 |
return get_test_directory() + "/../../" |
| 109 |
|
| 110 |
|
| 111 |
def get_install_root(): |
| 112 |
if os.environ.get('RSPAMD_INSTALLROOT'): |
| 113 |
return os.path.abspath(os.environ['RSPAMD_INSTALLROOT']) |
| 114 |
|
| 115 |
return os.path.abspath("../install/") |
| 116 |
|
| 117 |
|
| 118 |
def get_rspamd(): |
| 119 |
if os.environ.get('RSPAMD'): |
| 120 |
return os.environ['RSPAMD'] |
| 121 |
if os.environ.get('RSPAMD_INSTALLROOT'): |
| 122 |
return os.environ['RSPAMD_INSTALLROOT'] + "/bin/rspamd" |
| 123 |
dname = get_top_dir() |
| 124 |
return dname + "/src/rspamd" |
| 125 |
|
| 126 |
|
| 127 |
def get_rspamc(): |
| 128 |
if os.environ.get('RSPAMC'): |
| 129 |
return os.environ['RSPAMC'] |
| 130 |
if os.environ.get('RSPAMD_INSTALLROOT'): |
| 131 |
return os.environ['RSPAMD_INSTALLROOT'] + "/bin/rspamc" |
| 132 |
dname = get_top_dir() |
| 133 |
return dname + "/src/client/rspamc" |
| 134 |
|
| 135 |
|
| 136 |
def get_rspamadm(): |
| 137 |
if os.environ.get('RSPAMADM'): |
| 138 |
return os.environ['RSPAMADM'] |
| 139 |
if os.environ.get('RSPAMD_INSTALLROOT'): |
| 140 |
return os.environ['RSPAMD_INSTALLROOT'] + "/bin/rspamadm" |
| 141 |
dname = get_top_dir() |
| 142 |
return dname + "/src/rspamadm/rspamadm" |
| 143 |
|
| 144 |
|
| 145 |
def HTTP(method, host, port, path, data=None, headers={}): |
| 146 |
c = http.client.HTTPConnection("%s:%s" % (host, port)) |
| 147 |
c.request(method, path, data, headers) |
| 148 |
r = c.getresponse() |
| 149 |
t = r.read() |
| 150 |
s = r.status |
| 151 |
c.close() |
| 152 |
return [s, t] |
| 153 |
|
| 154 |
|
| 155 |
def HTTP_With_Headers(method, host, port, path, data=None, headers={}): |
| 156 |
"""HTTP request that returns response headers. |
| 157 |
Returns [status, body, headers_dict] |
| 158 |
""" |
| 159 |
c = http.client.HTTPConnection("%s:%s" % (host, port)) |
| 160 |
c.request(method, path, data, headers) |
| 161 |
r = c.getresponse() |
| 162 |
t = r.read() |
| 163 |
s = r.status |
| 164 |
h = dict(r.getheaders()) |
| 165 |
c.close() |
| 166 |
return [s, t, h] |
| 167 |
|
| 168 |
|
| 169 |
def HTTPS(method, host, port, path, data=None, headers={}): |
| 170 |
ctx = ssl.create_default_context() |
| 171 |
ctx.check_hostname = False |
| 172 |
ctx.verify_mode = ssl.CERT_NONE |
| 173 |
c = http.client.HTTPSConnection("%s:%s" % (host, port), context=ctx) |
| 174 |
c.request(method, path, data, headers) |
| 175 |
r = c.getresponse() |
| 176 |
t = r.read() |
| 177 |
s = r.status |
| 178 |
c.close() |
| 179 |
return [s, t] |
| 180 |
|
| 181 |
|
| 182 |
def HTTPS_With_Headers(method, host, port, path, data=None, headers={}): |
| 183 |
"""HTTPS request that returns response headers. |
| 184 |
Returns [status, body, headers_dict] |
| 185 |
""" |
| 186 |
ctx = ssl.create_default_context() |
| 187 |
ctx.check_hostname = False |
| 188 |
ctx.verify_mode = ssl.CERT_NONE |
| 189 |
c = http.client.HTTPSConnection("%s:%s" % (host, port), context=ctx) |
| 190 |
c.request(method, path, data, headers) |
| 191 |
r = c.getresponse() |
| 192 |
t = r.read() |
| 193 |
s = r.status |
| 194 |
h = dict(r.getheaders()) |
| 195 |
c.close() |
| 196 |
return [s, t, h] |
| 197 |
|
| 198 |
|
| 199 |
def generate_ssl_cert(tmpdir): |
| 200 |
"""Generate a self-signed EC certificate and key in tmpdir. |
| 201 |
Returns (cert_path, key_path). |
| 202 |
""" |
| 203 |
cert_path = os.path.join(tmpdir, "test-cert.pem") |
| 204 |
key_path = os.path.join(tmpdir, "test-key.pem") |
| 205 |
subprocess.check_call([ |
| 206 |
"openssl", "req", "-x509", "-newkey", "ec", |
| 207 |
"-pkeyopt", "ec_paramgen_curve:prime256v1", |
| 208 |
"-keyout", key_path, "-out", cert_path, |
| 209 |
"-days", "1", "-nodes", |
| 210 |
"-subj", "/CN=rspamd-test", |
| 211 |
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 212 |
# Make readable by rspamd worker (runs as nobody) |
| 213 |
os.chmod(cert_path, 0o644) |
| 214 |
os.chmod(key_path, 0o644) |
| 215 |
return cert_path, key_path |
| 216 |
|
| 217 |
|
| 218 |
def hard_link(src, dst): |
| 219 |
os.link(src, dst) |
| 220 |
|
| 221 |
|
| 222 |
def make_temporary_directory(): |
| 223 |
"""Creates and returns a unique temporary directory |
| 224 |
|
| 225 |
Example: |
| 226 |
| ${RSPAMD_TMPDIR} = | Make Temporary Directory | |
| 227 |
""" |
| 228 |
dirname = tempfile.mkdtemp() |
| 229 |
os.chmod(dirname, stat.S_IRUSR | |
| 230 |
stat.S_IXUSR | |
| 231 |
stat.S_IWUSR | |
| 232 |
stat.S_IRGRP | |
| 233 |
stat.S_IXGRP | |
| 234 |
stat.S_IROTH | |
| 235 |
stat.S_IXOTH) |
| 236 |
return dirname |
| 237 |
|
| 238 |
|
| 239 |
def make_temporary_file(): |
| 240 |
return tempfile.mktemp() |
| 241 |
|
| 242 |
|
| 243 |
def path_splitter(path): |
| 244 |
dirname = os.path.dirname(path) |
| 245 |
basename = os.path.basename(path) |
| 246 |
return [dirname, basename] |
| 247 |
|
| 248 |
|
| 249 |
def rspamc(addr, port, filename): |
| 250 |
mboxgoo = b"From MAILER-DAEMON Fri May 13 19:17:40 2016\r\n" |
| 251 |
goo = open(filename, 'rb').read() |
| 252 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 253 |
s.connect((addr, port)) |
| 254 |
s.send(b"CHECK RSPAMC/1.0\r\nContent-length: ") |
| 255 |
s.send(str(len(goo + mboxgoo)).encode('utf-8')) |
| 256 |
s.send(b"\r\n\r\n") |
| 257 |
s.send(mboxgoo) |
| 258 |
s.send(goo) |
| 259 |
data = b"" |
| 260 |
while True: |
| 261 |
chunk = s.recv(32768) |
| 262 |
if not chunk: |
| 263 |
break |
| 264 |
data += chunk |
| 265 |
s.close() |
| 266 |
return data.decode('utf-8') |
| 267 |
|
| 268 |
|
| 269 |
def Scan_File(filename, **headers): |
| 270 |
addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}") |
| 271 |
port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL}") |
| 272 |
headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}") |
| 273 |
c = http.client.HTTPConnection("%s:%s" % (addr, port)) |
| 274 |
c.request("POST", "/checkv2", open(filename, "rb"), headers) |
| 275 |
r = c.getresponse() |
| 276 |
assert r.status == 200 |
| 277 |
d = json.JSONDecoder(strict=True).decode(r.read().decode('utf-8')) |
| 278 |
c.close() |
| 279 |
BuiltIn().set_test_variable("${SCAN_RESULT}", d) |
| 280 |
return |
| 281 |
|
| 282 |
|
| 283 |
def _build_multipart(boundary, metadata_json, message_bytes): |
| 284 |
"""Build a multipart/form-data body with metadata and message parts.""" |
| 285 |
body = b"" |
| 286 |
body += ("--" + boundary + "\r\n").encode() |
| 287 |
body += b"Content-Disposition: form-data; name=\"metadata\"\r\n" |
| 288 |
body += b"Content-Type: application/json\r\n" |
| 289 |
body += b"\r\n" |
| 290 |
if isinstance(metadata_json, str): |
| 291 |
metadata_json = metadata_json.encode('utf-8') |
| 292 |
body += metadata_json |
| 293 |
body += b"\r\n" |
| 294 |
body += ("--" + boundary + "\r\n").encode() |
| 295 |
body += b"Content-Disposition: form-data; name=\"message\"\r\n" |
| 296 |
body += b"\r\n" |
| 297 |
if isinstance(message_bytes, str): |
| 298 |
message_bytes = message_bytes.encode('utf-8') |
| 299 |
body += message_bytes |
| 300 |
body += b"\r\n" |
| 301 |
body += ("--" + boundary + "--\r\n").encode() |
| 302 |
return body |
| 303 |
|
| 304 |
|
| 305 |
def _build_multipart_single(boundary, part_name, part_data, content_type=None): |
| 306 |
"""Build a multipart/form-data body with a single part.""" |
| 307 |
body = b"" |
| 308 |
body += ("--" + boundary + "\r\n").encode() |
| 309 |
body += ("Content-Disposition: form-data; name=\"%s\"\r\n" % part_name).encode() |
| 310 |
if content_type: |
| 311 |
body += ("Content-Type: %s\r\n" % content_type).encode() |
| 312 |
body += b"\r\n" |
| 313 |
if isinstance(part_data, str): |
| 314 |
part_data = part_data.encode('utf-8') |
| 315 |
body += part_data |
| 316 |
body += b"\r\n" |
| 317 |
body += ("--" + boundary + "--\r\n").encode() |
| 318 |
return body |
| 319 |
|
| 320 |
|
| 321 |
def _parse_multipart_response(body, content_type): |
| 322 |
"""Parse a multipart/mixed response and return the 'result' part data as string.""" |
| 323 |
if isinstance(body, bytes): |
| 324 |
body = body.decode('utf-8', errors='replace') |
| 325 |
|
| 326 |
# Extract boundary from Content-Type header |
| 327 |
m = re.search(r'boundary="?([^";]+)"?', content_type) |
| 328 |
if not m: |
| 329 |
raise ValueError("No boundary found in Content-Type: %s" % content_type) |
| 330 |
boundary = m.group(1) |
| 331 |
|
| 332 |
# Split on boundary |
| 333 |
parts = body.split("--" + boundary) |
| 334 |
for part in parts: |
| 335 |
if part.startswith("--"): |
| 336 |
continue # closing boundary |
| 337 |
if not part.strip(): |
| 338 |
continue |
| 339 |
|
| 340 |
# Split headers from body |
| 341 |
if "\r\n\r\n" in part: |
| 342 |
headers, data = part.split("\r\n\r\n", 1) |
| 343 |
elif "\n\n" in part: |
| 344 |
headers, data = part.split("\n\n", 1) |
| 345 |
else: |
| 346 |
continue |
| 347 |
|
| 348 |
# Check if this is the "result" part |
| 349 |
if 'name="result"' in headers: |
| 350 |
# Strip trailing \r\n |
| 351 |
data = data.rstrip("\r\n") |
| 352 |
return data |
| 353 |
|
| 354 |
raise ValueError("No 'result' part found in multipart response") |
| 355 |
|
| 356 |
|
| 357 |
def Scan_File_V3(filename, metadata=None, **headers): |
| 358 |
"""Send a /checkv3 multipart request and set ${SCAN_RESULT}.""" |
| 359 |
addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}") |
| 360 |
port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL}") |
| 361 |
|
| 362 |
meta = metadata if metadata else {} |
| 363 |
meta_json = json.dumps(meta) |
| 364 |
message_data = open(filename, "rb").read() |
| 365 |
|
| 366 |
boundary = "----rspamd-test-%016x" % random.getrandbits(64) |
| 367 |
body = _build_multipart(boundary, meta_json, message_data) |
| 368 |
|
| 369 |
headers["Content-Type"] = "multipart/form-data; boundary=" + boundary |
| 370 |
if "Queue-Id" not in headers: |
| 371 |
headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}") |
| 372 |
|
| 373 |
c = http.client.HTTPConnection("%s:%s" % (addr, port)) |
| 374 |
c.request("POST", "/checkv3", body, headers) |
| 375 |
r = c.getresponse() |
| 376 |
assert r.status == 200, "Expected HTTP 200 but got %d" % r.status |
| 377 |
|
| 378 |
resp_body = r.read() |
| 379 |
resp_ct = r.getheader("Content-Type", "") |
| 380 |
result_data = _parse_multipart_response(resp_body, resp_ct) |
| 381 |
|
| 382 |
d = json.JSONDecoder(strict=True).decode(result_data) |
| 383 |
c.close() |
| 384 |
BuiltIn().set_test_variable("${SCAN_RESULT}", d) |
| 385 |
return |
| 386 |
|
| 387 |
|
| 388 |
def Scan_File_V3_Expect_Error(filename, expected_status, metadata=None, |
| 389 |
body_override=None, content_type_override=None, |
| 390 |
**headers): |
| 391 |
"""Send a /checkv3 request and expect a specific HTTP error status.""" |
| 392 |
addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}") |
| 393 |
port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL}") |
| 394 |
|
| 395 |
boundary = "----rspamd-test-%016x" % random.getrandbits(64) |
| 396 |
|
| 397 |
if body_override is not None: |
| 398 |
body = body_override |
| 399 |
else: |
| 400 |
meta = metadata if metadata else {} |
| 401 |
meta_json = json.dumps(meta) |
| 402 |
message_data = open(filename, "rb").read() if filename else b"" |
| 403 |
body = _build_multipart(boundary, meta_json, message_data) |
| 404 |
|
| 405 |
if content_type_override: |
| 406 |
headers["Content-Type"] = content_type_override |
| 407 |
else: |
| 408 |
headers["Content-Type"] = "multipart/form-data; boundary=" + boundary |
| 409 |
|
| 410 |
if "Queue-Id" not in headers: |
| 411 |
headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}") |
| 412 |
|
| 413 |
c = http.client.HTTPConnection("%s:%s" % (addr, port)) |
| 414 |
c.request("POST", "/checkv3", body, headers) |
| 415 |
r = c.getresponse() |
| 416 |
actual_status = r.status |
| 417 |
r.read() |
| 418 |
c.close() |
| 419 |
assert actual_status == int(expected_status), \ |
| 420 |
"Expected HTTP %s but got %d" % (expected_status, actual_status) |
| 421 |
return |
| 422 |
|
| 423 |
|
| 424 |
def Scan_File_V3_Single_Part(part_name, part_data, content_type_part=None, **headers): |
| 425 |
"""Send a /checkv3 request with only a single part.""" |
| 426 |
addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}") |
| 427 |
port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL}") |
| 428 |
|
| 429 |
boundary = "----rspamd-test-%016x" % random.getrandbits(64) |
| 430 |
body = _build_multipart_single(boundary, part_name, part_data, content_type_part) |
| 431 |
|
| 432 |
headers["Content-Type"] = "multipart/form-data; boundary=" + boundary |
| 433 |
if "Queue-Id" not in headers: |
| 434 |
headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}") |
| 435 |
|
| 436 |
c = http.client.HTTPConnection("%s:%s" % (addr, port)) |
| 437 |
c.request("POST", "/checkv3", body, headers) |
| 438 |
r = c.getresponse() |
| 439 |
status = r.status |
| 440 |
r.read() |
| 441 |
c.close() |
| 442 |
return status |
| 443 |
|
| 444 |
|
| 445 |
def Scan_File_SSL(filename, port=None, **headers): |
| 446 |
"""Like Scan_File but over HTTPS (TLS) to the normal worker SSL port.""" |
| 447 |
addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}") |
| 448 |
if port is None: |
| 449 |
port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL_SSL}") |
| 450 |
headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}") |
| 451 |
ctx = ssl.create_default_context() |
| 452 |
ctx.check_hostname = False |
| 453 |
ctx.verify_mode = ssl.CERT_NONE |
| 454 |
c = http.client.HTTPSConnection("%s:%s" % (addr, port), context=ctx) |
| 455 |
c.request("POST", "/checkv2", open(filename, "rb"), headers) |
| 456 |
r = c.getresponse() |
| 457 |
assert r.status == 200, "Expected HTTP 200 but got %d" % r.status |
| 458 |
d = json.JSONDecoder(strict=True).decode(r.read().decode('utf-8')) |
| 459 |
c.close() |
| 460 |
BuiltIn().set_test_variable("${SCAN_RESULT}", d) |
| 461 |
return |
| 462 |
|
| 463 |
|
| 464 |
def Scan_File_V3_SSL(filename, port=None, metadata=None, **headers): |
| 465 |
"""Like Scan_File_V3 but over HTTPS (TLS).""" |
| 466 |
addr = BuiltIn().get_variable_value("${RSPAMD_LOCAL_ADDR}") |
| 467 |
if port is None: |
| 468 |
port = BuiltIn().get_variable_value("${RSPAMD_PORT_NORMAL_SSL}") |
| 469 |
|
| 470 |
meta = metadata if metadata else {} |
| 471 |
meta_json = json.dumps(meta) |
| 472 |
message_data = open(filename, "rb").read() |
| 473 |
|
| 474 |
boundary = "----rspamd-test-%016x" % random.getrandbits(64) |
| 475 |
body = _build_multipart(boundary, meta_json, message_data) |
| 476 |
|
| 477 |
headers["Content-Type"] = "multipart/form-data; boundary=" + boundary |
| 478 |
if "Queue-Id" not in headers: |
| 479 |
headers["Queue-Id"] = BuiltIn().get_variable_value("${TEST_NAME}") |
| 480 |
|
| 481 |
ctx = ssl.create_default_context() |
| 482 |
ctx.check_hostname = False |
| 483 |
ctx.verify_mode = ssl.CERT_NONE |
| 484 |
c = http.client.HTTPSConnection("%s:%s" % (addr, port), context=ctx) |
| 485 |
c.request("POST", "/checkv3", body, headers) |
| 486 |
r = c.getresponse() |
| 487 |
assert r.status == 200, "Expected HTTP 200 but got %d" % r.status |
| 488 |
|
| 489 |
resp_body = r.read() |
| 490 |
resp_ct = r.getheader("Content-Type", "") |
| 491 |
result_data = _parse_multipart_response(resp_body, resp_ct) |
| 492 |
|
| 493 |
d = json.JSONDecoder(strict=True).decode(result_data) |
| 494 |
c.close() |
| 495 |
BuiltIn().set_test_variable("${SCAN_RESULT}", d) |
| 496 |
return |
| 497 |
|
| 498 |
|
| 499 |
def Send_SIGUSR1(pid): |
| 500 |
pid = int(pid) |
| 501 |
os.kill(pid, signal.SIGUSR1) |
| 502 |
|
| 503 |
|
| 504 |
def set_directory_ownership(path, username, groupname): |
| 505 |
if os.getuid() == 0: |
| 506 |
uid = pwd.getpwnam(username).pw_uid |
| 507 |
gid = grp.getgrnam(groupname).gr_gid |
| 508 |
os.chown(path, uid, gid) |
| 509 |
|
| 510 |
|
| 511 |
def spamc(addr, port, filename): |
| 512 |
goo = open(filename, 'rb').read() |
| 513 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 514 |
s.connect((addr, port)) |
| 515 |
s.send(b"SYMBOLS SPAMC/1.0\r\nContent-length: ") |
| 516 |
s.send(str(len(goo)).encode('utf-8')) |
| 517 |
s.send(b"\r\n\r\n") |
| 518 |
s.send(goo) |
| 519 |
s.shutdown(socket.SHUT_WR) |
| 520 |
data = b"" |
| 521 |
while True: |
| 522 |
chunk = s.recv(32768) |
| 523 |
if not chunk: |
| 524 |
break |
| 525 |
data += chunk |
| 526 |
s.close() |
| 527 |
return data.decode('utf-8') |
| 528 |
|
| 529 |
|
| 530 |
def TCP_Connect(addr, port): |
| 531 |
"""Attempts to open a TCP connection to specified address:port |
| 532 |
|
| 533 |
Example: |
| 534 |
| Wait Until Keyword Succeeds | 5s | 10ms | TCP Connect | localhost | 8080 | |
| 535 |
""" |
| 536 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 537 |
s.settimeout(5) # seconds |
| 538 |
s.connect((addr, port)) |
| 539 |
s.close() |
| 540 |
|
| 541 |
|
| 542 |
def try_reap_zombies(): |
| 543 |
try: |
| 544 |
os.waitpid(-1, os.WNOHANG) |
| 545 |
except ChildProcessError: |
| 546 |
pass |
| 547 |
|
| 548 |
|
| 549 |
def ping_rspamd(addr, port): |
| 550 |
return str(urlopen("http://%s:%s/ping" % (addr, port)).read()) |
| 551 |
|
| 552 |
|
| 553 |
def redis_check(addr, port): |
| 554 |
"""Attempts to open a TCP connection to specified address:port |
| 555 |
|
| 556 |
Example: |
| 557 |
| Wait Until Keyword Succeeds | 5s | 10ms | TCP Connect | localhost | 8080 | |
| 558 |
""" |
| 559 |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 560 |
s.settimeout(1.0) # seconds |
| 561 |
s.connect((addr, port)) |
| 562 |
if s.sendall(b"ECHO TEST\n"): |
| 563 |
result = s.recv(128) |
| 564 |
return result == b'TEST\n' |
| 565 |
else: |
| 566 |
return False |
| 567 |
|
| 568 |
|
| 569 |
def update_dictionary(a, b): |
| 570 |
a.update(b) |
| 571 |
return a |
| 572 |
|
| 573 |
|
| 574 |
TERM_TIMEOUT = 10 # wait after sending a SIGTERM signal |
| 575 |
KILL_WAIT = 20 # additional wait after sending a SIGKILL signal |
| 576 |
|
| 577 |
|
| 578 |
def shutdown_process(process): |
| 579 |
# send SIGTERM |
| 580 |
process.terminate() |
| 581 |
|
| 582 |
try: |
| 583 |
process.wait(TERM_TIMEOUT) |
| 584 |
return |
| 585 |
except psutil.TimeoutExpired: |
| 586 |
logger.info("PID {} is not terminated in {} seconds, sending SIGKILL...".format(process.pid, TERM_TIMEOUT)) |
| 587 |
try: |
| 588 |
# send SIGKILL |
| 589 |
process.kill() |
| 590 |
except psutil.NoSuchProcess: |
| 591 |
# process exited just before we tried to kill |
| 592 |
return |
| 593 |
|
| 594 |
try: |
| 595 |
process.wait(KILL_WAIT) |
| 596 |
except psutil.TimeoutExpired: |
| 597 |
raise RuntimeError("Failed to shutdown process {} ({})".format(process.pid, process.name())) |
| 598 |
|
| 599 |
|
| 600 |
def shutdown_process_with_children(pid): |
| 601 |
pid = int(pid) |
| 602 |
try: |
| 603 |
process = psutil.Process(pid=pid) |
| 604 |
except psutil.NoSuchProcess: |
| 605 |
return |
| 606 |
children = process.children(recursive=True) |
| 607 |
shutdown_process(process) |
| 608 |
for child in children: |
| 609 |
try: |
| 610 |
child.kill() |
| 611 |
except psutil.NoSuchProcess: |
| 612 |
pass |
| 613 |
psutil.wait_procs(children, timeout=KILL_WAIT) |
| 614 |
|
| 615 |
|
| 616 |
def write_to_stdin(process_handle, text): |
| 617 |
if not isinstance(text, bytes): |
| 618 |
text = bytes(text, 'utf-8') |
| 619 |
lib = BuiltIn().get_library_instance('Process') |
| 620 |
obj = lib.get_process_object() |
| 621 |
obj.stdin.write(text + b"\n") |
| 622 |
obj.stdin.flush() |
| 623 |
obj.stdin.close() |
| 624 |
out = obj.stdout.read(4096) |
| 625 |
return out.decode('utf-8') |
| 626 |
|
| 627 |
|
| 628 |
def get_file_if_exists(file_path): |
| 629 |
if os.path.exists(file_path): |
| 630 |
with open(file_path, 'r') as myfile: |
| 631 |
return myfile.read() |
| 632 |
return None |
| 633 |
|
| 634 |
|
| 635 |
def _merge_luacov_stats(statsfile, coverage): |
| 636 |
""" |
| 637 |
Reads a coverage stats file written by luacov and merges coverage data to |
| 638 |
'coverage' dict: { src_file: hits_list } |
| 639 |
|
| 640 |
Format of the file defined in: |
| 641 |
https://github.com/keplerproject/luacov/blob/master/src/luacov/stats.lua |
| 642 |
""" |
| 643 |
with open(statsfile, 'r') as fh: |
| 644 |
while True: |
| 645 |
# max_line:filename |
| 646 |
line = fh.readline().rstrip() |
| 647 |
if not line: |
| 648 |
break |
| 649 |
|
| 650 |
max_line, src_file = line.split(':') |
| 651 |
counts = [int(x) for x in fh.readline().split()] |
| 652 |
assert len(counts) == int(max_line) |
| 653 |
|
| 654 |
if src_file in coverage: |
| 655 |
# enlarge list if needed: lenght of list in different luacov.stats.out files may differ |
| 656 |
old_len = len(coverage[src_file]) |
| 657 |
new_len = len(counts) |
| 658 |
if new_len > old_len: |
| 659 |
coverage[src_file].extend([0] * (new_len - old_len)) |
| 660 |
# sum execution counts for each line |
| 661 |
for l, exe_cnt in enumerate(counts): |
| 662 |
coverage[src_file][l] += exe_cnt |
| 663 |
else: |
| 664 |
coverage[src_file] = counts |
| 665 |
|
| 666 |
|
| 667 |
def _dump_luacov_stats(statsfile, coverage): |
| 668 |
""" |
| 669 |
Saves data to the luacov stats file. Existing file is overwritted if exists. |
| 670 |
""" |
| 671 |
src_files = sorted(coverage) |
| 672 |
|
| 673 |
with open(statsfile, 'w') as fh: |
| 674 |
for src in src_files: |
| 675 |
stats = " ".join(str(n) for n in coverage[src]) |
| 676 |
fh.write("%s:%s\n%s\n" % (len(coverage[src]), src, stats)) |
| 677 |
|
| 678 |
|
| 679 |
# File used by luacov to collect coverage stats |
| 680 |
LUA_STATSFILE = "luacov.stats.out" |
| 681 |
|
| 682 |
|
| 683 |
def collect_lua_coverage(): |
| 684 |
""" |
| 685 |
Merges ${RSPAMD_TMPDIR}/*.luacov.stats.out into luacov.stats.out |
| 686 |
|
| 687 |
Example: |
| 688 |
| Collect Lua Coverage | |
| 689 |
""" |
| 690 |
# decided not to do optional coverage so far |
| 691 |
# if not 'ENABLE_LUA_COVERAGE' in os.environ['HOME']: |
| 692 |
# logger.info("ENABLE_LUA_COVERAGE is not present in env, will not collect Lua coverage") |
| 693 |
# return |
| 694 |
|
| 695 |
tmp_dir = BuiltIn().get_variable_value("${RSPAMD_TMPDIR}") |
| 696 |
|
| 697 |
coverage = {} |
| 698 |
input_files = [] |
| 699 |
|
| 700 |
for f in glob.iglob("%s/*.luacov.stats.out" % tmp_dir): |
| 701 |
_merge_luacov_stats(f, coverage) |
| 702 |
input_files.append(f) |
| 703 |
|
| 704 |
if input_files: |
| 705 |
if os.path.isfile(LUA_STATSFILE): |
| 706 |
_merge_luacov_stats(LUA_STATSFILE, coverage) |
| 707 |
_dump_luacov_stats(LUA_STATSFILE, coverage) |
| 708 |
logger.info("%s merged into %s" % (", ".join(input_files), LUA_STATSFILE)) |
| 709 |
else: |
| 710 |
logger.info("no *.luacov.stats.out files found in %s" % tmp_dir) |
| 711 |
|
| 712 |
|
| 713 |
def file_exists(file): |
| 714 |
return os.path.isfile(file) |
| 715 |
|
| 716 |
|
| 717 |
def redis_stream_read_msgpack(host, port, stream_key): |
| 718 |
"""Read latest entry from Redis stream and decode msgpack data. |
| 719 |
|
| 720 |
Returns decoded dict with metadata fields. |
| 721 |
|
| 722 |
Example: |
| 723 |
| ${data} = | Redis Stream Read Msgpack | ${RSPAMD_REDIS_ADDR} | ${RSPAMD_REDIS_PORT} | test:structured | |
| 724 |
""" |
| 725 |
try: |
| 726 |
import redis |
| 727 |
except ImportError: |
| 728 |
raise Exception("redis module not installed - run: pip install redis") |
| 729 |
|
| 730 |
try: |
| 731 |
import msgpack |
| 732 |
except ImportError: |
| 733 |
raise Exception("msgpack module not installed - run: pip install msgpack") |
| 734 |
|
| 735 |
r = redis.Redis(host=host, port=int(port), decode_responses=False) |
| 736 |
|
| 737 |
# Read from stream |
| 738 |
entries = r.xrange(stream_key, count=1) |
| 739 |
if not entries: |
| 740 |
raise Exception(f"No data in stream {stream_key}") |
| 741 |
|
| 742 |
# Get the first entry's data field |
| 743 |
entry_id, fields = entries[0] |
| 744 |
if b'data' not in fields: |
| 745 |
raise Exception(f"No data field in stream entry, keys: {list(fields.keys())}") |
| 746 |
|
| 747 |
msgpack_data = fields[b'data'] |
| 748 |
|
| 749 |
# Decode msgpack with raw=True to preserve bytes, then convert what we can |
| 750 |
decoded = msgpack.unpackb(msgpack_data, raw=True) |
| 751 |
|
| 752 |
# Convert bytes keys to strings for easier access |
| 753 |
def convert_keys(obj): |
| 754 |
if isinstance(obj, dict): |
| 755 |
return {k.decode('utf-8') if isinstance(k, bytes) else k: convert_keys(v) for k, v in obj.items()} |
| 756 |
elif isinstance(obj, list): |
| 757 |
return [convert_keys(item) for item in obj] |
| 758 |
elif isinstance(obj, bytes): |
| 759 |
# Try to decode as UTF-8, otherwise keep as bytes |
| 760 |
try: |
| 761 |
return obj.decode('utf-8') |
| 762 |
except UnicodeDecodeError: |
| 763 |
return obj |
| 764 |
return obj |
| 765 |
|
| 766 |
return convert_keys(decoded) |
| 767 |
|
| 768 |
|
| 769 |
def validate_structured_metadata(data, expected_fields=None): |
| 770 |
"""Validate structured metadata export format. |
| 771 |
|
| 772 |
Checks that required fields exist and UUID v7 has correct format. |
| 773 |
|
| 774 |
Example: |
| 775 |
| Validate Structured Metadata | ${data} | uuid,ip,score,action | |
| 776 |
""" |
| 777 |
import re |
| 778 |
|
| 779 |
if expected_fields is None: |
| 780 |
expected_fields = 'uuid,ip,score,action' |
| 781 |
|
| 782 |
errors = [] |
| 783 |
|
| 784 |
for field in expected_fields.split(','): |
| 785 |
field = field.strip() |
| 786 |
if field not in data: |
| 787 |
errors.append(f"Missing field: {field}") |
| 788 |
|
| 789 |
# Validate UUID v7 format if present |
| 790 |
if 'uuid' in data: |
| 791 |
uuid = data['uuid'] |
| 792 |
# UUID v7: xxxxxxxx-xxxx-7xxx-xxxx-xxxxxxxxxxxx |
| 793 |
if not re.match(r'^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', str(uuid)): |
| 794 |
errors.append(f"Invalid UUID v7 format: {uuid}") |
| 795 |
|
| 796 |
if errors: |
| 797 |
raise Exception("Validation errors: " + "; ".join(errors)) |
| 798 |
|
| 799 |
return True |
| 800 |
|
| 801 |
|
| 802 |
def validate_zstd_compressed_fields(data): |
| 803 |
"""Validate that zstd compression markers are set correctly. |
| 804 |
|
| 805 |
Returns count of compressed fields found. |
| 806 |
|
| 807 |
Example: |
| 808 |
| ${count} = | Validate Zstd Compressed Fields | ${data} | |
| 809 |
""" |
| 810 |
count = 0 |
| 811 |
|
| 812 |
# Check text_compressed flag |
| 813 |
if data.get('text_compressed'): |
| 814 |
count += 1 |
| 815 |
|
| 816 |
# Check attachments |
| 817 |
for att in data.get('attachments', []): |
| 818 |
if att.get('content_compressed'): |
| 819 |
count += 1 |
| 820 |
|
| 821 |
# Check images |
| 822 |
for img in data.get('images', []): |
| 823 |
if img.get('content_compressed'): |
| 824 |
count += 1 |
| 825 |
|
| 826 |
return count |
| 827 |
|
| 828 |
|
| 829 |
def validate_attachments_have_content_type(data): |
| 830 |
"""Validate that attachments have content_type field. |
| 831 |
|
| 832 |
Returns count of attachments with content_type. |
| 833 |
|
| 834 |
Example: |
| 835 |
| ${count} = | Validate Attachments Have Content Type | ${data} | |
| 836 |
""" |
| 837 |
count = 0 |
| 838 |
for att in data.get('attachments', []): |
| 839 |
if 'content_type' in att and att['content_type']: |
| 840 |
count += 1 |
| 841 |
return count |