Conditions | 29 |
Total Lines | 254 |
Code Lines | 106 |
Lines | 0 |
Ratio | 0 % |
Tests | 1 |
CRAP Score | 843.7856 |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like ssg.build_remediations.expand_xccdf_subs() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | 2 | from __future__ import absolute_import |
|
262 | 2 | def expand_xccdf_subs(fix, remediation_type, remediation_functions): |
|
263 | """For those remediation scripts utilizing some of the internal SCAP |
||
264 | Security Guide remediation functions expand the selected shell variables |
||
265 | and remediation functions calls with <xccdf:sub> element |
||
266 | |||
267 | This routine translates any instance of the 'populate' function call in |
||
268 | the form of: |
||
269 | |||
270 | populate variable_name |
||
271 | |||
272 | into |
||
273 | |||
274 | variable_name="<sub idref="variable_name"/>" |
||
275 | |||
276 | Also transforms any instance of the 'ansible-populate' function call in the |
||
277 | form of: |
||
278 | (ansible-populate variable_name) |
||
279 | into |
||
280 | |||
281 | <sub idref="variable_name"/> |
||
282 | |||
283 | Also transforms any instance of some other known remediation function (e.g. |
||
284 | 'replace_or_append' etc.) from the form of: |
||
285 | |||
286 | function_name "arg1" "arg2" ... "argN" |
||
287 | |||
288 | into: |
||
289 | |||
290 | <sub idref="function_function_name"/> |
||
291 | function_name "arg1" "arg2" ... "argN" |
||
292 | """ |
||
293 | |||
294 | if remediation_type == "ansible": |
||
295 | fix_text = fix.text |
||
296 | |||
297 | if "(ansible-populate " in fix_text: |
||
298 | raise RuntimeError( |
||
299 | "(ansible-populate VAR) has been deprecated. Please use " |
||
300 | "(xccdf-var VAR) instead. Keep in mind that the latter will " |
||
301 | "make an ansible variable out of XCCDF Value as opposed to " |
||
302 | "substituting directly." |
||
303 | ) |
||
304 | |||
305 | # If you change this string make sure it still matches the pattern |
||
306 | # defined in OpenSCAP. Otherwise you break variable handling in |
||
307 | # 'oscap xccdf generate fix' and the variables won't be customizable! |
||
308 | # https://github.com/OpenSCAP/openscap/blob/1.2.17/src/XCCDF_POLICY/xccdf_policy_remediate.c#L588 |
||
309 | # const char *pattern = |
||
310 | # "- name: XCCDF Value [^ ]+ # promote to variable\n set_fact:\n" |
||
311 | # " ([^:]+): (.+)\n tags:\n - always\n"; |
||
312 | # We use !!str typecast to prevent treating values as different types |
||
313 | # eg. yes as a bool or 077 as an octal number |
||
314 | fix_text = re.sub( |
||
315 | r"- \(xccdf-var\s+(\S+)\)", |
||
316 | r"- name: XCCDF Value \1 # promote to variable\n" |
||
317 | r" set_fact:\n" |
||
318 | r" \1: !!str (ansible-populate \1)\n" |
||
319 | r" tags:\n" |
||
320 | r" - always", |
||
321 | fix_text |
||
322 | ) |
||
323 | |||
324 | pattern = r'\(ansible-populate\s*(\S+)\)' |
||
325 | |||
326 | # we will get list what looks like |
||
327 | # [text, varname, text, varname, ..., text] |
||
328 | parts = re.split(pattern, fix_text) |
||
329 | |||
330 | fix.text = parts[0] # add first "text" |
||
331 | for index in range(1, len(parts), 2): |
||
332 | varname = parts[index] |
||
333 | text_between_vars = parts[index + 1] |
||
334 | |||
335 | # we cannot combine elements and text easily |
||
336 | # so text is in ".tail" of element |
||
337 | xccdfvarsub = ElementTree.SubElement(fix, "sub", idref=varname) |
||
338 | xccdfvarsub.tail = text_between_vars |
||
339 | return |
||
340 | |||
341 | elif remediation_type == "puppet": |
||
342 | pattern = r'\(puppet-populate\s*(\S+)\)' |
||
343 | |||
344 | # we will get list what looks like |
||
345 | # [text, varname, text, varname, ..., text] |
||
346 | parts = re.split(pattern, fix.text) |
||
347 | |||
348 | fix.text = parts[0] # add first "text" |
||
349 | for index in range(1, len(parts), 2): |
||
350 | varname = parts[index] |
||
351 | text_between_vars = parts[index + 1] |
||
352 | |||
353 | # we cannot combine elements and text easily |
||
354 | # so text is in ".tail" of element |
||
355 | xccdfvarsub = ElementTree.SubElement(fix, "sub", idref=varname) |
||
356 | xccdfvarsub.tail = text_between_vars |
||
357 | return |
||
358 | |||
359 | elif remediation_type == "anaconda": |
||
360 | pattern = r'\(anaconda-populate\s*(\S+)\)' |
||
361 | |||
362 | # we will get list what looks like |
||
363 | # [text, varname, text, varname, ..., text] |
||
364 | parts = re.split(pattern, fix.text) |
||
365 | |||
366 | fix.text = parts[0] # add first "text" |
||
367 | for index in range(1, len(parts), 2): |
||
368 | varname = parts[index] |
||
369 | text_between_vars = parts[index + 1] |
||
370 | |||
371 | # we cannot combine elements and text easily |
||
372 | # so text is in ".tail" of element |
||
373 | xccdfvarsub = ElementTree.SubElement(fix, "sub", idref=varname) |
||
374 | xccdfvarsub.tail = text_between_vars |
||
375 | return |
||
376 | |||
377 | elif remediation_type == "bash": |
||
378 | # This remediation script doesn't utilize internal remediation functions |
||
379 | # Skip it without any further processing |
||
380 | if 'remediation_functions' not in fix.text: |
||
381 | return |
||
382 | |||
383 | # This remediation script utilizes some of internal remediation functions |
||
384 | # Expand shell variables and remediation functions calls with <xccdf:sub> |
||
385 | # elements |
||
386 | pattern = r'\n+(\s*(?:' + r'|'.join(remediation_functions) + r')[^\n]*)\n' |
||
387 | patcomp = re.compile(pattern, re.DOTALL) |
||
388 | fixparts = re.split(patcomp, fix.text) |
||
389 | if fixparts[0] is not None: |
||
390 | # Split the portion of fix.text from fix start to first call of |
||
391 | # remediation function, keeping only the third part: |
||
392 | # * tail to hold part of the fix.text after inclusion, |
||
393 | # but before first call of remediation function |
||
394 | try: |
||
395 | rfpattern = '(.*remediation_functions)(.*)' |
||
396 | rfpatcomp = re.compile(rfpattern, re.DOTALL) |
||
397 | _, _, tail, _ = re.split(rfpatcomp, fixparts[0], maxsplit=2) |
||
398 | except ValueError: |
||
399 | sys.stderr.write("Processing fix.text for: %s rule\n" |
||
400 | % fix.get('rule')) |
||
401 | sys.stderr.write("Unable to extract part of the fix.text " |
||
402 | "after inclusion of remediation functions." |
||
403 | " Aborting..\n") |
||
404 | sys.exit(1) |
||
405 | # If the 'tail' is not empty, make it new fix.text. |
||
406 | # Otherwise use '' |
||
407 | fix.text = tail if tail is not None else '' |
||
|
|||
408 | # Drop the first element of 'fixparts' since it has been processed |
||
409 | fixparts.pop(0) |
||
410 | # Perform sanity check on new 'fixparts' list content (to continue |
||
411 | # successfully 'fixparts' has to contain even count of elements) |
||
412 | if len(fixparts) % 2 != 0: |
||
413 | sys.stderr.write("Error performing XCCDF expansion on " |
||
414 | "remediation script: %s\n" |
||
415 | % fix.get("rule")) |
||
416 | sys.stderr.write("Invalid count of elements. Exiting!\n") |
||
417 | sys.exit(1) |
||
418 | # Process remaining 'fixparts' elements in pairs |
||
419 | # First pair element is remediation function to be XCCDF expanded |
||
420 | # Second pair element (if not empty) is the portion of the original |
||
421 | # fix text to be used in newly added sublement's tail |
||
422 | for idx in range(0, len(fixparts), 2): |
||
423 | # We previously removed enclosing newlines when creating |
||
424 | # fixparts list. Add them back and reuse the above 'pattern' |
||
425 | fixparts[idx] = "\n%s\n" % fixparts[idx] |
||
426 | # Sanity check (verify the first field truly contains call of |
||
427 | # some of the remediation functions) |
||
428 | if re.match(pattern, fixparts[idx], re.DOTALL) is not None: |
||
429 | # This chunk contains call of 'populate' function |
||
430 | if "populate" in fixparts[idx]: |
||
431 | varname, fixtextcontrib = get_populate_replacement(remediation_type, |
||
432 | fixparts[idx]) |
||
433 | # Define new XCCDF <sub> element for the variable |
||
434 | xccdfvarsub = ElementTree.Element("sub", idref=varname) |
||
435 | |||
436 | # If this is first sub element, |
||
437 | # the textcontribution needs to go to fix text |
||
438 | # otherwise, append to last subelement |
||
439 | nfixchildren = len(list(fix)) |
||
440 | if nfixchildren == 0: |
||
441 | fix.text += fixtextcontrib |
||
442 | else: |
||
443 | previouselem = fix[nfixchildren-1] |
||
444 | previouselem.tail += fixtextcontrib |
||
445 | |||
446 | # If second pair element is not empty, append it as |
||
447 | # tail for the subelement (prefixed with closing '"') |
||
448 | if fixparts[idx + 1] is not None: |
||
449 | xccdfvarsub.tail = '"' + '\n' + fixparts[idx + 1] |
||
450 | # Otherwise append just enclosing '"' |
||
451 | else: |
||
452 | xccdfvarsub.tail = '"' + '\n' |
||
453 | # Append the new subelement to the fix element |
||
454 | fix.append(xccdfvarsub) |
||
455 | # This chunk contains call of other remediation function |
||
456 | else: |
||
457 | # Extract remediation function name |
||
458 | funcname = re.search(r'\n\s*(\S+)(| .*)\n', |
||
459 | fixparts[idx], |
||
460 | re.DOTALL).group(1) |
||
461 | # Define new XCCDF <sub> element for the function |
||
462 | xccdffuncsub = ElementTree.Element( |
||
463 | "sub", idref='function_%s' % funcname) |
||
464 | # Append original function call into tail of the |
||
465 | # subelement |
||
466 | xccdffuncsub.tail = fixparts[idx] |
||
467 | # If the second element of the pair is not empty, |
||
468 | # append it to the tail of the subelement too |
||
469 | if fixparts[idx + 1] is not None: |
||
470 | xccdffuncsub.tail += fixparts[idx + 1] |
||
471 | # Append the new subelement to the fix element |
||
472 | fix.append(xccdffuncsub) |
||
473 | # Ensure the newly added <xccdf:sub> element for the |
||
474 | # function will be always inserted at newline |
||
475 | # If xccdffuncsub is the first <xccdf:sub> element |
||
476 | # being added as child of <fix> and fix.text doesn't |
||
477 | # end up with newline character, append the newline |
||
478 | # to the fix.text |
||
479 | if list(fix).index(xccdffuncsub) == 0: |
||
480 | if re.search(r'.*\n$', fix.text) is None: |
||
481 | fix.text += '\n' |
||
482 | # If xccdffuncsub isn't the first child (first |
||
483 | # <xccdf:sub> being added), and tail of previous |
||
484 | # child doesn't end up with newline, append the newline |
||
485 | # to the tail of previous child |
||
486 | else: |
||
487 | previouselem = fix[list(fix).index(xccdffuncsub) - 1] |
||
488 | if re.search(r'.*\n$', previouselem.tail) is None: |
||
489 | previouselem.tail += '\n' |
||
490 | |||
491 | # Perform a sanity check if all known remediation function calls have been |
||
492 | # properly XCCDF substituted. Exit with failure if some wasn't |
||
493 | |||
494 | # First concat output form of modified fix text (including text appended |
||
495 | # to all children of the fix) |
||
496 | modfix = [fix.text] |
||
497 | for child in fix.getchildren(): |
||
498 | if child is not None and child.text is not None: |
||
499 | modfix.append(child.text) |
||
500 | modfixtext = "".join(modfix) |
||
501 | for func in remediation_functions: |
||
502 | # Then efine expected XCCDF sub element form for this function |
||
503 | funcxccdfsub = "<sub idref=\"function_%s\"" % func |
||
504 | # Finally perform the sanity check -- if function was properly XCCDF |
||
505 | # substituted both the original function call and XCCDF <sub> element |
||
506 | # for that function need to be present in the modified text of the fix |
||
507 | # Otherwise something went wrong, thus exit with failure |
||
508 | if func in modfixtext and funcxccdfsub not in modfixtext: |
||
509 | sys.stderr.write("Error performing XCCDF <sub> substitution " |
||
510 | "for function %s in %s fix. Exiting...\n" |
||
511 | % (func, fix.get("rule"))) |
||
512 | sys.exit(1) |
||
513 | else: |
||
514 | sys.stderr.write("Unknown remediation type '%s'\n" % (remediation_type)) |
||
515 | sys.exit(1) |
||
516 |