Conditions | 29 |
Total Lines | 249 |
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 |
|
261 | 2 | def expand_xccdf_subs(fix, remediation_type, remediation_functions): |
|
262 | """For those remediation scripts utilizing some of the internal SCAP |
||
263 | Security Guide remediation functions expand the selected shell variables |
||
264 | and remediation functions calls with <xccdf:sub> element |
||
265 | |||
266 | This routine translates any instance of the 'populate' function call in |
||
267 | the form of: |
||
268 | |||
269 | populate variable_name |
||
270 | |||
271 | into |
||
272 | |||
273 | variable_name="<sub idref="variable_name"/>" |
||
274 | |||
275 | Also transforms any instance of the 'ansible-populate' function call in the |
||
276 | form of: |
||
277 | (ansible-populate variable_name) |
||
278 | into |
||
279 | |||
280 | <sub idref="variable_name"/> |
||
281 | |||
282 | Also transforms any instance of some other known remediation function (e.g. |
||
283 | 'replace_or_append' etc.) from the form of: |
||
284 | |||
285 | function_name "arg1" "arg2" ... "argN" |
||
286 | |||
287 | into: |
||
288 | |||
289 | <sub idref="function_function_name"/> |
||
290 | function_name "arg1" "arg2" ... "argN" |
||
291 | """ |
||
292 | |||
293 | if remediation_type == "ansible": |
||
294 | fix_text = fix.text |
||
295 | |||
296 | if "(ansible-populate " in fix_text: |
||
297 | raise RuntimeError( |
||
298 | "(ansible-populate VAR) has been deprecated. Please use " |
||
299 | "(xccdf-var VAR) instead. Keep in mind that the latter will " |
||
300 | "make an ansible variable out of XCCDF Value as opposed to " |
||
301 | "substituting directly." |
||
302 | ) |
||
303 | |||
304 | # we use the horrid "!!str |-" syntax to force strings without using |
||
305 | # quotes. quotes enable yaml escaping rules so we'd have to escape all |
||
306 | # the backslashes and at this point we don't know if there are any. |
||
307 | fix_text = re.sub( |
||
308 | r"- \(xccdf-var\s+(\S+)\)", |
||
309 | r"- name: XCCDF Value \1 # promote to variable\n" |
||
310 | r" set_fact:\n" |
||
311 | r" \1: !!str |-\n" |
||
312 | r" (ansible-populate \1)\n" |
||
313 | r" tags:\n" |
||
314 | r" - always", |
||
315 | fix_text |
||
316 | ) |
||
317 | |||
318 | pattern = r'\(ansible-populate\s*(\S+)\)' |
||
319 | |||
320 | # we will get list what looks like |
||
321 | # [text, varname, text, varname, ..., text] |
||
322 | parts = re.split(pattern, fix_text) |
||
323 | |||
324 | fix.text = parts[0] # add first "text" |
||
325 | for index in range(1, len(parts), 2): |
||
326 | varname = parts[index] |
||
327 | text_between_vars = parts[index + 1] |
||
328 | |||
329 | # we cannot combine elements and text easily |
||
330 | # so text is in ".tail" of element |
||
331 | xccdfvarsub = ElementTree.SubElement(fix, "sub", idref=varname) |
||
332 | xccdfvarsub.tail = text_between_vars |
||
333 | return |
||
334 | |||
335 | elif remediation_type == "puppet": |
||
336 | pattern = r'\(puppet-populate\s*(\S+)\)' |
||
337 | |||
338 | # we will get list what looks like |
||
339 | # [text, varname, text, varname, ..., text] |
||
340 | parts = re.split(pattern, fix.text) |
||
341 | |||
342 | fix.text = parts[0] # add first "text" |
||
343 | for index in range(1, len(parts), 2): |
||
344 | varname = parts[index] |
||
345 | text_between_vars = parts[index + 1] |
||
346 | |||
347 | # we cannot combine elements and text easily |
||
348 | # so text is in ".tail" of element |
||
349 | xccdfvarsub = ElementTree.SubElement(fix, "sub", idref=varname) |
||
350 | xccdfvarsub.tail = text_between_vars |
||
351 | return |
||
352 | |||
353 | elif remediation_type == "anaconda": |
||
354 | pattern = r'\(anaconda-populate\s*(\S+)\)' |
||
355 | |||
356 | # we will get list what looks like |
||
357 | # [text, varname, text, varname, ..., text] |
||
358 | parts = re.split(pattern, fix.text) |
||
359 | |||
360 | fix.text = parts[0] # add first "text" |
||
361 | for index in range(1, len(parts), 2): |
||
362 | varname = parts[index] |
||
363 | text_between_vars = parts[index + 1] |
||
364 | |||
365 | # we cannot combine elements and text easily |
||
366 | # so text is in ".tail" of element |
||
367 | xccdfvarsub = ElementTree.SubElement(fix, "sub", idref=varname) |
||
368 | xccdfvarsub.tail = text_between_vars |
||
369 | return |
||
370 | |||
371 | elif remediation_type == "bash": |
||
372 | # This remediation script doesn't utilize internal remediation functions |
||
373 | # Skip it without any further processing |
||
374 | if 'remediation_functions' not in fix.text: |
||
375 | return |
||
376 | |||
377 | # This remediation script utilizes some of internal remediation functions |
||
378 | # Expand shell variables and remediation functions calls with <xccdf:sub> |
||
379 | # elements |
||
380 | pattern = r'\n+(\s*(?:' + r'|'.join(remediation_functions) + r')[^\n]*)\n' |
||
381 | patcomp = re.compile(pattern, re.DOTALL) |
||
382 | fixparts = re.split(patcomp, fix.text) |
||
383 | if fixparts[0] is not None: |
||
384 | # Split the portion of fix.text from fix start to first call of |
||
385 | # remediation function, keeping only the third part: |
||
386 | # * tail to hold part of the fix.text after inclusion, |
||
387 | # but before first call of remediation function |
||
388 | try: |
||
389 | rfpattern = '(.*remediation_functions)(.*)' |
||
390 | rfpatcomp = re.compile(rfpattern, re.DOTALL) |
||
391 | _, _, tail, _ = re.split(rfpatcomp, fixparts[0], maxsplit=2) |
||
392 | except ValueError: |
||
393 | sys.stderr.write("Processing fix.text for: %s rule\n" |
||
394 | % fix.get('rule')) |
||
395 | sys.stderr.write("Unable to extract part of the fix.text " |
||
396 | "after inclusion of remediation functions." |
||
397 | " Aborting..\n") |
||
398 | sys.exit(1) |
||
399 | # If the 'tail' is not empty, make it new fix.text. |
||
400 | # Otherwise use '' |
||
401 | fix.text = tail if tail is not None else '' |
||
402 | # Drop the first element of 'fixparts' since it has been processed |
||
403 | fixparts.pop(0) |
||
404 | # Perform sanity check on new 'fixparts' list content (to continue |
||
405 | # successfully 'fixparts' has to contain even count of elements) |
||
406 | if len(fixparts) % 2 != 0: |
||
407 | sys.stderr.write("Error performing XCCDF expansion on " |
||
408 | "remediation script: %s\n" |
||
409 | % fix.get("rule")) |
||
410 | sys.stderr.write("Invalid count of elements. Exiting!\n") |
||
411 | sys.exit(1) |
||
412 | # Process remaining 'fixparts' elements in pairs |
||
413 | # First pair element is remediation function to be XCCDF expanded |
||
414 | # Second pair element (if not empty) is the portion of the original |
||
415 | # fix text to be used in newly added sublement's tail |
||
416 | for idx in range(0, len(fixparts), 2): |
||
417 | # We previously removed enclosing newlines when creating |
||
418 | # fixparts list. Add them back and reuse the above 'pattern' |
||
419 | fixparts[idx] = "\n%s\n" % fixparts[idx] |
||
420 | # Sanity check (verify the first field truly contains call of |
||
421 | # some of the remediation functions) |
||
422 | if re.match(pattern, fixparts[idx], re.DOTALL) is not None: |
||
423 | # This chunk contains call of 'populate' function |
||
424 | if "populate" in fixparts[idx]: |
||
425 | varname, fixtextcontrib = get_populate_replacement(remediation_type, |
||
426 | fixparts[idx]) |
||
427 | # Define new XCCDF <sub> element for the variable |
||
428 | xccdfvarsub = ElementTree.Element("sub", idref=varname) |
||
429 | |||
430 | # If this is first sub element, |
||
431 | # the textcontribution needs to go to fix text |
||
432 | # otherwise, append to last subelement |
||
433 | nfixchildren = len(list(fix)) |
||
434 | if nfixchildren == 0: |
||
435 | fix.text += fixtextcontrib |
||
436 | else: |
||
437 | previouselem = fix[nfixchildren-1] |
||
438 | previouselem.tail += fixtextcontrib |
||
439 | |||
440 | # If second pair element is not empty, append it as |
||
441 | # tail for the subelement (prefixed with closing '"') |
||
442 | if fixparts[idx + 1] is not None: |
||
443 | xccdfvarsub.tail = '"' + '\n' + fixparts[idx + 1] |
||
444 | # Otherwise append just enclosing '"' |
||
445 | else: |
||
446 | xccdfvarsub.tail = '"' + '\n' |
||
447 | # Append the new subelement to the fix element |
||
448 | fix.append(xccdfvarsub) |
||
449 | # This chunk contains call of other remediation function |
||
450 | else: |
||
451 | # Extract remediation function name |
||
452 | funcname = re.search(r'\n\s*(\S+)(| .*)\n', |
||
453 | fixparts[idx], |
||
454 | re.DOTALL).group(1) |
||
455 | # Define new XCCDF <sub> element for the function |
||
456 | xccdffuncsub = ElementTree.Element( |
||
457 | "sub", idref='function_%s' % funcname) |
||
458 | # Append original function call into tail of the |
||
459 | # subelement |
||
460 | xccdffuncsub.tail = fixparts[idx] |
||
461 | # If the second element of the pair is not empty, |
||
462 | # append it to the tail of the subelement too |
||
463 | if fixparts[idx + 1] is not None: |
||
464 | xccdffuncsub.tail += fixparts[idx + 1] |
||
465 | # Append the new subelement to the fix element |
||
466 | fix.append(xccdffuncsub) |
||
467 | # Ensure the newly added <xccdf:sub> element for the |
||
468 | # function will be always inserted at newline |
||
469 | # If xccdffuncsub is the first <xccdf:sub> element |
||
470 | # being added as child of <fix> and fix.text doesn't |
||
471 | # end up with newline character, append the newline |
||
472 | # to the fix.text |
||
473 | if list(fix).index(xccdffuncsub) == 0: |
||
474 | if re.search(r'.*\n$', fix.text) is None: |
||
475 | fix.text += '\n' |
||
476 | # If xccdffuncsub isn't the first child (first |
||
477 | # <xccdf:sub> being added), and tail of previous |
||
478 | # child doesn't end up with newline, append the newline |
||
479 | # to the tail of previous child |
||
480 | else: |
||
481 | previouselem = fix[list(fix).index(xccdffuncsub) - 1] |
||
482 | if re.search(r'.*\n$', previouselem.tail) is None: |
||
483 | previouselem.tail += '\n' |
||
484 | |||
485 | # Perform a sanity check if all known remediation function calls have been |
||
486 | # properly XCCDF substituted. Exit with failure if some wasn't |
||
487 | |||
488 | # First concat output form of modified fix text (including text appended |
||
489 | # to all children of the fix) |
||
490 | modfix = [fix.text] |
||
491 | for child in fix.getchildren(): |
||
492 | if child is not None and child.text is not None: |
||
493 | modfix.append(child.text) |
||
494 | modfixtext = "".join(modfix) |
||
495 | for func in remediation_functions: |
||
496 | # Then efine expected XCCDF sub element form for this function |
||
497 | funcxccdfsub = "<sub idref=\"function_%s\"" % func |
||
498 | # Finally perform the sanity check -- if function was properly XCCDF |
||
499 | # substituted both the original function call and XCCDF <sub> element |
||
500 | # for that function need to be present in the modified text of the fix |
||
501 | # Otherwise something went wrong, thus exit with failure |
||
502 | if func in modfixtext and funcxccdfsub not in modfixtext: |
||
503 | sys.stderr.write("Error performing XCCDF <sub> substitution " |
||
504 | "for function %s in %s fix. Exiting...\n" |
||
505 | % (func, fix.get("rule"))) |
||
506 | sys.exit(1) |
||
507 | else: |
||
508 | sys.stderr.write("Unknown remediation type '%s'\n" % (remediation_type)) |
||
509 | sys.exit(1) |
||
510 |
The coding style of this project requires that you add a docstring to this code element. Below, you find an example for methods:
If you would like to know more about docstrings, we recommend to read PEP-257: Docstring Conventions.