|
| 1 | +import logging |
| 2 | +import threading |
| 3 | + |
| 4 | +from contextlib import contextmanager |
| 5 | +from typing import Iterator |
| 6 | +from uuid import UUID |
| 7 | + |
| 8 | +import neo4j |
| 9 | + |
| 10 | +from django.conf import settings |
| 11 | + |
| 12 | +import neo4j.exceptions |
| 13 | + |
| 14 | +# Without this Celery goes crazy with Neo4j logging |
| 15 | +logging.getLogger("neo4j").setLevel(logging.ERROR) |
| 16 | +logging.getLogger("neo4j").propagate = False |
| 17 | + |
| 18 | +# Module-level process-wide driver singleton |
| 19 | +_driver: neo4j.Driver | None = None |
| 20 | +_lock = threading.Lock() |
| 21 | + |
| 22 | +# Base Neo4j functions |
| 23 | + |
| 24 | + |
| 25 | +def get_uri() -> str: |
| 26 | + host = settings.DATABASES["neo4j"]["HOST"] |
| 27 | + port = settings.DATABASES["neo4j"]["PORT"] |
| 28 | + return f"bolt://{host}:{port}" |
| 29 | + |
| 30 | + |
| 31 | +def init_driver() -> neo4j.Driver: |
| 32 | + global _driver |
| 33 | + if _driver is not None: |
| 34 | + return _driver |
| 35 | + |
| 36 | + with _lock: |
| 37 | + if _driver is None: |
| 38 | + uri = get_uri() |
| 39 | + config = settings.DATABASES["neo4j"] |
| 40 | + |
| 41 | + _driver = neo4j.GraphDatabase.driver( |
| 42 | + uri, auth=(config["USER"], config["PASSWORD"]) |
| 43 | + ) |
| 44 | + _driver.verify_connectivity() |
| 45 | + |
| 46 | + return _driver |
| 47 | + |
| 48 | + |
| 49 | +def get_driver() -> neo4j.Driver: |
| 50 | + return init_driver() |
| 51 | + |
| 52 | + |
| 53 | +def close_driver() -> None: # TODO: Use it |
| 54 | + global _driver |
| 55 | + with _lock: |
| 56 | + if _driver is not None: |
| 57 | + try: |
| 58 | + _driver.close() |
| 59 | + |
| 60 | + finally: |
| 61 | + _driver = None |
| 62 | + |
| 63 | + |
| 64 | +@contextmanager |
| 65 | +def get_session(database: str | None = None) -> Iterator[neo4j.Session]: |
| 66 | + try: |
| 67 | + with get_driver().session(database=database) as session: |
| 68 | + yield session |
| 69 | + |
| 70 | + except neo4j.exceptions.Neo4jError as exc: |
| 71 | + raise GraphDatabaseQueryException(message=exc.message, code=exc.code) |
| 72 | + |
| 73 | + |
| 74 | +def create_database(database: str) -> None: |
| 75 | + query = "CREATE DATABASE $database IF NOT EXISTS" |
| 76 | + parameters = {"database": database} |
| 77 | + |
| 78 | + with get_session() as session: |
| 79 | + session.run(query, parameters) |
| 80 | + |
| 81 | + |
| 82 | +def drop_database(database: str) -> None: |
| 83 | + query = f"DROP DATABASE `{database}` IF EXISTS DESTROY DATA" |
| 84 | + |
| 85 | + with get_session() as session: |
| 86 | + session.run(query) |
| 87 | + |
| 88 | + |
| 89 | +def drop_subgraph(database: str, root_node_label: str, root_node_id: str) -> int: |
| 90 | + query = """ |
| 91 | + MATCH (a:__ROOT_NODE_LABEL__ {id: $root_node_id}) |
| 92 | + CALL apoc.path.subgraphNodes(a, {}) |
| 93 | + YIELD node |
| 94 | + DETACH DELETE node |
| 95 | + RETURN COUNT(node) AS deleted_nodes_count |
| 96 | + """.replace("__ROOT_NODE_LABEL__", root_node_label) |
| 97 | + parameters = {"root_node_id": root_node_id} |
| 98 | + |
| 99 | + with get_session(database) as session: |
| 100 | + result = session.run(query, parameters) |
| 101 | + |
| 102 | + try: |
| 103 | + return result.single()["deleted_nodes_count"] |
| 104 | + |
| 105 | + except neo4j.exceptions.ResultConsumedError: |
| 106 | + return 0 # As there are no nodes to delete, the result is empty |
| 107 | + |
| 108 | + |
| 109 | +# Neo4j functions related to Prowler + Cartography |
| 110 | +DATABASE_NAME_TEMPLATE = "db-{attack_paths_scan_id}" |
| 111 | + |
| 112 | + |
| 113 | +def get_database_name(attack_paths_scan_id: UUID) -> str: |
| 114 | + attack_paths_scan_id_str = str(attack_paths_scan_id).lower() |
| 115 | + return DATABASE_NAME_TEMPLATE.format(attack_paths_scan_id=attack_paths_scan_id_str) |
| 116 | + |
| 117 | + |
| 118 | +# Exceptions |
| 119 | + |
| 120 | + |
| 121 | +class GraphDatabaseQueryException(Exception): |
| 122 | + def __init__(self, message: str, code: str | None = None) -> None: |
| 123 | + super().__init__(message) |
| 124 | + self.message = message |
| 125 | + self.code = code |
| 126 | + |
| 127 | + def __str__(self) -> str: |
| 128 | + if self.code: |
| 129 | + return f"{self.code}: {self.message}" |
| 130 | + |
| 131 | + return self.message |
0 commit comments