|
1 | 1 | import base64 |
2 | | -import datetime |
| 2 | +import ipaddress |
3 | 3 | import json |
4 | 4 |
|
5 | 5 | misperrors = {"error": "Error"} |
6 | 6 |
|
7 | 7 | # possible module-types: 'expansion', 'hover' or both |
8 | 8 | moduleinfo = { |
9 | | - "version": "1", |
| 9 | + "version": "2", |
10 | 10 | "author": "Hannah Ward", |
11 | 11 | "description": "Module to export a MISP event in CEF format.", |
12 | 12 | "module-type": ["export"], |
13 | 13 | "name": "CEF Export", |
14 | 14 | "logo": "", |
15 | 15 | "requirements": [], |
16 | 16 | "features": ( |
17 | | - "The module takes a MISP event in input, to look every attribute. Each attribute matching with some predefined" |
18 | | - " types is then exported in Common Event Format.\nThus, there is no particular feature concerning MISP Events" |
19 | | - " since any event can be exported. However, 4 configuration parameters recognized by CEF format are required" |
20 | | - " and should be provided by users before exporting data: the device vendor, product and version, as well as the" |
21 | | - " default severity of data." |
| 17 | + "Exports supported event and object attributes as UTF-8 CEF file records, with standard escaping and field" |
| 18 | + " validation. IPv6 address records use CEF:1; other records use CEF:0. Device settings and severity have" |
| 19 | + " defaults. See the [usage" |
| 20 | + " guide](https://github.com/MISP/misp-modules/blob/main/documentation/export_mod/cef_export.md) for mappings" |
| 21 | + " and compatibility changes." |
22 | 22 | ), |
23 | 23 | "references": [ |
24 | | - "https://community.softwaregrp.com/t5/ArcSight-Connectors/ArcSight-Common-Event-Format-CEF-Guide/ta-p/1589306?attachment-id=65537" |
| 24 | + "https://www.microfocus.com/documentation/arcsight/arcsight-smartconnectors-24.3/pdfdoc/cef-implementation-standard/cef-implementation-standard.pdf" |
25 | 25 | ], |
26 | | - "input": "MISP Event attributes", |
| 26 | + "input": "MISP events and object attributes in standard, bare or legacy export format.", |
27 | 27 | "output": "Common Event Format file", |
28 | 28 | } |
29 | 29 |
|
|
43 | 43 |
|
44 | 44 | mispattributes = {"input": list(cefmapping.keys())} |
45 | 45 | outputFileExtension = "cef" |
46 | | -responseType = "application/txt" |
| 46 | +responseType = "text/plain" |
| 47 | +inputSource = ["event", "event-collection"] |
| 48 | +DEFAULT_CONFIG = { |
| 49 | + "Default_Severity": 1, |
| 50 | + "Device_Vendor": "MISP", |
| 51 | + "Device_Product": "MISP", |
| 52 | + "Device_Version": 1, |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +def _text(value, name, limit, header=False): |
| 57 | + if not isinstance(value, str) or not value.strip() or len(value) > limit: |
| 58 | + raise ValueError(f"{name} must be a non-empty string of at most {limit} characters.") |
| 59 | + value.encode("utf-8") |
| 60 | + if any(ord(char) < 32 and (header or char not in "\r\n\t") or ord(char) == 127 for char in value): |
| 61 | + raise ValueError(f"{name} contains an unsupported control character.") |
| 62 | + return value |
| 63 | + |
| 64 | + |
| 65 | +def _header(value, name, limit): |
| 66 | + if type(value) is int: |
| 67 | + value = str(value) |
| 68 | + value = _text(value, name, limit, header=True) |
| 69 | + return value.replace("\\", "\\\\").replace("|", "\\|") |
| 70 | + |
| 71 | + |
| 72 | +def _extension(value): |
| 73 | + return value.replace("\\", "\\\\").replace("=", "\\=").replace("\n", "\\n").replace("\r", "\\r") |
| 74 | + |
| 75 | + |
| 76 | +def _severity(value): |
| 77 | + if type(value) is int and 0 <= value <= 10: |
| 78 | + return str(value) |
| 79 | + if isinstance(value, str): |
| 80 | + if value in ("Unknown", "Low", "Medium", "High", "Very-High"): |
| 81 | + return value |
| 82 | + if value.isascii() and value.isdecimal() and 0 <= int(value) <= 10: |
| 83 | + return str(int(value)) |
| 84 | + raise ValueError("Default_Severity must be an integer from 0 to 10 or Unknown, Low, Medium, High, Very-High.") |
| 85 | + |
| 86 | + |
| 87 | +def _records(container, key): |
| 88 | + records = container.get(key, []) |
| 89 | + if not isinstance(records, list) or any(not isinstance(record, dict) for record in records): |
| 90 | + raise ValueError(f"{key} must be a list of objects.") |
| 91 | + return records |
| 92 | + |
| 93 | + |
| 94 | +def _attributes(data): |
| 95 | + if isinstance(data, dict): |
| 96 | + data = [data] |
| 97 | + if not isinstance(data, list) or any(not isinstance(event, dict) for event in data): |
| 98 | + raise ValueError("data must be a MISP event or a list of events.") |
| 99 | + for envelope in data: |
| 100 | + event = envelope.get("Event", envelope) |
| 101 | + if not isinstance(event, dict): |
| 102 | + raise ValueError("Event must be an object.") |
| 103 | + # Legacy exports place collections alongside the Event metadata. |
| 104 | + collections = dict(event, **envelope) |
| 105 | + yield from _records(collections, "Attribute") |
| 106 | + for obj in _records(collections, "Object"): |
| 107 | + yield from _records(obj, "Attribute") |
| 108 | + |
| 109 | + |
| 110 | +def _record(attr, device, severity): |
| 111 | + kind = attr.get("type") |
| 112 | + if not isinstance(kind, str) or kind not in cefmapping: |
| 113 | + return None |
| 114 | + key = cefmapping[kind] |
| 115 | + value = _text(attr.get("value"), kind, 255 if key == "fileHash" else 1023) |
| 116 | + cef_version = 0 |
| 117 | + if key in ("src", "dst"): |
| 118 | + address = ipaddress.ip_address(value) |
| 119 | + if "%" in value: |
| 120 | + raise ValueError("Scoped IPv6 addresses cannot be represented in a CEF address field.") |
| 121 | + value = str(address) |
| 122 | + cef_version = int(address.version == 6) |
| 123 | + category = _text(attr.get("category", kind), "category", 512, header=True) |
| 124 | + name = _header(category, "category", 512) |
| 125 | + extension = [(key, value), ("cat", category)] |
| 126 | + if "timestamp" in attr: |
| 127 | + timestamp = attr["timestamp"] |
| 128 | + if not (type(timestamp) is int and timestamp >= 0) and not ( |
| 129 | + isinstance(timestamp, str) and timestamp.isascii() and timestamp.isdecimal() |
| 130 | + ): |
| 131 | + raise ValueError("Attribute timestamp must be non-negative Unix seconds.") |
| 132 | + extension.extend( |
| 133 | + [("deviceCustomDate1", str(int(timestamp) * 1000)), ("deviceCustomDate1Label", "MISP attribute timestamp")] |
| 134 | + ) |
| 135 | + fields = [f"CEF:{cef_version}", *device, kind, name, severity] |
| 136 | + return "|".join(fields) + "|" + " ".join(f"{key}={_extension(value)}" for key, value in extension) |
47 | 137 |
|
48 | 138 |
|
49 | 139 | def handler(q=False): |
50 | 140 | if q is False: |
51 | 141 | return False |
52 | | - request = json.loads(q) |
53 | | - if "config" in request: |
54 | | - config = request["config"] |
55 | | - else: |
56 | | - config = { |
57 | | - "Default_Severity": 1, |
58 | | - "Device_Vendor": "MISP", |
59 | | - "Device_Product": "MISP", |
60 | | - "Device_Version": 1, |
61 | | - } |
62 | | - |
63 | | - data = request["data"] |
64 | | - response = "" |
65 | | - for ev in data: |
66 | | - event = ev["Attribute"] |
67 | | - for attr in event: |
68 | | - if attr["type"] in cefmapping: |
69 | | - response += "{} host CEF:0|{}|{}|{}|{}|{}|{}|{}={}\n".format( |
70 | | - datetime.datetime.fromtimestamp(int(attr["timestamp"])).strftime("%b %d %H:%M:%S"), |
71 | | - config["Device_Vendor"], |
72 | | - config["Device_Product"], |
73 | | - config["Device_Version"], |
74 | | - attr["category"], |
75 | | - attr["category"], |
76 | | - config["Default_Severity"], |
77 | | - cefmapping[attr["type"]], |
78 | | - attr["value"], |
79 | | - ) |
80 | | - |
81 | | - r = { |
82 | | - "response": [], |
83 | | - "data": str(base64.b64encode(bytes(response, "utf-8")), "utf-8"), |
84 | | - } |
85 | | - return r |
| 142 | + try: |
| 143 | + request = json.loads(q) |
| 144 | + if not isinstance(request, dict) or "data" not in request: |
| 145 | + raise ValueError("A request object with data is required.") |
| 146 | + supplied_config = request.get("config", {}) |
| 147 | + if not isinstance(supplied_config, dict): |
| 148 | + raise ValueError("config must be an object.") |
| 149 | + config = {**DEFAULT_CONFIG, **supplied_config} |
| 150 | + severity = _severity(config["Default_Severity"]) |
| 151 | + device = [ |
| 152 | + _header(config[key], key, limit) |
| 153 | + for key, limit in (("Device_Vendor", 63), ("Device_Product", 63), ("Device_Version", 31)) |
| 154 | + ] |
| 155 | + lines = [] |
| 156 | + for attr in _attributes(request["data"]): |
| 157 | + line = _record(attr, device, severity) |
| 158 | + if line is not None: |
| 159 | + lines.append(line + "\n") |
| 160 | + return {"response": [], "data": base64.b64encode("".join(lines).encode("utf-8")).decode("ascii")} |
| 161 | + except (TypeError, ValueError) as error: |
| 162 | + return {"error": f"Unable to export CEF: {error}"} |
86 | 163 |
|
87 | 164 |
|
88 | 165 | def introspection(): |
89 | | - modulesetup = {} |
90 | | - try: |
91 | | - responseType |
92 | | - modulesetup["responseType"] = responseType |
93 | | - except NameError: |
94 | | - pass |
95 | | - try: |
96 | | - userConfig |
97 | | - modulesetup["userConfig"] = userConfig |
98 | | - except NameError: |
99 | | - pass |
100 | | - try: |
101 | | - outputFileExtension |
102 | | - modulesetup["outputFileExtension"] = outputFileExtension |
103 | | - except NameError: |
104 | | - pass |
105 | | - try: |
106 | | - inputSource |
107 | | - modulesetup["inputSource"] = inputSource |
108 | | - except NameError: |
109 | | - pass |
110 | | - return modulesetup |
| 166 | + return { |
| 167 | + **mispattributes, |
| 168 | + "responseType": responseType, |
| 169 | + "outputFileExtension": outputFileExtension, |
| 170 | + "inputSource": inputSource, |
| 171 | + } |
111 | 172 |
|
112 | 173 |
|
113 | 174 | def version(): |
|
0 commit comments