Debian Codegraph @

swig/openscap_api.py

raw symbols SCIP
1 # This file is a wrapper for python API for openscap
2 # library
3 #
4 # Copyright 2010 Red Hat Inc., Durham, North Carolina.
5 # All Rights Reserved.
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 #
21 # Authors:
22 # Maros Barabas <[email protected]>
23
24 """Python module for openscap implementing openscap API
25 """
26 __author__ = 'Maros Barabas'
27 __version__ = '1.0'
28
29 import logging # Logger for debug/info/error messages
30 import re
31
32 logger = logging.getLogger("openscap")
33
34
35 def _import_helper():
36 from os.path import dirname
37 import importlib.machinery
38 import importlib.util
39 spec = importlib.machinery.PathFinder.find_spec('_openscap_py', [dirname(__file__)])
40 if not spec:
41 spec = importlib.machinery.PathFinder.find_spec('_openscap_py')
42 if not spec:
43 raise ImportError("Unable to import _openscap_py module, extra path: '%s'."
44 % dirname(__file__))
45 mod = importlib.util.module_from_spec(spec)
46 spec.loader.exec_module(mod)
47 return mod
48
49
50 OSCAP = _import_helper()
51 del _import_helper
52
53 import os
54
55
56 def extract_type_from_obj(obj):
57 # Extract the name of structure from the representation of the object
58 # "<Swig Object of type 'struct xccdf_result_iterator *' at 0x7f8f65fc1390>"
59 # or "<Swig Object of type 'oval_agent_session_t *' at 0x7f9aa2cdf360>"
60 return re.findall(r"type '(struct )?(\b\S*\b)", obj.__repr__())[0][1]
61
62
63 class OSCAP_List(list):
64 """OSCAP List class is designed to store lists generated from openscap iterators.
65 All functions that return iterators are preprocessed by creation of OSCAP List instance
66 and move all objects given by oscap list iteration loop to list.
67
68 OSCAP List class implement standard Python list."""
69
70 def remove(self, item):
71 """Function to remove item from list. This removed item should be also
72 removed from parent oscap list. This function is supported only if there exists
73 reset function on iterators. Exception is throwed otherwise."""
74 try:
75 self.iterator.reset()
76 while self.iterator.has_more():
77 litem = self.iterator.next()
78 if (type(item) == str and type(litem) == str and litem == item) or \
79 ("instance" in item.__dict__ and litem.instance == item.instance):
80
81 self.iterator.remove()
82
83 '''
84 Warning, list.remove(self, item) will fail because python yield
85 a new reference at each loop. So wee need to loop again into the python list,
86 get the new reference and remove it. Demo:
87
88 print(item.instance)
89 print(litem.instance)
90 print(litem.instance == item.instance)
91
92 RETURNS:
93
94 <Swig Object of type 'struct xccdf_refine_value *' at 0x7ff85ed73bd0>
95 <Swig Object of type 'struct xccdf_refine_value *' at 0x7ff85ed73c90>
96 True
97 '''
98
99 for i in self[:]:
100 if "instance" in item.__dict__ and i.instance == item.instance:
101 list.remove(self, i)
102
103 except NameError:
104 raise Exception("Removing %s items throught oscap list is not allowed. "
105 "Please use appropriate function."
106 % (self.iterator.object[:self.iterator.object.find("_iterator")],))
107
108 def __del__(self):
109 """Free the list structure"""
110 self.iterator.free()
111
112 def generate(self, iterator):
113 """Generate all object from oscap list throught iterators and store them in list object.
114 Do not call this function on your own !"""
115 self.iterator = iterator
116
117 while iterator.has_more():
118 list.append(self, iterator.next())
119
120 def append(self, item, n=1):
121 """This function is not allowed. Please use appropriate function from library."""
122 raise Exception("Append %s item throught oscap list is not allowed. "
123 "Please use appropriate function."
124 % (self.iterator.object[:self.iterator.object.find("_iterator")],))
125
126 def extend(self, item, n=1):
127 """This function is not allowed. Please use appropriate function from library."""
128 raise Exception("Extending %s items throught oscap list is not allowed. "
129 "Please use appropriate function."
130 % (self.iterator.object[:self.iterator.object.find("_iterator")],))
131
132 def insert(self, item, n=1):
133 """This function is not allowed. Please use appropriate function from library."""
134 raise Exception("Inserting %s items to oscap list is not allowed. "
135 "Please use appropriate function."
136 % (self.iterator.object[:self.iterator.object.find("_iterator")],))
137
138 def sort(self, item, n=1):
139 """This function is not allowed. Please use appropriate function from library."""
140 raise Exception("Sorting %s items in oscap list is not allowed."
141 % (self.iterator.object[:self.iterator.object.find("_iterator")],))
142
143 def reverse(self, item, n=1):
144 """This function is not allowed. Please use appropriate function from library."""
145 raise Exception("Reversing %s items in oscap list is not allowed."
146 % (self.iterator.object[:self.iterator.object.find("_iterator")],))
147
148
149 class OSCAP_Object(object):
150 """
151 Abstract class that represents all structures, functions and averything from
152 openscap library. Each structure from library is mapped inside OSCAP Object
153 with "object" and "instance" parameters.
154
155 "object" is variable of this class that keeps string representation of
156 type of the structure
157 "instance" is a variable of this class that keeps the pointer to the real
158 C structure.
159 """
160
161 def __init__(self, object, instance=None):
162 """ Called when the instance is created """
163 dict.__setattr__(self, "object", object)
164 dict.__setattr__(self, "instance", instance)
165
166 @staticmethod
167 def new(retobj):
168 if type(retobj).__name__ in ('SwigPyObject', 'PySwigObject'):
169 return OSCAP_Object(extract_type_from_obj(retobj), retobj)
170 else:
171 return retobj
172
173 def __eq__(self, other):
174 """ Two OSCAP Objects are compared by their string representations
175 which reflect type and instance.
176 """
177 return str.__eq__(self.__repr__(), other.__repr__())
178
179 def __repr__(self):
180 return "<Oscap Object of type '%s' with instance '%s'>" % (self.object, self.instance)
181
182 def __func_wrapper(self, func, value=None):
183 """ This is only a wrapper for getter_wrapper - another wrapper for
184 openscap library functions.
185 """
186
187 def __getter_wrapper(*args, **kwargs):
188 """ This function is a wrapper for function objects of openscap library.
189 Each function is called with variable number of parameters cause we don't
190 know how many parameters each function takes. This is based on try-except
191 methot that we try to call the function and if it fell down we try another
192 number of parameters.
193 This is based on knowledge that C language will always
194 cause error when the function is called with wrong number of parameters.
195 """
196 newargs = ()
197 for arg in args:
198 if isinstance(arg, OSCAP_Object):
199 newargs += (arg.instance,)
200 else:
201 newargs += (arg,)
202
203 try:
204 retobj = func()
205 except TypeError as err:
206 try:
207 retobj = func(*newargs)
208 except TypeError as err:
209 if self.instance:
210 try:
211 retobj = func(self.instance)
212 except TypeError as err:
213 try:
214 retobj = func(self.instance, *newargs)
215 except TypeError as err:
216 raise TypeError(
217 "Wrong number of arguments in function %s" % (func.__name__,))
218 else:
219 raise TypeError(
220 "%s: No instance or wrong number of parameters" % (func.__name__))
221
222 if retobj is None:
223 return None
224 elif retobj.__str__().find("iterator") != -1:
225 # We have an iterator here
226 list = OSCAP_List()
227 list.generate(OSCAP_Object.new(retobj))
228 list.object = self.object
229 return list
230 return OSCAP_Object.new(retobj)
231
232 return __getter_wrapper
233
234 def introspect_all(self):
235 """ Listing all builtin functions accessible through SWIG """
236 return OSCAP.__dict__
237
238 def introspect_functions(self):
239 ''' Returns all builtin function accessible through SWIG
240 which is corresponding to the current object
241 '''
242 funcs = dict()
243 for (k, v) in OSCAP.__dict__.items():
244 if k.startswith(self.object):
245 funcs[k] = v
246 return funcs
247
248 def introspect_constants(self, value=None, prefix=None):
249 '''
250 Returns constants names / values, given a value and/or a name filter (regex)
251 Example, introspect_constants(1, "XCCDF_RESULT") returns {XCCDF_RESULT_PASS: 1}
252
253 !!! constants are here designated by C enums (=> numeric value)
254 '''
255 return {k: v for k, v in OSCAP.__dict__.items() if (value is None or v == value) and
256 (isinstance(v, int)) and (prefix is None or k.startswith(prefix))}
257
258 def __getattr__(self, name):
259 """ Called when an attribute lookup has not found the attribute in the usual places (i.e.
260 it is not an instance attribute nor is it found in the class tree for self). name is
261 the attribute name."""
262
263 if name == "export" and self.object == "xccdf_policy":
264 return self.policy_export
265
266 if name in self.__dict__:
267 return self.__dict__[name]
268
269 # cache self.object + "_" + name for perf / clearness purpose
270 obj_name = self.object + "_" + name
271
272 """ Catch potential C function overriden in OSCAP_Object
273 like xccdf_session_set_rule or xccdf_session_free for instance. """
274 if obj_name in dir(OSCAP_Object):
275 func = getattr(OSCAP_Object, obj_name)
276 if callable(func):
277 return self.__func_wrapper(func)
278
279 # If attribute is not in a local dictionary, look for it in a library
280 func = OSCAP.__dict__.get(name)
281 if func is not None:
282 return func
283
284 """ Looking for function object_subject() """
285 obj = OSCAP.__dict__.get(obj_name)
286
287 if obj is not None:
288 if callable(obj):
289 return self.__func_wrapper(obj)
290
291 """ Looking for function object_get_subject() """
292 obj = OSCAP.__dict__.get(self.object + "_get_" + name)
293 if obj is not None:
294 try:
295 return self.__func_wrapper(obj)()
296 except:
297 return self.__func_wrapper(obj)
298
299 """ Looking if it can be a constructor """
300 obj = OSCAP.__dict__.get(obj_name + "_new")
301 if obj is not None:
302 # this will call the __call__ definition of OSCAP_Object
303 return OSCAP_Object(obj_name)
304
305 """ There is not function with the name 'name' let return the OSCAP_Object """
306 raise AttributeError("Attribute {0} not found for object {1}"
307 .format(name, self.object))
308
309 def __dir__(self):
310 """Lists all attributes inside this object.
311
312 This is mainly used by auto-completion and for dir(obj) in interactive prompt.
313 (only available in Python 2.6 and newer but doesn't hurt anything in older Pythons)
314 """
315
316 ret = list()
317 ret.extend(dir(type(self)))
318 ret.extend(list(self.__dict__))
319
320 # we intentionally don't add all functions from the library, having
321 # them in getattr has IMO not been the right call, they would just
322 # clutter everything...
323
324 for key, v in OSCAP.__dict__.items():
325 if key.startswith(self.object + "_"):
326 # the getattr wrapper only deals with callables
327 if callable(OSCAP.__dict__[key]):
328 ret.append(key[len(self.object) + 1:])
329
330 # we also don't add the object_get_{name} methods as {name}, it IMO
331 # only allows bugs to pass as working code
332
333 return sorted(ret)
334
335 def __call__(self, *args, **kwargs):
336 newargs = ()
337 for arg in args:
338 if isinstance(arg, OSCAP_Object):
339 newargs += (arg.instance,)
340 else:
341 newargs += (arg,)
342
343 # It's maybe looking for "new" ?
344 obj = OSCAP.__dict__.get(self.object + "_new")
345 if obj is not None:
346 return OSCAP_Object.new(obj(*newargs))
347 else:
348 raise NameError("name '" + self.object + "' is not defined")
349
350 def __setattr__(self, name, value):
351 if name in self.__dict__:
352 return self.__dict__[name]
353
354 obj = OSCAP.__dict__.get(self.object + "_set_" + name)
355 if obj is None:
356 obj = OSCAP.__dict__.get(self.object + "_add_" + name)
357 if obj is None:
358 return None
359
360 if isinstance(value, OSCAP_Object):
361 value = value.instance
362 return obj(self.instance, value)
363
364 """
365 def __del__(self):
366 #print "Free ", self.object
367 if "instance" in self.__dict__ and self.__dict__["instance"] != None:
368 # In what situations we need to free objects ?
369 if self.object.find("iterator") > -1:
370
371 self.free()
372 """
373
374 def free(self):
375 if self.object == "oval_agent_session":
376 return OSCAP.oval_agent_destroy_session(self.instance)
377 # print "Free on demand ", self.object
378 if "instance" in self.__dict__ and self.__dict__["instance"] is not None:
379 obj = OSCAP.__dict__.get(self.object + "_free")
380 if obj is not None:
381 if callable(obj):
382 obj(self.__dict__["instance"])
383 dict.__setattr__(self, "instance", None)
384 else:
385 raise Exception("Can't free %s" % (self.object,))
386
387 """ ********* Implementation of non-trivial functions ********* """
388
389 def xccdf_session_set_rule(self, rule):
390 OSCAP.xccdf_session_set_rule_py(self, rule)
391
392 # helper function to find easily the result of a single rule
393 # should be called in the context of a xccdf_session_set_rule
394 def xccdf_session_get_rule_result(self, rule):
395 self = OSCAP_Object("xccdf_session", self)
396 rs = self.get_xccdf_policy().get_results()[-1] # get last value
397 for rr in rs.get_rule_results():
398 if rule == rr.get_idref():
399 return rr
400
401 def xccdf_session_free(self):
402 OSCAP.xccdf_session_free_py(self)
403
404 def __start_callback(self, rule, obj):
405 return obj[0](OSCAP_Object("xccdf_rule", rule), obj[1])
406
407 def __output_callback(self, result, obj):
408 # the returned object can be a rule_result or an oval_definition_result,
409 # so I extract the right name from the object repr.
410 return obj[0](OSCAP_Object(extract_type_from_obj(result), result), obj[1])
411
412 def register_start_callback(self, cb, usr):
413 if self.object != "xccdf_policy_model":
414 raise TypeError(
415 "Wrong call of register_start_callback function on %s" % (self.object,))
416 return OSCAP.xccdf_policy_model_register_start_callback_py(
417 self.instance, self.__start_callback, (cb, usr))
418
419 def register_output_callback(self, cb, usr):
420 if self.object != "xccdf_policy_model":
421 raise TypeError(
422 "Wrong call of register_output_callback function on %s" % (self.object,))
423 return OSCAP.xccdf_policy_model_register_output_callback_py(
424 self.instance, self.__output_callback, (cb, usr))
425
426 def register_engine_oval(self, sess):
427 if self.object != "xccdf_policy_model":
428 raise TypeError(
429 "Wrong call of register_engine_oval function on %s" % (self.object,))
430 return OSCAP.xccdf_policy_model_register_engine_oval(self.instance, sess.instance)
431
432 def register_engine_sce(self, parameters):
433 if self.object != "xccdf_policy_model":
434 raise TypeError(
435 "Wrong call of register_engine_sce function on %s" % (self.object,))
436 return OSCAP.xccdf_policy_model_register_engine_sce(self.instance, parameters.instance)
437
438 def agent_eval_system(self, sess, cb, usr):
439 if self.object != "oval":
440 raise TypeError(
441 "Wrong call of oval_agent_eval_system function on %s" % (self.object,))
442 return OSCAP.oval_agent_eval_system_py(sess.instance, self.__output_callback, (cb, usr))
443
444 def query_sysinfo(self):
445 if self.object != "oval_probe_session_t":
446 raise TypeError(
447 "Wrong call of oval_probe_session_query_sysinfo function on %s" % (self.object,))
448 return OSCAP.oval_probe_session_query_sysinfo(self.instance)
449
450 def query_objects(self):
451 if self.object != "oval_probe_session_t":
452 raise TypeError(
453 "Wrong call of oval_probe_session_query_objects function on %s" % (self.object,))
454 return OSCAP.oval_probe_session_query_objects(self.instance)
455
456 """ ********* Implementation of required high level functions ********* """
457
458 def get_all_values(self):
459
460 # first ensure that we are using an item (or convert to it otherwise)
461 if self.object != "xccdf_item":
462 item = self.to_item()
463 if item is None:
464 return None
465 else:
466 item = self
467 values = []
468
469 if item.type == OSCAP.XCCDF_BENCHMARK:
470 values.extend(item.to_benchmark().values)
471 elif item.type == OSCAP.XCCDF_GROUP:
472 values.extend(item.to_group().values)
473 else:
474 return []
475
476 for content in item.content:
477 values.extend(content.get_all_values())
478
479 return values
480
481 def get_values_by_rule_id(self, id, check=None):
482 """get_values_by_rule_id -- Get all Value elements that are referenced by rule with specified ID
483 If check is not None, then it is (very ugly) recursive call
484 """
485
486 if self.object != "xccdf_policy":
487 raise TypeError(
488 "Wrong call of \"get_values_by_rule_id\" function. "
489 "Should be xccdf_policy (have %s)" % (self.object,))
490 items = []
491 values = []
492
493 # Case 1: check is not None -- we have recursive call
494 if check is not None:
495 if check.complex:
496 # This check is complext so there is more checks within
497 for child in check.children:
498 values.extend(self.get_values_by_rule_id(id, check=child))
499 else:
500 for export in check.exports:
501 values.append(export.value)
502 return values
503
504 # Case 2: check is None -- this is regular call of function
505 item = self.model.benchmark.get_item(id)
506 if item.type != OSCAP.XCCDF_RULE:
507 raise TypeError(
508 "Wrong type of item with id \"%s\". Expected XCCDF_RULE, got " % (id, item.type))
509 rule = item.to_rule()
510 for check in rule.checks:
511 if check.complex:
512 # This check is complext so there is more checks within
513 for child in check.children:
514 values.extend(self.get_values_by_rule_id(id, check=child))
515 else:
516 for export in check.exports:
517 values.append(export.value)
518
519 for value in self.model.benchmark.get_all_values():
520 if value.id in values:
521 items.append(self.__parse_value(value))
522
523 return items
524
525 def __parse_value(self, value):
526 ''' Used by get_tailoring_items() '''
527
528 # update the local lang lists
529 def __update_lang(item, lang):
530 if lang not in item["langs"]:
531 item["langs"].add(lang)
532
533 # get value properties
534 item = {}
535 item["id"] = value.id
536 item["langs"] = {self.model.benchmark.lang} # set of available langs
537 item["lang"] = self.model.benchmark.lang # legacy support of item["lang"]
538 item["titles"] = {}
539 item["descs"] = {}
540 # Titles / Questions
541 if len(value.question):
542 for question in value.question:
543 item["titles"][question.lang] = question.text
544 else:
545 for title in value.title:
546 __update_lang(item, title.lang)
547 item["titles"][title.lang] = title.text
548
549 if item["lang"] not in item["titles"]:
550 item["titles"][item["lang"]] = ""
551 # Descriptions
552 for desc in value.description:
553 __update_lang(item, desc.lang)
554 item["descs"][desc.lang] = desc.text
555 if item["lang"] not in item["descs"]:
556 item["descs"][item["lang"]] = ""
557 # Type
558 item["type"] = value.type
559 # Values
560 item["options"] = {}
561 item["choices"] = {}
562 for instance in value.instances:
563 item["options"][instance.selector] = instance.value
564 if len(instance.choices):
565 item["choices"][instance.selector] = instance.choices
566
567 # Get regexp match from match of elements
568
569 # Get regexp match from match elements
570 item["match"] = "|".join([i.match for i in value.instances if i.match])
571
572 # Get regexp match from type of value
573 if not len(item["match"]):
574 item["match"] = ["", "^[\\d]+$", "^.*$", "^[01]$"][value.type]
575
576 if self.profile is not None:
577 for r_value in self.profile.refine_values:
578 if r_value.item == value.id:
579 item["selected"] = ( # will return None if invalid selector TODO: raise err ?
580 r_value.selector, item["options"].get(r_value.selector))
581 for s_value in self.profile.setvalues:
582 if s_value.item == value.id:
583 item["selected"] = ('', s_value.value)
584
585 if "selected" not in item:
586 if "" in item["options"]:
587 item["selected"] = ('', item["options"][""])
588 else:
589 item["selected"] = ('', '')
590
591 """
592 print "ID: \r\t\t", item["id"]
593 print "Language: \r\t\t", item["lang"]
594 print "Titles: \r\t\t", item["titles"]
595 print "Descriptions: \r\t\t", item["descs"]
596 print "Type: \r\t\t", ["", "Number", "String", "Boolean"][item["type"]]
597 print "Options: \r\t\t", item["options"]
598 print "Choices: \r\t\t", item["choices"]
599 print "Match: \r\t\t", item["match"]
600 print "Selected: \r\t\t", item["selected"]
601 print
602 """
603
604 return item
605
606 def get_tailor_items(self):
607 """xccdf_policy.get_tailor_items() -- Get all items that can be tailored by tool.
608 Function will return all values that can be tailored by specified XCCDF Policy's Profile
609
610 Function will return list of items where item is dictionary with key representation:
611 "id" - id of value
612 "lang" - default language of document
613 "titles" - list of tuples (language, title)
614 "descs" - list of tuples (language, description)
615 "type" - type of value represented by integer: {0:"", 1:"Number",
616 2:"String", 3:"Boolean"}
617
618 "options" - dictionary of options where key is selector
619 and value is Value instance value
620
621 "match" - Regexp that input must match
622 "selected" - tuple (selector, value) of default or choosen value instance
623 """
624
625 if self.object != "xccdf_policy":
626 raise TypeError(
627 "Wrong call of \"get_tailor_items\" function. "
628 "Should be xccdf_policy (have %s)" % (self.object,))
629 items = []
630
631 for value in self.model.benchmark.get_all_values():
632 items.append(self.__parse_value(value))
633
634 return items
635
636 def set_tailor_items(self, items):
637 """xccdf_policy.set_tailor_items(items) -- Set tailored items to selected XCCDF Profile
638 Function will set all refine-values, setvalues to the selected XCCDF Policy's profile.
639 All refines should be specified in 'items' list.
640 All existing refine elements that are not included in 'items' list will be let unchanched.
641
642 Example:
643 value = { "id": value_id
644 "value": default_value }
645 items = [value]
646 xccdf_policy.set_tailor_items(items)"""
647
648 if self.object != "xccdf_policy":
649 raise TypeError(
650 "Wrong call of \"set_tailor_items\" function. "
651 "Should be xccdf_policy (have %s)" % (self.object,))
652 if len(items) == 0:
653 return
654
655 # items = [{id, value}]
656 for item in items:
657 selector = None
658 value = self.model.benchmark.item(item["id"]).to_value()
659 for instance in value.instances:
660 if item["value"] == instance.value:
661 selector = instance.selector
662
663 oper = remarks = setvalue = None
664 for r_value in self.profile.refine_values[:]:
665 if r_value.item == item["id"]:
666 oper = r_value.oper
667 remarks = r_value.remarks
668 self.profile.refine_values.remove(r_value)
669
670 for s_value in self.profile.setvalues[:]:
671 if s_value.item == item["id"]:
672 setvalue = s_value.value
673 self.profile.setvalues.remove(s_value)
674
675 if selector is not None and selector != '':
676 r_value = xccdf.refine_value()
677 r_value.item = item["id"]
678 r_value.selector = selector
679 if oper is not None:
680 r_value.oper = oper
681 if remarks is not None:
682 for remark in remarks:
683 r_value.add_remark(remark)
684 self.profile.add_refine_value(r_value)
685 elif selector is None:
686 s_value = xccdf.setvalue()
687 s_value.item = item["id"]
688 s_value.value = item["value"]
689 self.profile.add_setvalue(s_value)
690
691 def set_refine_rule(self, id, weight=None, severity=None, role=None):
692 """xccdf_policy.set_refine_rules(refines)
693 -- Set weight, severity and role of the rule in selected Profile.
694 Function will set all refine-rules to the selected XCCDF Policy's profile.
695
696 Example:
697 xccdf_policy.set_refine_rule("rul-2.1", severity=oscap.XCCDF_SEVERITY_HIGH)
698 """
699
700 if self.object != "xccdf_policy":
701 raise TypeError(
702 "Wrong call of \"set_refine_rule\" function. "
703 "Should be xccdf_policy (have %s)" % (self.object,))
704 if id is None:
705 raise AttributeError(
706 "Missing ID of rule in xccdf_policy.set_refine_rule function")
707
708 rule = self.model.benchmark.item(id).to_rule()
709 if rule is None:
710 raise Exception("Rule \"%s\" not found in benchmark" % (id,))
711
712 if not weight and not severity and not role:
713 return
714
715 refine = xccdf.refine_rule()
716 refine.item = id
717 for r_rule in self.profile.refine_rules[:]:
718 if r_rule.item == id:
719 refine.weight = r_rule.weight
720 refine.severity = r_rule.severity
721 refine.role = r_rule.role
722 self.profile.refine_rules.remove(r_rule)
723
724 # Set new weight of the rule
725 if weight is not None:
726 refine.weight = weight
727
728 # Set new severity of the rule
729 if severity is not None:
730 refine.severity = severity
731
732 # Set new role of the rule
733 if role is not None:
734 refine.role = role
735
736 self.profile.add_refine_rule(refine)
737
738 def get_all_rules(self):
739 """xccdf_policy.get_all_rules() -- Get all rules/selectors and titles from benchmark
740 """
741
742 if self.object != "xccdf_policy":
743 raise TypeError(
744 "Wrong call of \"get_all_rules\" function. "
745 "Should be xccdf_policy (have %s)" % (self.object,))
746 pass # TODO
747
748 def set_rules(self, rules):
749 """xccdf_policy.set_rules(rules) -- Set which rules are selected by given XCCDF Profile
750 Function set selectors for given XCCDF Policy's profile.
751 Selectors are represented by ID strings in 'rules' list
752 All existing selectors that are not included
753 in 'rules' list will be deleted.
754
755 Example:
756 # We want to have selected only first rule and second group
757 xccdf_policy.set_rules(["id-rule-1", "id-group-2"])"""
758
759 if self.object != "xccdf_policy":
760 raise TypeError(
761 "Wrong call of \"set_rules\" function. "
762 "Should be xccdf_policy (have %s)" % (self.object,))
763
764 for select in self.selects:
765 if select.item not in rules:
766 select.selected = False
767 else:
768 rules.remove(select.item)
769 select.selected = True
770
771 for id in rules:
772 select = xccdf.select()
773 select.selected = True
774 select.item = id
775 self.add_select(select)
776
777 def init(self, path, paths={}):
778 """xccdf.init(path) -- Initialize openscap library
779 Provides standard initialization of OPENScap library.
780 Parameter 'path' is the path to XCCDF File.
781 Parameter 'paths' is dictionary where key is file identificator and value path to the file.
782
783 Initialization has next steps:
784 - Parse oscap configuration file with path to XML files
785 - Import default XCCDF document as specified in configuration file
786 - Import all definitions files that are required for XCCDF evaluation
787
788 Function returns dictionary with keys:
789 "policy_model" - XCCDF Policy Model loaded from XCCDF file
790 "def_models" - list of OVAL Definitions models from OVAL files
791 "sessions" -dictionary of OVAL Agent sessions provided by OVAL Definitions models
792
793 All returned objects have to be freed by user. Use functions:
794 retval["policy_model"].free()
795 for model in retval["def_models"]:
796 model.free()
797 for sess in retval["sessions"]:
798 sess.free()
799 """
800
801 if path is None:
802 return None
803
804 OSCAP.oscap_init()
805 dirname = os.path.dirname(path)
806 f_XCCDF = path
807
808 benchmark = self.benchmark_import(f_XCCDF)
809
810 if benchmark.instance is None:
811 if OSCAP.oscap_err():
812 desc = OSCAP.oscap_err_desc()
813 else:
814 desc = "Unknown error, please report this bug (https://github.com/OpenSCAP/openscap/issues)"
815 raise ImportError(
816 "Benchmark \"%s\" loading failed: %s" % (f_XCCDF, desc))
817
818 policy_model = self.policy_model_new(benchmark)
819 files = policy_model.get_files()
820 def_models = []
821 sessions = {}
822 names = {}
823 for file in files.strings:
824 if file in paths:
825 f_OVAL = paths[file]
826 else:
827 f_OVAL = os.path.join(dirname, file)
828 if os.path.exists(f_OVAL):
829 def_model = oval.definition_model_import_source(
830 OSCAP.oscap_source_new_from_file(f_OVAL))
831 if def_model.instance is None:
832 if OSCAP.oscap_err():
833 desc = OSCAP.oscap_err_desc()
834 else:
835 desc = "Unknown error,please report this bug (https://github.com/OpenSCAP/openscap/issues)"
836 raise ImportError(
837 "Cannot import definition model for \"%s\": %s" % (f_OVAL, desc))
838 def_models.append(def_model)
839 sess = oval.agent_new_session(def_model, file)
840 if sess is None or sess.instance is None:
841 if OSCAP.oscap_err():
842 desc = OSCAP.oscap_err_desc()
843 else:
844 desc = "Unknown error,please report this bug (https://github.com/OpenSCAP/openscap/issues)"
845 raise ImportError(
846 "Cannot create agent session for \"%s\": %s" % (f_OVAL, desc))
847 sessions[file] = sess
848 names[file] = [sess, def_model]
849 policy_model.register_engine_oval(sess)
850 else:
851 # TODO manage properly warnings/debug
852 print(
853 "WARNING: Skipping %s file which is referenced from XCCDF content" % (f_OVAL,))
854 files.free()
855 return {"def_models": def_models, "sessions": sessions,
856 "policy_model": policy_model, "xccdf_path": f_XCCDF, "names": names
857 }
858
859 def policy_export(self, result=None, title=None, filename=None,
860 prefix=None, path=None, sessions=None, variables=True):
861 """Export all files for given policy.
862 """
863
864 if self.object != "xccdf_policy":
865 raise TypeError(
866 "Wrong call of \"export\" function. "
867 "Should be xccdf_policy (have %s)" % (self.object,))
868
869 '''
870 FIXME: We clone both benchmark and the result to avoid changing them
871 when just export is requested. Although this is the right behavior,
872 it is potentially wasteful, result.clone() and benchmark.clone()
873 could potentially take a lot of time to complete. A better solution would be
874 to add the result, export and then remove the result (with appropriate exception safety
875 of course) or even better, allow export with custom result list.
876 '''
877
878 result_clone = result.clone()
879 result_clone.benchmark_uri = path or "benchmark.xml"
880 o_title = common.text()
881 o_title.text = title
882 result_clone.title = o_title
883 result_clone.fill_sysinfo()
884
885 files = [filename]
886
887 benchmark_clone = self.model.benchmark.clone()
888
889 for model in benchmark_clone.models:
890 result_clone.score = self.score(result_clone, model.system)
891
892 benchmark_clone.add_result(result_clone)
893
894 benchmark_clone.export(filename)
895
896 dirname = os.path.dirname(filename)
897 for path in sessions.keys():
898 sess = sessions[path]
899 rmodel = oval.agent_get_results_model(sess)
900 pfile = path + ".result.xml"
901 OSCAP.oval_results_model_export(
902 rmodel.instance, None, os.path.join(dirname, pfile))
903 files.append(pfile)
904 if variables:
905 dmodel = rmodel.definition_model
906 for i, vmodel in enumerate(dmodel.variable_models):
907 vfile = "%s.variables-%d.xml" % (path, i)
908 vmodel.export(os.path.join(dirname, vfile))
909 files.append(vfile)
910
911 return files
912
913 def destroy(self, sdir):
914
915 OSCAP.oscap_cleanup()
916 for model in sdir["def_models"] + sdir["sessions"].values() + [sdir["policy_model"]]:
917 model.free()
918
919
920 # ------------------------------------------------------------------------------------------------------------
921 # DS
922
923 class DS_Class(OSCAP_Object):
924
925 def __init__(self):
926 dict.__setattr__(self, "object", "ds")
927 # dict.__setattr__(self, "version", OSCAP.oval_definition_model_supported())
928
929 def __repr__(self):
930 return "<Oscap Object of type 'DS Class' at %s>" % (hex(id(self)),)
931
932
933 # ------------------------------------------------------------------------------------------------------------
934 # XCCDF
935
936 class _XCCDF_Benchmark_Class(OSCAP_Object):
937
938 def __init__(self, path):
939 dict.__setattr__(self, "object", "xccdf_benchmark")
940 dict.__setattr__(self, "instance", OSCAP.xccdf_benchmark_import_source(
941 OSCAP.oscap_source_new_from_file(path)))
942
943 def __repr__(self):
944 return "<Oscap Object of type 'XCCDF Benchmark' at %s>" % (hex(id(self)),)
945
946
947 class XCCDF_Class(OSCAP_Object):
948
949 def __init__(self):
950 dict.__setattr__(self, "object", "xccdf")
951 dict.__setattr__(self, "version", OSCAP.xccdf_benchmark_supported())
952 pass
953
954 def __repr__(self):
955 return "<Oscap Object of type 'XCCDF Class' at %s>" % (hex(id(self)),)
956
957 """ Import XCCDF Benchmark
958 """
959 def benchmark_import(self, path):
960 return _XCCDF_Benchmark_Class(path)
961
962
963 # ------------------------------------------------------------------------------------------------------------
964 # OVAL
965
966 class OVAL_Class(OSCAP_Object):
967
968 def __init__(self):
969 dict.__setattr__(self, "object", "oval")
970 dict.__setattr__(
971 self, "version", OSCAP.oval_definition_model_supported())
972 pass
973
974 def __repr__(self):
975 return "<Oscap Object of type 'OVAL Class' at %s>" % (hex(id(self)),)
976
977
978 # ------------------------------------------------------------------------------------------------------------
979 # CVE
980
981 class CVE_Class(OSCAP_Object):
982 """
983 CVE Class
984 """
985
986 def __init__(self):
987 dict.__setattr__(self, "object", "cve")
988 # dict.__setattr__(self, "version", OSCAP.cve_model_supported())
989 pass
990
991 def __repr__(self):
992 return "<Oscap Object of type 'CVE Class' at %s>" % (hex(id(self)),)
993
994 # ------------------------------------------------------------------------------------------------------------
995 # CPE
996
997
998 class CPE_Class(OSCAP_Object):
999 """
1000 CPE Class
1001 """
1002
1003 def __init__(self):
1004 dict.__setattr__(self, "object", "cpe")
1005 dict.__setattr__(self, "version", "CPE Lang: %s; CPE Dict: %s; CPE Name: %s"
1006 % (OSCAP.cpe_lang_model_supported(),
1007 OSCAP.cpe_dict_model_supported(),
1008 OSCAP.cpe_name_supported()))
1009 pass
1010
1011 def __repr__(self):
1012 return "<Oscap Object of type 'CPE Class' at %s>" % (hex(id(self)),)
1013
1014 # ------------------------------------------------------------------------------------------------------------
1015 # SCE
1016
1017
1018 class SCE_Class(OSCAP_Object):
1019 """
1020 SCE Class
1021 """
1022
1023 def __init__(self):
1024 dict.__setattr__(self, "object", "sce")
1025 pass
1026
1027 def __repr__(self):
1028 return "<Oscap Object of type 'SCE Class' at %s>" % (hex(id(self)),)
1029
1030 # ------------------------------------------------------------------------------------------------------------
1031
1032 """ This part is very IMPORTANT! Implement your application functions
1033 to use openscap library this way:
1034 policy_titles = openscap.xccdf.policy.titles (this will reflect xccdf_policy_get_titles() func)
1035 Below are particular objects for parts of openscap library module system.
1036 The only change is in using oscap module wich is conflicting with oscap namespace.
1037 This module is renamed to common. All functions using OSCAP functions should look like:
1038 openscap.common.debug.seterr(err) (this will reflect oscap_debug_seterr() func)
1039 """
1040
1041 ds = DS_Class()
1042 xccdf = XCCDF_Class()
1043 oval = OVAL_Class()
1044 cve = CVE_Class()
1045 cpe = CPE_Class()
1046 sce = SCE_Class()
1047 common = OSCAP_Object("oscap")