Debian Codegraph @

artifacts/source_type.py

raw
1 # -*- coding: utf-8 -*-
2 """The source type objects.
3
4 The source type objects define the source of the artifact data. In earlier
5 versions of the artifact definitions collector definitions had a similar
6 purpose as the source type. Currently the following source types are defined:
7 * artifact; the source is one or more artifact definitions;
8 * file; the source is one or more files;
9 * path; the source is one or more paths;
10 * Windows Registry key; the source is one or more Windows Registry keys;
11 * Windows Registry value; the source is one or more Windows Registry values;
12 * WMI query; the source is a Windows Management Instrumentation query.
13
14 The difference between the file and path source types are that file should
15 be used to define file entries that contain data and path, file entries that
16 define a location. E.g. on Windows %SystemRoot% could be considered a path
17 artifact definition, pointing to a location e.g. C:\\Windows. And where
18 C:\\Windows\\System32\\winevt\\Logs\\AppEvent.evt a file artifact definition,
19 pointing to the Application Event Log file.
20 """
21
22 import abc
23
24 from artifacts import definitions
25 from artifacts import errors
26
27
28 class SourceType(object):
29 """Artifact definition source type interface."""
30
31 # Note that redundant-returns-doc is broken for pylint 1.7.x for
32 # abstract methods.
33 # pylint: disable=redundant-returns-doc
34
35 TYPE_INDICATOR = None
36
37 def __init__(self):
38 """Initializes an artifact definition source type.
39
40 Raises:
41 FormatError: if the indicator is not defined.
42 """
43 super(SourceType, self).__init__()
44
45 if not self.TYPE_INDICATOR:
46 raise errors.FormatError('Missing type indicator.')
47
48 @property
49 def type_indicator(self):
50 """str: type indicator."""
51 return self.TYPE_INDICATOR
52
53 @abc.abstractmethod
54 def AsDict(self):
55 """Represents a source type as a dictionary.
56
57 Returns:
58 dict[str, str]: source type attributes.
59 """
60
61
62 class ArtifactGroupSourceType(SourceType):
63 """Artifact group source type."""
64
65 TYPE_INDICATOR = definitions.TYPE_INDICATOR_ARTIFACT_GROUP
66
67 def __init__(self, names=None):
68 """Initializes a source type.
69
70 Args:
71 names (Optional[str]): artifact definition names.
72
73 Raises:
74 FormatError: when artifact names is not set.
75 """
76 if not names:
77 raise errors.FormatError('Missing names value.')
78
79 super(ArtifactGroupSourceType, self).__init__()
80 self.names = names
81
82 def AsDict(self):
83 """Represents a source type as a dictionary.
84
85 Returns:
86 dict[str, str]: source type attributes.
87 """
88 return {'names': self.names}
89
90
91 class CommandSourceType(SourceType):
92 """Command source type."""
93
94 TYPE_INDICATOR = definitions.TYPE_INDICATOR_COMMAND
95
96 def __init__(self, args=None, cmd=None):
97 """Initializes a source type.
98
99 Args:
100 args (list[str]): arguments to the command to run.
101 cmd (str): command to run.
102
103 Raises:
104 FormatError: when args or cmd is not set.
105 """
106 if args is None or cmd is None:
107 raise errors.FormatError('Missing args or cmd value.')
108
109 super(CommandSourceType, self).__init__()
110 self.args = args
111 self.cmd = cmd
112
113 def AsDict(self):
114 """Represents a source type as a dictionary.
115
116 Returns:
117 dict[str, str]: source type attributes.
118 """
119 return {'cmd': self.cmd, 'args': self.args}
120
121
122 class DirectorySourceType(SourceType):
123 """Directory source type."""
124
125 TYPE_INDICATOR = definitions.TYPE_INDICATOR_DIRECTORY
126
127 def __init__(self, paths=None, separator='/'):
128 """Initializes a source type.
129
130 Args:
131 paths (Optional[str]): paths relative to the root of the file system.
132 separator (Optional[str]): path segment separator.
133
134 Raises:
135 FormatError: when paths is not set or not a list type.
136 """
137 if not paths:
138 raise errors.FormatError('Missing paths value.')
139
140 if not isinstance(paths, list):
141 raise errors.FormatError('Invalid paths value, not a list.')
142
143 super(DirectorySourceType, self).__init__()
144 self.paths = paths
145 self.separator = separator
146
147 def AsDict(self):
148 """Represents a source type as a dictionary.
149
150 Returns:
151 dict[str, str]: source type attributes.
152 """
153 source_type_attributes = {'paths': self.paths}
154 if self.separator != '/':
155 source_type_attributes['separator'] = self.separator
156
157 return source_type_attributes
158
159
160 class FileSourceType(SourceType):
161 """File source type."""
162
163 TYPE_INDICATOR = definitions.TYPE_INDICATOR_FILE
164
165 def __init__(self, paths=None, separator='/'):
166 """Initializes a source type.
167
168 Args:
169 paths (Optional[str]): paths relative to the root of the file system.
170 separator (Optional[str]): path segment separator.
171
172 Raises:
173 FormatError: when paths is not set or not a list type.
174 """
175 if not paths:
176 raise errors.FormatError('Missing paths value.')
177
178 if not isinstance(paths, list):
179 raise errors.FormatError('Invalid paths value, not a list.')
180
181 super(FileSourceType, self).__init__()
182 self.paths = paths
183 self.separator = separator
184
185 def AsDict(self):
186 """Represents a source type as a dictionary.
187
188 Returns:
189 dict[str, str]: source type attributes.
190 """
191 source_type_attributes = {'paths': self.paths}
192 if self.separator != '/':
193 source_type_attributes['separator'] = self.separator
194
195 return source_type_attributes
196
197
198 class PathSourceType(SourceType):
199 """Path source type."""
200
201 TYPE_INDICATOR = definitions.TYPE_INDICATOR_PATH
202
203 def __init__(self, paths=None, separator='/'):
204 """Initializes a source type.
205
206 Args:
207 paths (Optional[str]): paths relative to the root of the file system.
208 separator (Optional[str]): path segment separator.
209
210 Raises:
211 FormatError: when paths is not set or not a list type.
212 """
213 if not paths:
214 raise errors.FormatError('Missing paths value.')
215
216 if not isinstance(paths, list):
217 raise errors.FormatError('Invalid paths value, not a list.')
218
219 super(PathSourceType, self).__init__()
220 self.paths = paths
221 self.separator = separator
222
223 def AsDict(self):
224 """Represents a source type as a dictionary.
225
226 Returns:
227 dict[str, str]: source type attributes.
228 """
229 source_type_attributes = {'paths': self.paths}
230 if self.separator != '/':
231 source_type_attributes['separator'] = self.separator
232
233 return source_type_attributes
234
235
236 class WindowsRegistryKeySourceType(SourceType):
237 """Windows Registry key source type."""
238
239 TYPE_INDICATOR = definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_KEY
240
241 VALID_PREFIXES = [
242 r'HKEY_LOCAL_MACHINE',
243 r'HKEY_USERS',
244 r'HKEY_CLASSES_ROOT',
245 r'%%current_control_set%%',
246 ]
247
248 def __init__(self, keys=None):
249 """Initializes a source type.
250
251 Args:
252 keys (Optional[list[str]]): key paths relative to the root of
253 the Windows Registry.
254
255 Raises:
256 FormatError: when keys is not set.
257 """
258 if not keys:
259 raise errors.FormatError('Missing keys value.')
260
261 if not isinstance(keys, list):
262 raise errors.FormatError('keys must be a list')
263
264 for key in keys:
265 self.ValidateKey(key)
266
267 super(WindowsRegistryKeySourceType, self).__init__()
268 self.keys = keys
269
270 def AsDict(self):
271 """Represents a source type as a dictionary.
272
273 Returns:
274 dict[str, str]: source type attributes.
275 """
276 return {'keys': self.keys}
277
278 @classmethod
279 def ValidateKey(cls, key_path):
280 """Validates this key against supported key names.
281
282 Args:
283 key_path (str): path of a Windows Registry key.
284
285 Raises:
286 FormatError: when key is not supported.
287 """
288 for prefix in cls.VALID_PREFIXES:
289 if key_path.startswith(prefix):
290 return
291
292 # TODO: move check to validator.
293 if key_path.startswith('HKEY_CURRENT_USER\\'):
294 raise errors.FormatError(
295 'HKEY_CURRENT_USER\\ is not supported instead use: '
296 'HKEY_USERS\\%%users.sid%%\\')
297
298 raise errors.FormatError(f'Unupported Registry key path: {key_path:s}')
299
300
301 class WindowsRegistryValueSourceType(SourceType):
302 """Windows Registry value source type."""
303
304 TYPE_INDICATOR = definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE
305
306 def __init__(self, key_value_pairs=None):
307 """Initializes a source type.
308
309 Args:
310 key_value_pairs (Optional[list[tuple[str, str]]]): key path and value
311 name pairs, where key paths are relative to the root of the Windows
312 Registry.
313
314 Raises:
315 FormatError: when key value pairs is not set.
316 """
317 if not key_value_pairs:
318 raise errors.FormatError('Missing key value pairs value.')
319
320 if not isinstance(key_value_pairs, list):
321 raise errors.FormatError('key_value_pairs must be a list')
322
323 for pair in key_value_pairs:
324 if not isinstance(pair, dict):
325 raise errors.FormatError('key_value_pair must be a dict')
326
327 if set(pair.keys()) != set(['key', 'value']):
328 key_value_pairs = ', '.join([
329 f'{key:s}: {value:s}' for key, value in key_value_pairs])
330 raise errors.FormatError((
331 f'key_value_pair missing "key" and "value" keys, got: '
332 f'{key_value_pairs:s}'))
333
334 WindowsRegistryKeySourceType.ValidateKey(pair['key'])
335
336 super(WindowsRegistryValueSourceType, self).__init__()
337 self.key_value_pairs = key_value_pairs
338
339 def AsDict(self):
340 """Represents a source type as a dictionary.
341
342 Returns:
343 dict[str, str]: source type attributes.
344 """
345 return {'key_value_pairs': self.key_value_pairs}
346
347
348 class WMIQuerySourceType(SourceType):
349 """WMI query source type.
350
351 Attributes:
352 base_object (str): WMI base object.
353 query (str): WMI query.
354 """
355
356 TYPE_INDICATOR = definitions.TYPE_INDICATOR_WMI_QUERY
357
358 def __init__(self, base_object=None, query=None):
359 """Initializes a source type.
360
361 Args:
362 base_object (Optional[str]): WMI base object.
363 query (Optional[str]): WMI query.
364
365 Raises:
366 FormatError: when query is not set.
367 """
368 if not query:
369 raise errors.FormatError('Missing query value.')
370
371 super(WMIQuerySourceType, self).__init__()
372 self.base_object = base_object
373 self.query = query
374
375 def AsDict(self):
376 """Represents a source type as a dictionary.
377
378 Returns:
379 dict[str, str]: source type attributes.
380 """
381 source_type_attributes = {'query': self.query}
382 if self.base_object:
383 source_type_attributes['base_object'] = self.base_object
384
385 return source_type_attributes
386
387
388 class SourceTypeFactory(object):
389 """Source type factory."""
390
391 _source_type_classes = {
392 definitions.TYPE_INDICATOR_ARTIFACT_GROUP: ArtifactGroupSourceType,
393 definitions.TYPE_INDICATOR_COMMAND: CommandSourceType,
394 definitions.TYPE_INDICATOR_DIRECTORY: DirectorySourceType,
395 definitions.TYPE_INDICATOR_FILE: FileSourceType,
396 definitions.TYPE_INDICATOR_PATH: PathSourceType,
397 definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_KEY:
398 WindowsRegistryKeySourceType,
399 definitions.TYPE_INDICATOR_WINDOWS_REGISTRY_VALUE:
400 WindowsRegistryValueSourceType,
401 definitions.TYPE_INDICATOR_WMI_QUERY: WMIQuerySourceType,
402 }
403
404 @classmethod
405 def CreateSourceType(cls, type_indicator, attributes):
406 """Creates a source type.
407
408 Args:
409 type_indicator (str): source type indicator.
410 attributes (dict[str, object]): source type attributes.
411
412 Returns:
413 SourceType: a source type.
414
415 Raises:
416 FormatError: if the type indicator is not set or unsupported,
417 or if required attributes are missing.
418 """
419 if type_indicator not in cls._source_type_classes:
420 raise errors.FormatError(
421 f'Unsupported type indicator: {type_indicator:s}.')
422
423 return cls._source_type_classes[type_indicator](**attributes)
424
425 @classmethod
426 def DeregisterSourceType(cls, source_type_class):
427 """Deregisters a source type.
428
429 Source types are identified based on their type indicator.
430
431 Args:
432 source_type_class (type): source type.
433
434 Raises:
435 KeyError: if a source type is not set for the corresponding type
436 indicator.
437 """
438 if source_type_class.TYPE_INDICATOR not in cls._source_type_classes:
439 raise KeyError((
440 f'Source type not set for type: '
441 f'{source_type_class.TYPE_INDICATOR:s}.'))
442
443 del cls._source_type_classes[source_type_class.TYPE_INDICATOR]
444
445 @classmethod
446 def GetSourceTypes(cls):
447 """Retrieves the source types.
448
449 Returns:
450 list[type]: source types.
451 """
452 return cls._source_type_classes.values()
453
454 @classmethod
455 def GetSourceTypeIndicators(cls):
456 """Retrieves the source type indicators.
457
458 Returns:
459 list[str]: source type indicators.
460 """
461 return cls._source_type_classes.keys()
462
463 @classmethod
464 def RegisterSourceType(cls, source_type_class):
465 """Registers a source type.
466
467 Source types are identified based on their type indicator.
468
469 Args:
470 source_type_class (type): source type.
471
472 Raises:
473 KeyError: if source types is already set for the corresponding
474 type indicator.
475 """
476 if source_type_class.TYPE_INDICATOR in cls._source_type_classes:
477 raise KeyError((
478 f'Source type already set for type: '
479 f'{source_type_class.TYPE_INDICATOR:s}.'))
480
481 cls._source_type_classes[source_type_class.TYPE_INDICATOR] = (
482 source_type_class)
483
484 @classmethod
485 def RegisterSourceTypes(cls, source_type_classes):
486 """Registers source types.
487
488 Source types are identified based on their type indicator.
489
490 Args:
491 source_type_classes (list[type]): source types.
492 """
493 for source_type_class in source_type_classes:
494 cls.RegisterSourceType(source_type_class)