Debian Codegraph @

cvdupdate/cvdupdate.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Copyright (C) 2021-2025 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
3
4 This module provides a tool to download and update clamav databases and database
5 patch files (CDIFFs) for the purposes of hosting your own database mirror.
6
7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10
11 http://www.apache.org/licenses/LICENSE-2.0
12
13 Unless required by applicable law or agreed to in writing, software
14 distributed under the License is distributed on an "AS IS" BASIS,
15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 See the License for the specific language governing permissions and
17 limitations under the License.
18 """
19
20 import copy
21 import datetime
22 import http.client as http_client
23 import json
24 import logging
25 import os
26 import platform
27 import re
28 import subprocess
29 import sys
30 import time
31 import uuid
32 from enum import Enum
33 from pathlib import Path
34 from typing import *
35
36 try:
37 from importlib.metadata import PackageNotFoundError, version as _get_version
38 except ImportError: # pragma: no cover - backport for older Pythons
39 from importlib_metadata import PackageNotFoundError, version as _get_version
40 try:
41 import requests
42 except ModuleNotFoundError:
43 class _RequestsMissing:
44 def __getattr__(self, name):
45 raise ModuleNotFoundError(
46 "The 'requests' package is required to perform network operations. "
47 "Install it with 'pip install requests'."
48 )
49 requests = _RequestsMissing()
50 try:
51 from dns import resolver
52 except ModuleNotFoundError:
53 class _DNSMissing:
54 def __getattr__(self, name):
55 raise ModuleNotFoundError(
56 "The 'dnspython' package is required for DNS lookups. "
57 "Install it with 'pip install dnspython'."
58 )
59 resolver = _DNSMissing()
60 from packaging import version
61
62 class CvdStatus(Enum):
63 NO_UPDATE = 0
64 UPDATED = 1
65 ERROR = 2
66
67 class CVDUpdate:
68
69 default_config_path: Path = Path.home() / ".cvdupdate" / "config.json"
70
71 default_config: dict = {
72 "nameserver" : "",
73 "max retry" : 3, # No `cvd config set` option to set this, because we don't
74 # _really_ want people hammering the CDN with partial downloads.
75
76 "log directory" : str(Path.home() / ".cvdupdate" / "logs"),
77 "rotate logs" : True,
78 "# logs to keep" : 30,
79
80 "db directory" : str(Path.home() / ".cvdupdate" / "database"),
81 "rotate cdiffs" : True,
82 "# cdiffs to keep" : 30,
83 "state file": "",
84 }
85
86 default_state: dict = {
87 "dbs" : {
88 "main.cvd" : {
89 "url" : "https://database.clamav.net/main.cvd",
90 "retry after" : 0,
91 "last modified" : 0,
92 "last checked" : 0,
93 "DNS field" : 1, # only for CVDs
94 "local version" : 0, # only for CVDs
95 "CDIFFs" : [] # only for CVDs
96 },
97 "daily.cvd" : {
98 "url" : "https://database.clamav.net/daily.cvd",
99 "retry after" : 0,
100 "last modified" : 0,
101 "last checked" : 0,
102 "DNS field" : 2,
103 "local version" : 0,
104 "CDIFFs" : []
105 },
106 "bytecode.cvd" : {
107 "url" : "https://database.clamav.net/bytecode.cvd",
108 "retry after" : 0,
109 "last modified" : 0,
110 "last checked" : 0,
111 "DNS field" : 7,
112 "local version" : 0,
113 "CDIFFs" : []
114 },
115 },
116 }
117
118 config_path: Path
119 config: dict
120 state: dict
121 db_dir: Path
122 log_dir: Path
123 version: str
124
125 def __init__(
126 self,
127 config: str = "",
128 log_dir: str = "",
129 db_dir: str = "",
130 nameserver: str = "",
131 verbose: bool = False,
132 ) -> None:
133 """
134 CVDUpdate class.
135
136 Args:
137 log_dir: path output log.
138 db_dir: path where databases will be downloaded.
139 verbose: Enable DEBUG-level logs and other verbose messages.
140 """
141 try:
142 self.version = _get_version('cvdupdate')
143 except PackageNotFoundError:
144 self.version = "0.0"
145 self.verbose = verbose
146 self._read_config(
147 config,
148 db_dir,
149 log_dir,
150 nameserver)
151 self._init_logging()
152
153 def _init_logging(self) -> None:
154 """
155 Initializes the logging parameters.
156 """
157 today = datetime.datetime.now()
158 log_file = self.log_dir / f"{today:%Y-%m-%d}.log"
159
160 if not self.log_dir.exists():
161 # Make a new log directory
162 os.makedirs(log_file.parent)
163 else:
164 # Log dir already exists, lets check if we need to prune old logs
165 logs = self.log_dir.glob('*.log')
166 for log in logs:
167 log_date_str = str(log.stem)
168 log_date = datetime.datetime.strptime(log_date_str, "%Y-%m-%d")
169 if log_date + datetime.timedelta(days=self.config["# logs to keep"]) < today:
170 # Log is too old, delete!
171 os.remove(str(log))
172
173 stderr_level = logging.WARNING
174
175 stderr_handler = logging.StreamHandler(sys.stderr)
176 stderr_handler.setLevel(stderr_level)
177
178 class FilterNotStdErr(logging.Filter):
179 def filter(self, record: logging.LogRecord) -> bool:
180 return record.levelno < stderr_level
181
182 stdout_handler = logging.StreamHandler(sys.stdout)
183 stdout_handler.addFilter(FilterNotStdErr())
184
185 logging.basicConfig(
186 level=logging.DEBUG if self.verbose else logging.INFO,
187 format="%(asctime)s - %(levelname)s: %(message)s",
188 datefmt="%Y-%m-%d %I:%M:%S %p",
189 force=True, # an import might already have the root logger configured
190 handlers=[
191 stderr_handler,
192 stdout_handler,
193 logging.FileHandler(log_file),
194 ],
195 )
196
197 self.logger = logging.getLogger(f"cvdupdate-{self.version}")
198
199 # Also set the log level for urllib3, because it's "DEBUG" by default,
200 # and we may not like that.
201 urllib3_logger = logging.getLogger("urllib3.connectionpool")
202 urllib3_logger.setLevel(self.logger.level)
203
204 def _read_config(self,
205 config: str,
206 db_dir: str,
207 log_dir: str,
208 nameserver: str) -> None:
209 """
210 Read in the config file.
211 Create a new one if one does not already exist.
212 """
213 need_save = False
214
215 if config == "":
216 self.config_path = copy.deepcopy(self.default_config_path)
217 else:
218 self.config_path = Path(config)
219
220 if self.config_path.exists():
221 # Config already exists, load it.
222 with self.config_path.open('r') as config_file:
223 self.config = json.load(config_file)
224 else:
225 # Config does not exist, use default
226 self.config = copy.deepcopy(self.default_config)
227 need_save = True
228
229 if db_dir != "":
230 self.config["db directory"] = db_dir
231 need_save = True
232 self.db_dir = Path(self.config["db directory"])
233
234 if log_dir != "":
235 self.config["log directory"] = log_dir
236 need_save = True
237 self.log_dir = Path(self.config["log directory"])
238
239 if nameserver != "":
240 self.config['nameserver'] = nameserver
241 need_save = True
242
243 # For backwards compatibility with older configs.
244 if 'nameserver' not in self.config:
245 self.config['nameserver'] = ""
246 need_save = True
247 if 'max retry' not in self.config:
248 self.config['max retry'] = 3
249 need_save = True
250
251 if not hasattr(self, 'state'):
252 self.state = {}
253
254 # keep database state in a separate file, defaulting to same dir as config file
255 if 'state file' not in self.config or self.config['state file'] == '':
256 self.config['state file'] = str(self.config_path.parent / "state.json")
257 need_save = True
258
259 # handle migration from config.json to state.json
260 if 'dbs' in self.config:
261 self.state['dbs'] = self.config['dbs']
262 del self.config['dbs']
263
264 if 'uuid' in self.config:
265 self.state['uuid'] = self.config['uuid']
266 del self.config['uuid']
267
268 state_file = Path(self.config['state file'])
269 if state_file.exists():
270 # state file exists, load it.
271 with state_file.open('r') as st_fi:
272 self.state = json.load(st_fi)
273 elif self.state == {} or 'dbs' not in self.state:
274 # state file does not exist
275 # so we either have a fresh install or we have a messed up json
276 # create a skeleton structure
277 self.state = copy.deepcopy(self.default_state)
278 need_save = True
279
280 if 'uuid' not in self.state:
281 # Create a UUID to put in our User-Agent for better (anonymous) metrics
282 self.state['uuid'] = str(uuid.uuid4())
283 need_save = True
284
285 if need_save:
286 self._save_config()
287
288 def _save_config(self) -> None:
289 """
290 Save the current configuration.
291 """
292 for fi in (self.config_path, Path(self.config['state file'])):
293 if not fi.parent.exists():
294 # parent directory doesn't exist yet
295 try:
296 os.makedirs(str(fi.parent))
297 except Exception as exc:
298 print("Failed to create config directory!")
299 raise exc
300
301 try:
302 with self.config_path.open('w') as config_file:
303 json.dump(self.config, config_file, indent=4)
304 except Exception as exc:
305 print("Failed to create config file!")
306 raise exc
307
308 try:
309 with open(self.config['state file'], 'w') as state_file:
310 json.dump(self.state, state_file, indent=4)
311 except Exception as exc:
312 print("Failed to create state file!")
313 raise exc
314
315 if self.verbose:
316 print(f"Saved: {self.config_path}\n")
317 print(f"Saved: {self.config['state file']}\n")
318
319 def config_show(self):
320 """
321 Print out the config
322 """
323 print(f"Config file: {self.config_path}\n")
324 print(f"Config:\n{json.dumps(self.config, indent=4)}\n")
325 print(f"State file: {self.config['state file']}\n")
326 print(f"State:\n{json.dumps(self.state, indent=4)}\n")
327
328 def update(self, db: str = "") -> bool:
329 """
330 Update a specific database or all the databases.
331 """
332
333 def clean_dbs(self):
334 """
335 Delete cvd controlled files in the database directory.
336 """
337 dbs = self.state['dbs'].keys()
338 for db in dbs:
339 cvddb = self.db_dir / db
340 if cvddb.exists():
341 try:
342 self.logger.info(f"Deleting: {db}")
343 os.remove(str(cvddb))
344
345 # If there is a matching .sign digital signature file, remove it too
346 if os.path.exists(str(cvddb) + ".sign"):
347 os.remove(str(cvddb) + ".sign")
348
349 except Exception as exc:
350 self.logger.debug(f"Tried to remove {db}")
351 raise exc
352
353 # Remove / clear all CDIFFs
354 cdiff_files = self.db_dir.glob('*.cdiff')
355 for cdiff in cdiff_files:
356 try:
357 self.logger.info(f"Deleting CDIFF: {cdiff.name}")
358 os.remove(str(cdiff))
359
360 # If there is a matching .sign digital signature file, remove it too
361 if os.path.exists(str(cdiff) + ".sign"):
362 os.remove(str(cdiff) + ".sign")
363
364 except Exception as exc:
365 self.logger.debug(f"Tried to remove CDIFFs.")
366
367 # Config cleanup
368 for db in dbs:
369 self.state['dbs'][db]['CDIFFs'] = []
370 self.state['dbs'][db]['last modified'] = 0
371 self.state['dbs'][db]['last checked'] = 0
372 self.state['dbs'][db]['local version'] = 0
373
374 # Save config
375 self._save_config()
376
377 def clean_logs(self):
378 """
379 Delete all files in the log directory.
380 """
381 self.logger.info(f"Deleting log files...")
382 logs = self.log_dir.glob('*')
383 for log in logs:
384 os.remove(str(log))
385 print(f"Deleted: {log}")
386
387 def clean_all(self):
388 """
389 Delete all logs and databases and the config.
390 """
391 self.clean_dbs()
392
393 self.clean_logs()
394
395 os.remove(str(self.config_path))
396 print(f"Deleted: {self.config_path}")
397 os.remove(str(self.config['state file']))
398 print(f"Deleted: {self.config['state file']}")
399
400 def _index_local_databases(self) -> dict:
401 need_save = False
402 dbs = copy.deepcopy(self.state['dbs'])
403
404 db_paths = self.db_dir.glob('*')
405 for db in db_paths:
406 if db.name.endswith('.cdiff') or db.name.endswith('.sign'):
407 # Ignore CDIFFs and sign files, they'll get printed later.
408 continue
409
410 if db.name not in dbs:
411 version = 0
412
413 # Found a file in here that ISN'T a part of the config
414 if db.name.endswith('.cvd'):
415 # Found a CVD in here that ISN'T a part of the config!
416 # Very odd BTW.
417 self.logger.warning(f"Found a CVD in the DB directory that isn't in the config: {db.name}")
418 try:
419 version = self._get_cvd_version_from_file(db)
420 except Exception as exc:
421 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
422 self.logger.error(f"Failed to determine version for {db.name}")
423
424 dbs[db.name] = {
425 "url" : "n/a",
426 "retry after" : 0,
427 "last modified" : os.path.getmtime(str(db)),
428 "last checked" : 0,
429 "DNS field" : 0,
430 "local version" : version,
431 "CDIFFs" : []
432 }
433 else:
434 # DB on disk is from our config
435 if db.name.endswith(".cvd") and self.state['dbs'][db.name]['local version'] == 0:
436 # Seems like we somehow got a (config'd) CVD file in our database directory without
437 # saving the CVD info to the config. Let's just update the version field.
438 self.logger.info(f"Found {db.name} in the DB directory, though it wasn't downloaded using this tool.")
439 try:
440 dbs[db.name]['local version'] = self._get_cvd_version_from_file(self.db_dir / db.name)
441 self.logger.info(f"Identified mysterious {db.name} version: {dbs[db.name]['local version']}")
442
443 # Add the version info for this mysteriously deposited CVD to our config.
444 self.state['dbs'][db.name]['local version'] = dbs[db.name]['local version']
445 need_save = True
446 except Exception as exc:
447 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
448 self.logger.error(f"Failed to determine version # of mysterious {db.name} file. Perhaps it is corrupted?")
449
450 if need_save:
451 self._save_config()
452
453 return dbs
454
455 def db_list(self) -> None:
456 """
457 Print list of databases
458 """
459 dbs = self._index_local_databases()
460
461 for db in dbs:
462 updated = datetime.datetime.fromtimestamp(dbs[db]['last modified']).strftime('%Y-%m-%d %H:%M:%S')
463 checked = datetime.datetime.fromtimestamp(dbs[db]['last checked']).strftime('%Y-%m-%d %H:%M:%S')
464 self.logger.info(f"Database: {db}")
465 if dbs[db]['last modified'] == 0:
466 self.logger.info(" last modified: not downloaded")
467 else:
468 self.logger.info(f" last modified: {updated}")
469 if dbs[db]['last checked'] == 0:
470 self.logger.debug(" last checked: n/a")
471 else:
472 self.logger.debug(f" last checked: {checked}")
473 self.logger.debug(f" url: {dbs[db]['url']}")
474 if db.endswith(".cvd"):
475 # Only CVD's have versions.
476 self.logger.debug(f" local version: {dbs[db]['local version']}")
477 if len(dbs[db]['CDIFFs']) > 0:
478 self.logger.debug(f" CDIFFs:")
479 for cdiff in dbs[db]['CDIFFs']:
480 self.logger.debug(f" {cdiff}")
481
482
483 def db_show(self, name) -> bool:
484 """
485 Show details for a specific database
486 """
487 found = False
488 dbs = self._index_local_databases()
489
490 for db in dbs:
491 if db == name:
492 found = True;
493
494 updated = datetime.datetime.fromtimestamp(dbs[db]['last modified']).strftime('%Y-%m-%d %H:%M:%S')
495 checked = datetime.datetime.fromtimestamp(dbs[db]['last checked']).strftime('%Y-%m-%d %H:%M:%S')
496 self.logger.info(f"Database: {db}")
497 if dbs[db]['last modified'] == 0:
498 self.logger.info(" last modified: not downloaded")
499 else:
500 self.logger.info(f" last modified: {updated}")
501 if dbs[db]['last checked'] == 0:
502 self.logger.info(" last checked: n/a")
503 else:
504 self.logger.info(f" last checked: {checked}")
505 self.logger.info(f" url: {dbs[db]['url']}")
506 if db.endswith(".cvd"):
507 self.logger.info(f" local version: {dbs[db]['local version']}")
508 if len(dbs[db]['CDIFFs']) > 0:
509 self.logger.info(f" CDIFFs: \n{json.dumps(dbs[db]['CDIFFs'], indent=4)}")
510 return True
511
512 if not found:
513 self.logger.error(f"No such database: {name}")
514 return found
515
516 def _query_dns_txt_entry(self) -> bool:
517 '''
518 Attempt to get version from current.cvd.clamav.net DNS TXT entry
519 '''
520 got_it = False
521 self.logger.debug(f"Checking available versions via DNS TXT entry query of current.cvd.clamav.net")
522
523 try:
524 our_resolver = resolver.Resolver()
525 our_resolver.timeout = 5 # Explicitly setting query timeout to mitigate https://github.com/Cisco-Talos/cvdupdate/issues/17
526 nameservers = self._get_nameserver_configuration()
527
528 if nameservers:
529 our_resolver.nameservers = nameservers
530 self.logger.info(f"Using nameservers: {nameservers}")
531 else:
532 self.logger.info("Using system configured nameservers")
533
534 answer = str(our_resolver.resolve("current.cvd.clamav.net","TXT").response.answer[0])
535 versions = re.search('".*"', answer).group().strip('"')
536 self.dns_version_tokens = versions.split(':')
537 got_it = True
538 except Exception as exc:
539 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
540 self.logger.warning(f"Failed to determine available version via DNS TXT query!")
541
542 return got_it
543
544 def _get_nameserver_configuration(self) -> List[str]:
545 '''
546 Parse comma delimited nameserver string into a list for Resolver
547 '''
548 nameserver_string = self._get_nameserver_string()
549 nameservers = []
550
551 os_platform = platform.platform()
552 operating_system = os_platform.split("-")[0].lower()
553
554 if nameserver_string != "":
555 try:
556 nameservers = [x.strip() for x in nameserver_string.split(',')]
557 except Exception as exc:
558 self.logger.warning(f"Failed to parse nameserver configuration: {nameserver_string}, ignoring...")
559 nameservers = []
560
561 if nameservers == [] and operating_system == "windows":
562 # Try OpenDNS nameservers on Windows if not overridden by the user, because leaving it empty seems to fail.
563 nameservers = ['208.67.222.222', '208.67.220.220']
564
565 return nameservers
566
567 def _get_nameserver_string(self) -> str:
568 '''
569 Determine user provided nameserver configuration
570 '''
571 config_nameserver = self.config['nameserver']
572 env_nameserver = os.environ.get("CVDUPDATE_NAMESERVER")
573
574 # Environment variable overrides the configuration setting
575 if env_nameserver != None and env_nameserver != "":
576 self.logger.info(f"Found CVDUPDATE_NAMESERVER environment variable to provide nameservers: {env_nameserver}")
577 return env_nameserver
578 elif config_nameserver != None and config_nameserver != "":
579 self.logger.info(f"Found configuration provided nameservers: {config_nameserver}")
580 return config_nameserver
581
582 return ""
583
584 def _query_cvd_version_dns(self, db: str) -> int:
585 '''
586 This is a faux query.
587 Try to look up the version # from the DNS TXT entry we already have.
588 '''
589 version = 0
590
591 if self.dns_version_tokens == []:
592 # Query DNS if we haven't already
593 for _attempt in range(self.config['max retry']):
594 if self._query_dns_txt_entry():
595 break
596 # Pause before next attempt.
597 time.sleep(0.1)
598
599 if self.dns_version_tokens == []:
600 # Query failed. Bail out.
601 return version
602
603 self.logger.debug(f"Checking {db} version via DNS TXT advertisement.")
604
605 if self.state['dbs'][db]['DNS field'] == 0:
606 # Invalid DNS field value for database version.
607 self.logger.warning(f"Failed to get DB version from DNS TXT entry: Invalid DNS field value for database version.")
608 return version
609
610 try:
611 version = int(self.dns_version_tokens[self.state['dbs'][db]['DNS field']])
612 self.logger.debug(f"{db} version advertised by DNS: {version}")
613
614 # Update the "last checked" time.
615 self.state['dbs'][db]['last checked'] = time.time()
616
617 except Exception as exc:
618 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
619 self.logger.warning(f"Failed to get DB version from DNS TXT entry!")
620
621 return version
622
623 def _query_cvd_version_http(self, db: str) -> int:
624 '''
625 Download the CVD header and read the CVD version
626
627 Return 1+ if queried version.
628 Return 0 if failed.
629 '''
630 version = 0
631 url = self.state['dbs'][db]['url']
632
633 self.logger.debug(f"Checking {db} version via HTTP download of CVD header.")
634
635 ims = datetime.datetime.fromtimestamp(self.state['dbs'][db]['last modified'], tz=datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
636
637 retry = 0
638 response = None
639 while retry < self.config['max retry']:
640 response = requests.get(url, headers = {
641 'User-Agent': f'CVDUPDATE/{self.version} ({self.state["uuid"]})',
642 'Range': 'bytes=0-95',
643 'If-Modified-Since': ims,
644 })
645
646 if ((response.status_code == 200 or response.status_code == 206) and
647 ('content-length' in response.headers) and
648 (int(response.headers['content-length']) > len(response.content))):
649 self.logger.warning(f"Response was truncated somehow...")
650 self.logger.warning(f" Expected {response.headers['content-length']}")
651 self.logger.warning(f" Received {response.content}, let's retry.")
652 retry += 1
653 else:
654 break
655 if response is None:
656 self.logger.error(f"No response received requesting CVD header from {url}.")
657 return 0
658
659 if response.status_code == 200 or response.status_code == 206:
660 # Looks like we downloaded something...
661 if (('content-length' in response.headers) and int(response.headers['content-length']) > len(response.content)):
662 self.logger.error(f"Failed to download {db} header to check the version #.")
663 return 0
664
665 # Successfully downloaded the header.
666 # We used the IMS header so this means it's probably newer, but we'll check just in case.
667 cvd_header = response.content
668 version = self._get_version_from_cvd_header(cvd_header)
669 self.logger.debug(f"{db} version available by HTTP download: {version}")
670
671 elif response.status_code == 304:
672 # HTTP Not-Modified, it's not newer.than what we already have.
673 # Just return the current local version.
674 version = self.state['dbs'][db]['local version']
675 self.logger.debug(f"{db} not-modified since: {ims} (local version {version})")
676
677 elif response.status_code == 429:
678 # Rejected because downloading the same file too frequently.
679 self.logger.warning(f"Failed to download {db} header to check the version #.")
680 self.logger.warning(f"Download request rejected because we've downloaded the same file too frequently.")
681
682 try_again_seconds = 60 * 60 * 12 # 12 hours
683 if 'Retry-After' in response.headers.keys():
684 try_again_seconds = int(response.headers['Retry-After'])
685
686 self.state['dbs'][db]['retry after'] = time.time() + float(try_again_seconds)
687
688 try_again_string = str(datetime.timedelta(seconds=try_again_seconds))
689 self.logger.warning(f"We won't try {db} again for {try_again_string} hours.")
690
691 else:
692 # Check failed!
693 self.logger.error(f"Failed to download {db} header to check the version #. Url: {url}")
694
695 if version > 0:
696 # Update the "last checked" time.
697 self.state['dbs'][db]['last checked'] = time.time()
698
699 return version
700
701 def _download_db_from_url(self, db: str, url: str, last_modified: int, version=0) -> CvdStatus:
702 '''
703 Download contents from a url and save to a filename in the database directory.
704 Will use If-Modified-Since
705 If Not-Modified, it will not replace the current database.
706 '''
707 ims: str = datetime.datetime.fromtimestamp(last_modified, tz=datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
708
709 retry = 0
710 response = None
711 while retry < self.config['max retry']:
712 response = requests.get(url, headers = {
713 'User-Agent': f'CVDUPDATE/{self.version} ({self.state["uuid"]})',
714 'If-Modified-Since': ims,
715 })
716
717 if ((response.status_code == 200 or response.status_code == 206) and
718 ('content-length' in response.headers) and
719 (int(response.headers['content-length']) > len(response.content))):
720 self.logger.warning(f"Response was truncated somehow...")
721 self.logger.warning(f" Expected {response.headers['content-length']}")
722 self.logger.warning(f" Received {response.content}, let's retry.")
723 retry += 1
724 else:
725 break
726 if response is None:
727 self.logger.error(f"No response received requesting {url}.")
728 return CvdStatus.ERROR
729
730 if response.status_code == 200:
731 # Looks like we downloaded something...
732 if (('content-length' in response.headers) and int(response.headers['content-length']) > len(response.content)):
733 self.logger.error(f"Failed to download {db}")
734 return CvdStatus.ERROR
735
736 # Download Success
737 if version > 0:
738 self.logger.info(f"Downloaded {db}. Version: {version}")
739 else:
740 self.logger.info(f"Downloaded {db}")
741
742 try:
743 with (self.db_dir / db).open('wb') as new_db:
744 new_db.write(response.content)
745
746 # Update config w/ new db info
747 self.state['dbs'][db]['last modified'] = time.time()
748 if db.endswith('.cvd'):
749 self.state['dbs'][db]['local version'] = self._get_version_from_cvd_header(response.content[:96])
750
751 except Exception as exc:
752 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
753 self.logger.error(f"Failed to save {db} to {self.db_dir}")
754 return CvdStatus.ERROR
755
756 elif response.status_code == 304:
757 # Not modified since IMS. We have the latest version.
758 version = self.state['dbs'][db]['local version']
759 self.logger.info(f"{db} not-modified since: {ims} (local version {version})")
760
761 # Check for .cvd.sign.
762 # it won't download if we already have it.
763 self._download_sign_file_for(
764 db,
765 url,
766 last_modified=0,
767 version=version)
768
769 return CvdStatus.NO_UPDATE
770
771 elif response.status_code == 429:
772 # Rejected because downloading the same file too frequently.
773 self.logger.warning(f"Failed to download {db}.")
774 self.logger.warning(f"Download request rejected because we've downloaded the same file too frequently.")
775
776 try_again_seconds = 60 * 60 * 12 # 12 hours
777 if 'Retry-After' in response.headers.keys():
778 try_again_seconds = int(response.headers['Retry-After'])
779
780 self.state['dbs'][db]['retry after'] = time.time() + float(try_again_seconds)
781
782 try_again_string = str(datetime.timedelta(seconds=try_again_seconds))
783 self.logger.warning(f"We won't try {db} again for {try_again_string} hours.")
784
785 # We'll have to retry after the cooldown.
786 return CvdStatus.ERROR
787
788 else:
789 # HTTP Get failed.
790 self.logger.error(f"Failed to download {db} from {url}")
791 return CvdStatus.ERROR
792
793 # Now try downloading the corresponding .cvd.sign.
794 # It's okay if it doesn't exist
795 self._download_sign_file_for(
796 db,
797 url,
798 last_modified=0,
799 version=version)
800
801 return CvdStatus.UPDATED
802
803 def _download_cdiff(self, db: str, file: str, db_url: str, last_modified: int, desired_version: int, available_version: int) -> CvdStatus:
804 '''
805 Download a CDIFF file given a file name and version.
806 The file name should be in the format of "daily-12345.cdiff"
807 '''
808
809 self.logger.debug(f"Checking for {file}")
810
811 # now remove the old file name from the db_url and add the new sign file name
812 base_url = db_url.rsplit('/', 1)[0]
813 url = f"{base_url}/{file}"
814
815 retry = 0
816 response = None
817 while retry < self.config['max retry']:
818 response = requests.get(url, headers = {
819 'User-Agent': f'CVDUPDATE/{self.version} ({self.state["uuid"]})',
820 })
821
822 if ((response.status_code == 200 or response.status_code == 206) and
823 ('content-length' in response.headers) and
824 (int(response.headers['content-length']) > len(response.content))):
825 self.logger.warning(f"Response was truncated somehow...")
826 self.logger.warning(f" Expected {response.headers['content-length']}")
827 self.logger.warning(f" Received {response.content}, let's retry.")
828 retry += 1
829 else:
830 break
831 if response is None:
832 self.logger.error(f"No response received requesting {url}.")
833 return CvdStatus.ERROR
834
835 if response.status_code == 200:
836 # Looks like we downloaded something...
837 if (('content-length' in response.headers) and int(response.headers['content-length']) > len(response.content)):
838 self.logger.error(f"Failed to download CDIFF.")
839 return CvdStatus.ERROR
840
841 # Download Success
842 self.logger.info(f"Downloaded {file}")
843 try:
844 with (self.db_dir / f"{file}").open('wb') as new_db:
845 new_db.write(response.content)
846 except Exception as exc:
847 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
848 self.logger.error(f"Failed to save {file} to {self.db_dir}.")
849
850 # Update config with CDIFF, for posterity
851 self.state['dbs'][db]['CDIFFs'].append(file)
852
853 # Prune old CDIFFs if needed
854 if len(self.state['dbs'][db]['CDIFFs']) > self.config['# cdiffs to keep']:
855 try:
856 os.remove(self.db_dir / self.state['dbs'][db]['CDIFFs'][0])
857 except Exception as exc:
858 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
859 self.logger.debug(f"Tried to prune old cdiffs, but they weren't found, maybe someone else removed them already.")
860
861 self.state['dbs'][db]['CDIFFs'] = self.state['dbs'][db]['CDIFFs'][1:]
862
863 elif response.status_code == 429:
864 # Rejected because downloading the same file too frequently.
865 self.logger.warning(f"Failed to download {file}")
866 self.logger.warning(f"Download request rejected because we've downloaded the same file too frequently.")
867
868 try_again_seconds = 60 * 60 * 12 # 12 hours
869 if 'Retry-After' in response.headers.keys():
870 try_again_seconds = int(response.headers['Retry-After'])
871
872 self.state['dbs'][db]['retry after'] = time.time() + float(try_again_seconds)
873
874 try_again_string = str(datetime.timedelta(seconds=try_again_seconds))
875 self.logger.warning(f"We won't try {db} again for {try_again_string} hours.")
876
877 # Sure only a CDIFF failed, but if we want any chance of trying the CDIFF again
878 # in the future, let's bail out now and retry the CVD + CDIFFs after the cooldown.
879 return CvdStatus.ERROR
880
881 else:
882 # HTTP Get failed.
883 self.logger.info(f"No CDIFF found for {db} version # {desired_version}")
884
885 if desired_version < available_version:
886 desired_version = available_version - 1
887 self.logger.info(f"Will just skip to the last CDIFF instead.")
888 else:
889 self.logger.info(f"Giving up on CDIFFs for {db}")
890 return CvdStatus.NO_UPDATE
891
892 return CvdStatus.UPDATED
893
894
895 def _download_sign_file_for(self, file: str, file_url: str, last_modified: int, version=0) -> CvdStatus:
896 '''
897 Download signature file given a file name.
898 If version > 0, will ensure sign file includes version in the filename, like this:
899 - file-version.ext.sign
900 '''
901 ims: str = datetime.datetime.fromtimestamp(last_modified, tz=datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
902
903 sign_file = file + ".sign"
904 if version > 0 and str(version) not in file:
905 # the sign file name should include the version in this format: "file-version.ext.sign"
906 # reconstruct.
907 name_parts = file.rsplit('.', 1)
908 if len(name_parts) == 1:
909 self.logger.error(f"Invalid file name. Lacks extension: {file}")
910 return CvdStatus.ERROR
911
912 file_name = name_parts[0]
913 ext = name_parts[-1]
914 sign_file = f"{file_name}-{version}.{ext}.sign"
915
916 # check if we already have it.
917 if (self.db_dir / sign_file).exists():
918 self.logger.debug(f"We already have {sign_file}. Skipping...")
919 return CvdStatus.NO_UPDATE
920
921 # now remove the old file name from the file_url and add the new sign file name
922 base_url = file_url.rsplit('/', 1)[0]
923 url = f"{base_url}/{sign_file}"
924
925 retry = 0
926 response = None
927 while retry < self.config['max retry']:
928 response = requests.get(url, headers = {
929 'User-Agent': f'CVDUPDATE/{self.version} ({self.state["uuid"]})',
930 'If-Modified-Since': ims,
931 })
932
933 if ((response.status_code == 200 or response.status_code == 206) and
934 ('content-length' in response.headers) and
935 (int(response.headers['content-length']) > len(response.content))):
936 self.logger.warning(f"Response was truncated somehow...")
937 self.logger.warning(f" Expected {response.headers['content-length']}")
938 self.logger.warning(f" Received {response.content}, let's retry.")
939 retry += 1
940 else:
941 break
942 if response is None:
943 self.logger.error(f"No response received requesting {url}.")
944 return CvdStatus.ERROR
945
946 if response.status_code == 200:
947 # Looks like we downloaded something...
948 if (('content-length' in response.headers) and int(response.headers['content-length']) > len(response.content)):
949 self.logger.error(f"Failed to download {sign_file}")
950 return CvdStatus.ERROR
951
952 # Download Success
953 if version > 0:
954 self.logger.info(f"Downloaded {sign_file}. Version: {version}")
955 else:
956 self.logger.info(f"Downloaded {sign_file}")
957
958 try:
959 with (self.db_dir / sign_file).open('wb') as new_db:
960 new_db.write(response.content)
961
962 except Exception as exc:
963 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
964 self.logger.error(f"Failed to save {sign_file} to {self.db_dir}")
965 return CvdStatus.ERROR
966
967 elif response.status_code == 304:
968 # Not modified since IMS. We have the latest version.
969 self.logger.info(f"{sign_file} not-modified since: {ims} (local version {version})")
970 return CvdStatus.NO_UPDATE
971
972 elif response.status_code == 429:
973 # Rejected because downloading the same file too frequently.
974 self.logger.warning(f"Failed to download {sign_file} from {url} with 429 response.")
975 return CvdStatus.ERROR
976
977 else:
978 # HTTP Get failed.
979 self.logger.info(f"Request failed for {url}. Probably no external digital signature provided for {file}")
980 return CvdStatus.ERROR
981
982 return CvdStatus.UPDATED
983
984 def _download_cvd(self, db: str, available_version: int) -> CvdStatus:
985 '''
986 Download the latest available version
987 If we already have some version of the database, attempt to download all CDIFFs in between.
988 If we don't, just get the last two CDIFFs.
989 '''
990 local_version = self.state['dbs'][db]['local version']
991 desired_version = local_version + 1
992
993 if local_version >= available_version:
994 # Oh! We're already up to date, don't worry about it.
995 self.logger.info(f"{db} is up-to-date. Version: {local_version}")
996
997 db_url = self.state['dbs'][db]['url']
998
999 # Check for the .cvd.sign file, just in case we don't have that yet.
1000 # It won't download if we already have it.
1001 self._download_sign_file_for(
1002 db,
1003 db_url,
1004 last_modified=0,
1005 version=available_version)
1006
1007 return CvdStatus.NO_UPDATE
1008
1009 elif local_version == 0:
1010 # We don't have any version of the DB, let's just get the newest version + the last CDIFF
1011 desired_version = available_version
1012
1013 # First try to get CDIFFs
1014 self.logger.debug(f"Downloading CDIFFs first...")
1015 while desired_version <= available_version:
1016 # Attempt to download each CDIFF between our local version and the available version.
1017 # The url for CVDs should be https://database.clamav.net/<db>
1018 # Eg:
1019 # https://database.clamav.net/daily.cvd
1020 # For the daily CDIFFs, we would want:
1021 # https://database.clamav.net/daily-<version>.cdiff
1022 cdiff_file = f"{db[:-len('.cvd')]}-{desired_version}.cdiff"
1023
1024 if (self.db_dir / cdiff_file).exists():
1025 self.logger.debug(f"We already have {cdiff_file}. Skipping...")
1026 desired_version += 1
1027 continue
1028
1029 db_url = self.state['dbs'][db]['url']
1030
1031 # Download the .cdiff
1032 result = self._download_cdiff(
1033 db,
1034 cdiff_file,
1035 db_url,
1036 last_modified=0,
1037 desired_version=desired_version,
1038 available_version=available_version)
1039
1040 if result != CvdStatus.UPDATED:
1041 self.logger.error(f"Failed to download {cdiff_file}.")
1042 break
1043
1044 # Now try downloading the corresponding .cdiff.sign.
1045 # It's okay if it doesn't exist.
1046 self._download_sign_file_for(
1047 cdiff_file,
1048 db_url,
1049 last_modified=0,
1050 version=desired_version)
1051
1052 desired_version += 1
1053
1054 # Now download the available version.
1055 desired_version = available_version
1056
1057 url = f"{self.state['dbs'][db]['url']}?version={desired_version}"
1058
1059 return self._download_db_from_url(db, url, last_modified=0, version=desired_version)
1060
1061 def _get_version_from_cvd_header(self, cvd_header: bytes) -> int:
1062 '''
1063 Parse a CVD header to read the database version.
1064 '''
1065 header_fields = cvd_header.decode('utf-8', 'ignore').strip().split(':')
1066
1067 version_found = 0
1068 try:
1069 version_found = int(header_fields[2])
1070 except Exception as exc:
1071 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
1072 self.logger.error(f"Failed to determine version from CVD header!")
1073
1074 return version_found
1075
1076 def _get_cvd_version_from_file(self, path: Path) -> int:
1077 cvd_header: bytes = b''
1078 version_found = 0
1079
1080 try:
1081 with path.open('rb') as cvd_fd:
1082 cvd_header = cvd_fd.read(96)
1083
1084 if len(cvd_header) < 96:
1085 # Most likely a corrupted CVD. Delete.
1086 self.logger.debug(f"Failed to read CVD header, perhaps {path.name} is corrupted.")
1087 self.logger.debug(f"Will delete {path.name} so it will not cause further problems.")
1088 os.remove(str(path))
1089 else:
1090 # Got the header, lets parse out the version.
1091 version_found = self._get_version_from_cvd_header(cvd_header)
1092
1093 except Exception as exc:
1094 self.logger.debug(f"EXCEPTION OCCURRED: {exc}")
1095 self.logger.error(f"Failed to read version from CVD header from {path}.")
1096
1097 if version_found == 0:
1098 self.logger.error(f"Failed to determine version from CVD header.")
1099
1100 return version_found
1101
1102 def pypi_update_check(self):
1103 def check(name):
1104 """Checks if a newer version of the specified module is available on PyPI."""
1105 self.logger.debug(f'Checking for a newer version of {name}.')
1106 try:
1107 current_version_str = _get_version(name)
1108 current_version = version.parse(current_version_str)
1109
1110 response = requests.get(f"https://pypi.org/pypi/{name}/json") # Get package info
1111 response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
1112 latest_version_str = response.json()["info"]["version"]
1113 latest_version = version.parse(latest_version_str)
1114
1115 if latest_version > current_version:
1116 self.logger.warning(f'You are running {name} version: {current_version}.')
1117 self.logger.warning(f'There is a newer version on PyPI: {latest_version}. Please update!')
1118 return False # Newer version available
1119
1120 else:
1121 self.logger.debug(f'{name} is up-to-date: {current_version}.')
1122 return True # No newer version
1123
1124 except requests.exceptions.RequestException as e:
1125 self.logger.debug(f"Version check failed: {e}") # Log the error
1126 return True # Assume up-to-date on error
1127
1128 except PackageNotFoundError:
1129 self.logger.error(f"Package {name} not found locally.")
1130 return True # Assuming not found means no update possible
1131
1132 except Exception as e: # Catch other potential errors (json parsing etc.)
1133 self.logger.debug(f"Version check failed: {e}")
1134 return True # Assume up-to-date on error
1135
1136 return check('cvdupdate')
1137
1138 def db_update(self, db="", debug_mode=False) -> int:
1139 """
1140 Update one or all of the databases.
1141
1142 Returns: Number of errors.
1143 """
1144 self.update_errors = 0
1145 self.dbs_updated = 0
1146 self.dns_version_tokens = []
1147
1148 # Make sure we have a database directory to save files to
1149 if not self.db_dir.exists():
1150 os.makedirs(self.db_dir)
1151
1152 # Query DNS so we can efficiently query CVD version #'s
1153 self._query_dns_txt_entry()
1154 if self.dns_version_tokens == []:
1155 # Query failed. Bail out.
1156 self.logger.error(f"Failed to update: DNS query failed.")
1157 return 1
1158
1159 if debug_mode:
1160 http_client.HTTPConnection.debuglevel = 1
1161
1162 def update(db) -> CvdStatus:
1163 '''
1164 Update a database
1165 '''
1166 if self.state['dbs'][db]['retry after'] > 0:
1167 cooldown_date = datetime.datetime.fromtimestamp(self.state['dbs'][db]['retry after']).strftime('%Y-%m-%d %H:%M:%S')
1168
1169 if self.state['dbs'][db]['retry after'] > time.time():
1170 self.logger.warning(f"Skipping {db} which is on cooldown until {cooldown_date}")
1171 return CvdStatus.ERROR
1172 else:
1173 # Cooldown expired. Ok to try again.
1174 self.state['dbs'][db]['retry after'] = 0
1175 self.logger.info(f"{db} cooldown expired {cooldown_date}. OK to try again...")
1176
1177 if not self.state['dbs'][db]['url'].startswith('http'):
1178 self.logger.error(f"Failed to update {db}. Missing or invalid URL: {self.state['dbs'][db]['url']}")
1179 return CvdStatus.ERROR
1180
1181 self.logger.debug(f"Checking {db} for update from {self.state['dbs'][db]['url']}")
1182
1183 if db.endswith('.cvd'):
1184 # It's a CVD (official signed clamav database)
1185 advertised_version = 0
1186
1187 if (self.db_dir / db).exists():
1188 if self.state['dbs'][db]['local version'] == 0:
1189 # Seems like we somehow got a CVD in our database directory without
1190 # saving the CVD info to the config. Let's just update the version field.
1191 self.state['dbs'][db]['local version'] = self._get_cvd_version_from_file(self.db_dir / db)
1192 else:
1193 if self.state['dbs'][db]['local version'] != 0:
1194 # We have a local version but no CVD in the database directory.
1195 # Maybe it was moved or deleted? Let's just reset the local version.
1196 self.state['dbs'][db]['local version'] = 0
1197
1198 if self.state['dbs'][db]['DNS field'] > 0:
1199 # We can use the DNS TXT fields to check if our version is old.
1200 advertised_version = self._query_cvd_version_dns(db)
1201
1202 else:
1203 # We can't use DNS to see if our version is old.
1204 # Use HTTP to pull just the CVD header to check.
1205
1206 # First, make sure no one tampered with the DNS field for
1207 # main/daily/bytecode when using database.clamav.net
1208 if (('database.clamav.net' in self.state['dbs'][db]['url']) and
1209 (db == 'main.cvd' or db == 'daily.cvd' or db == 'bytecode.cvd')):
1210 self.logger.error(f'It appears that the "DNS field" in {self.config_path} for "{db}" was modified from the default.')
1211 self.logger.error(f'Updating {db} from database.clamav.net requires DNS for the version check in order to conserve bandwidth.')
1212 self.logger.error(f'Please restore the default settings for the "DNS field" and try again.')
1213 return CvdStatus.ERROR
1214
1215 advertised_version = self._query_cvd_version_http(db)
1216
1217 if advertised_version == 0:
1218 self.logger.error(f"Failed to update {db}. Failed to query available CVD version")
1219 return CvdStatus.ERROR
1220
1221 return self._download_cvd(db, advertised_version)
1222
1223 else:
1224 # Try the download.
1225 # Will use If-Modified-Since
1226 # If Not-Modified, it will not replace the current database.
1227 return self._download_db_from_url(
1228 db,
1229 self.state['dbs'][db]['url'],
1230 self.state['dbs'][db]['last modified'])
1231
1232 if db == "":
1233 # Update every DB.
1234 for db in self.state['dbs']:
1235 status = update(db)
1236 if status == CvdStatus.ERROR:
1237 self.update_errors += 1
1238 elif status == CvdStatus.UPDATED:
1239 self.dbs_updated += 1
1240
1241 else:
1242 # Update a specific DB.
1243 if db not in self.state['dbs']:
1244 self.logger.error(f"Update failed. Unknown database: {db}")
1245 else:
1246 status = update(db)
1247 if status == CvdStatus.ERROR:
1248 self.update_errors += 1
1249 elif status == CvdStatus.UPDATED:
1250 self.dbs_updated += 1
1251
1252 self._save_config()
1253
1254 if self.update_errors == 0 and self.dbs_updated > 0:
1255 with (self.db_dir / 'dns.txt').open('w') as dns_file:
1256 dns_file.write(':'.join(self.dns_version_tokens))
1257 self.logger.debug(f"Updated {self.db_dir / 'dns.txt'}")
1258
1259 return self.update_errors
1260
1261 def config_add_db(self, db: str, url: str) -> bool:
1262 """
1263 Add another database + url to check when we update.
1264 """
1265 extension = db.split('.')[-1]
1266 if extension not in [
1267 'cvd', 'cld', 'cud',
1268 'cfg', 'cat', 'crb',
1269 'ftm',
1270 'ndb', 'ndu',
1271 'ldb', 'ldu', 'idb',
1272 'ydb', 'yar', 'yara',
1273 'cdb',
1274 'cbc',
1275 'pdb', 'gdb', 'wdb',
1276 'hdb', 'hsb', 'hdu', 'hsu',
1277 'mdb', 'msb', 'mdu', 'msu',
1278 'ign', 'ign2',
1279 'info',
1280 ]:
1281 self.logger.warning(f"{db} does not have valid clamav database file extension.")
1282
1283 if db in self.state['dbs']:
1284 self.logger.info(f"Cannot add {db}, it is already in our list.")
1285 self.logger.info(f"Hint: Try `db list -V` or `db show {db}` for more information.")
1286 return False
1287
1288 self.state['dbs'][db] = {
1289 "url" : url,
1290 "retry after" : 0,
1291 "last modified" : 0,
1292 "last checked" : 0,
1293 "DNS field" : 0,
1294 "local version" : 0,
1295 "CDIFFs" : []
1296 }
1297
1298 self.logger.info(f"Added {db} ({url}) to DB list.")
1299 self.logger.info(f"{db} will be downloaded next time you run `cvd update` or `cvd update {db}`")
1300
1301 self._save_config()
1302
1303 return True
1304
1305 def config_remove_db(self, db: str) -> bool:
1306 """
1307 Remove a database from our list, and delete copies of the DB from the database directory.
1308 """
1309 if db not in self.state['dbs']:
1310 self.logger.info(f"Cannot remove {db}, it is not in our list.")
1311 self.logger.info(f"Hint: Try `db list -V` for more information.")
1312 return False
1313
1314 try:
1315 if (self.db_dir / db).exists():
1316 os.remove(str(self.db_dir / db))
1317 self.logger.info(f"Deleted {db} from database directory.")
1318
1319 except Exception as exc:
1320 self.logger.debug(f"An exception occured: {exc}")
1321 self.logger.error(f"Failed to delete {db} from databse directory!")
1322
1323 for cdiff in self.state['dbs'][db]['CDIFFs']:
1324 try:
1325 if (self.db_dir / cdiff).exists():
1326 os.remove(str(self.db_dir / cdiff))
1327 self.logger.info(f"Deleted {cdiff} from database directory.")
1328
1329 except Exception as exc:
1330 self.logger.debug(f"An exception occured: {exc}")
1331 self.logger.error(f"Failed to delete {cdiff} from databse directory!")
1332
1333 self.state['dbs'].pop(db)
1334
1335 self.logger.info(f"Removed {db} from DB list.")
1336
1337 self._save_config()
1338
1339 return True