Skip to content

trestle.tasks.cis_xlsx_to_oscal_cd

trestle.tasks.cis_xlsx_to_oscal_cd ¤

OSCAL transformation tasks.

Attributes¤

default_benchmark_control_prefix = 'cisc-' module-attribute ¤

default_benchmark_rule_prefix = 'CIS-' module-attribute ¤

head_recommendation_no = 'Recommendation #' module-attribute ¤

head_section_no = 'Section #' module-attribute ¤

logger = logging.getLogger(__name__) module-attribute ¤

output_file = 'component-definition.json' module-attribute ¤

timestamp = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat() module-attribute ¤

Classes¤

CisControlsHelper ¤

Cis controls helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
class CisControlsHelper:
    """Cis controls helper."""

    def __init__(self, cis_controls: str) -> None:
        """Initialize."""
        self.cis_controls = cis_controls

    def ctl_generator(self) -> Iterator[Dict]:
        """Generate ctls until finished."""
        parts = self.cis_controls.split(';TITLE:')
        # restore TITLE:
        for n in range(len(parts)):
            parts[n] = f'TITLE:{parts[n]}'
        # process triples TITLE, CONTROL, DESCRIPTION
        for part in parts:
            if part:
                s1 = part.split('DESCRIPTION:')
                description = s1[1].strip()
                s2 = s1[0].split('CONTROL:')
                control = s2[1].strip()
                control_version = control.split()[0]
                control_id = control.split()[1]
                s3 = s2[0].split('TITLE:')
                title = s3[1].strip()
                ctl = {
                    'description': description,
                    'control-version': control_version,
                    'control-id': control_id,
                    'title': title
                }
                yield ctl

    def get_ctl_list(self, ctl_pfx: str, profile_version: List[str]) -> List[str]:
        """Get control list."""
        ctl_list = []
        if self.cis_controls:
            for ctl in self.ctl_generator():
                if ctl['control-version'] not in profile_version:
                    continue
                ctl_id = ctl['control-id']
                try:
                    float(ctl_id)
                except Exception:
                    text = f'missing or invalid control-id: "{ctl_id}"'
                    raise RuntimeError(text)
                ctl_list.append(f'{ctl_pfx}{ctl_id}')
        return ctl_list
Attributes¤
cis_controls = cis_controls instance-attribute ¤
Functions¤
__init__(cis_controls) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
600
601
602
def __init__(self, cis_controls: str) -> None:
    """Initialize."""
    self.cis_controls = cis_controls
ctl_generator() ¤

Generate ctls until finished.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def ctl_generator(self) -> Iterator[Dict]:
    """Generate ctls until finished."""
    parts = self.cis_controls.split(';TITLE:')
    # restore TITLE:
    for n in range(len(parts)):
        parts[n] = f'TITLE:{parts[n]}'
    # process triples TITLE, CONTROL, DESCRIPTION
    for part in parts:
        if part:
            s1 = part.split('DESCRIPTION:')
            description = s1[1].strip()
            s2 = s1[0].split('CONTROL:')
            control = s2[1].strip()
            control_version = control.split()[0]
            control_id = control.split()[1]
            s3 = s2[0].split('TITLE:')
            title = s3[1].strip()
            ctl = {
                'description': description,
                'control-version': control_version,
                'control-id': control_id,
                'title': title
            }
            yield ctl
get_ctl_list(ctl_pfx, profile_version) ¤

Get control list.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
def get_ctl_list(self, ctl_pfx: str, profile_version: List[str]) -> List[str]:
    """Get control list."""
    ctl_list = []
    if self.cis_controls:
        for ctl in self.ctl_generator():
            if ctl['control-version'] not in profile_version:
                continue
            ctl_id = ctl['control-id']
            try:
                float(ctl_id)
            except Exception:
                text = f'missing or invalid control-id: "{ctl_id}"'
                raise RuntimeError(text)
            ctl_list.append(f'{ctl_pfx}{ctl_id}')
    return ctl_list

CisXlsxToOscalCd ¤

Bases: TaskBase

Task to transform CIS .xlsx to OSCAL component definition.

Attributes:

Name Type Description
name

Name of the task.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class CisXlsxToOscalCd(TaskBase):
    """
    Task to transform CIS .xlsx to OSCAL component definition.

    Attributes:
        name: Name of the task.
    """

    name = 'cis-xlsx-to-oscal-cd'

    def __init__(self, config_object: Optional[configparser.SectionProxy]) -> None:
        """
        Initialize trestle task.

        Args:
            config_object: Config section associated with the task.
        """
        self.config_object = config_object
        super().__init__(config_object)
        self._default_benchmark_sheet_name = 'Combined Profiles'
        self._default_component_type = 'software'
        self._default_output_overwrite = 'True'
        #
        self._example_benchmark_file = 'data/CIS_IBM_Db2_11_Benchmark_v1.1.0.xlsx'
        self._example_benchmark_title = 'CIS IBM Db2 11 Benchmark'
        self._example_benchmark_version = '1.1.0'
        self._example_oscal_cd_dir = 'data/component-definitions/CIS_IBM_Db2_11_Benchmark_v1.1.0'
        self._example_namespace = 'https://oscal-compass/compliance-trestle/schemas/oscal/cd'
        self._example_profile_version = 'v8'
        self._example_profile_source = 'catalogs/CIS_controls_v8/catalog.json'
        self._example_profile_description = 'CIS catalog v8'
        self._example_component_name = 'Db2 11'

    def print_info(self) -> None:
        """Print the help string."""
        logger.info(f'Help information for {self.name} task.')
        logger.info('')
        logger.info('Purpose: Create component definition from standard CIS benchmark')
        logger.info('')
        logger.info('Configuration flags sit under [task.cis-xlsx-to-oscal-cd]:')
        text1 = '  benchmark-file             = '
        text2 = f'(required) path of file to read the CIS benchmark .xlsx, e.g., "{self._example_benchmark_file}".'
        logger.info(text1 + text2)
        text1 = '  benchmark-title            = '
        text2 = f'(required) title of the CIS benchmark, e.g., "{self._example_benchmark_title}".'
        logger.info(text1 + text2)
        text1 = '  benchmark-version          = '
        text2 = f'(required) version of the CIS benchmark .xlsx, e.g., "{self._example_benchmark_version}".'
        logger.info(text1 + text2)
        text1 = '  benchmark-control-prefix   = '
        text2 = f'(optional) benchmark control prefix, default = "{default_benchmark_control_prefix}".'
        logger.info(text1 + text2)
        text1 = '  benchmark-rule-prefix      = '
        text2 = f'(optional) benchmark rule prefix, default = "{default_benchmark_rule_prefix}".'
        logger.info(text1 + text2)
        text1 = '  benchmark-sheet-name       = '
        text2 = f'(optional) benchmark sheet name, default = "{self._default_benchmark_sheet_name}".'
        logger.info(text1 + text2)
        text1 = '  component-name             = '
        text2 = f'(required) component name, e.g., "{self._example_component_name}".'
        logger.info(text1 + text2)
        text1 = '  component-description      = '
        text2 = f'(required) component description, e.g., "{self._example_component_name}".'
        logger.info(text1 + text2)
        text1 = '  component-type             = '
        text2 = f'(required) component type, e.g., "{self._default_component_type}".'
        logger.info(text1 + text2)
        text1 = '  namespace                  = '
        text2 = f'(required) namespace, e.g., "{self._example_namespace}".'
        logger.info(text1 + text2)
        text1 = '  output-dir                 = '
        text2 = f'(required) path of folder to write the OSCAL {output_file}, e.g., "{self._example_oscal_cd_dir}".'
        logger.info(text1 + text2)
        text1 = '  output-overwrite           = '
        text2 = f'(optional) output overwrite, default = "{self._default_output_overwrite}".'
        logger.info(text1 + text2)
        text1 = '  profile-version            = '
        text2 = f'(required) profile version, e.g., "{self._example_profile_version}".'
        logger.info(text1 + text2)
        text1 = '  profile-source             = '
        text2 = f'(required) profile source, e.g., "{self._example_profile_source}".'
        logger.info(text1 + text2)
        text1 = '  profile-description        = '
        text2 = f'(required) profile description, e.g., "{self._example_profile_description}".'
        logger.info(text1 + text2)

    def simulate(self) -> TaskOutcome:
        """Provide a simulated outcome."""
        return TaskOutcome('simulated-success')

    def execute(self) -> TaskOutcome:
        """Provide an actual outcome."""
        try:
            return self._execute()
        except Exception:
            logger.info(traceback.format_exc())
            return TaskOutcome('failure')

    def _execute(self) -> TaskOutcome:
        """Wrap the execute for exception handling."""
        if not self.config_object:
            logger.warning('config missing')
            return TaskOutcome('failure')
        # required
        try:
            self._benchmark_file = self.config_object['benchmark-file']
            self._oscal_cd_dir = self.config_object['output-dir']
            self._namespace = self.config_object['namespace']
            self._profile_version = self.config_object['profile-version']
        except KeyError as e:
            logger.info(f'key {e.args[0]} missing')
            return TaskOutcome('failure')
        # output
        self._oscal_cd_path = pathlib.Path(self._oscal_cd_dir)
        # insure output dir exists
        self._oscal_cd_path.mkdir(exist_ok=True, parents=True)
        # calculate output file name & check writability
        oname = 'component-definition.json'
        ofile = self._oscal_cd_path / oname
        overwrite = self.config_object.get('output-overwrite', self._default_output_overwrite)
        overwrite = as_bool(overwrite)
        if not overwrite and pathlib.Path(ofile).exists():
            logger.warning(f'output: {ofile} already exists')
            return TaskOutcome('failure')
        with self._get_tempdir() as tmpdir:
            # step 1 - add combined sheet, if needed
            combine_helper = CombineHelper(self.config_object, tmpdir)
            combine_helper.run()
            # step 2 - create trestle ready csv file from xlsx file
            xlsx_to_csv_helper = XlsxToCsvHelper(self.config_object, tmpdir)
            xlsx_to_csv_helper.run()
            # step 3 - create OSCAL json file from csv file
            csv_to_json_helper = CsvToJsonHelper(self.config_object, tmpdir)
            task_outcome = csv_to_json_helper.run()
            return task_outcome

    def _get_tempdir(self) -> tempfile.TemporaryDirectory():
        """Get tmpdir."""
        return tempfile.TemporaryDirectory()
Attributes¤
config_object = config_object instance-attribute ¤
name = 'cis-xlsx-to-oscal-cd' class-attribute instance-attribute ¤
Functions¤
__init__(config_object) ¤

Initialize trestle task.

Parameters:

Name Type Description Default
config_object Optional[SectionProxy]

Config section associated with the task.

required
Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def __init__(self, config_object: Optional[configparser.SectionProxy]) -> None:
    """
    Initialize trestle task.

    Args:
        config_object: Config section associated with the task.
    """
    self.config_object = config_object
    super().__init__(config_object)
    self._default_benchmark_sheet_name = 'Combined Profiles'
    self._default_component_type = 'software'
    self._default_output_overwrite = 'True'
    #
    self._example_benchmark_file = 'data/CIS_IBM_Db2_11_Benchmark_v1.1.0.xlsx'
    self._example_benchmark_title = 'CIS IBM Db2 11 Benchmark'
    self._example_benchmark_version = '1.1.0'
    self._example_oscal_cd_dir = 'data/component-definitions/CIS_IBM_Db2_11_Benchmark_v1.1.0'
    self._example_namespace = 'https://oscal-compass/compliance-trestle/schemas/oscal/cd'
    self._example_profile_version = 'v8'
    self._example_profile_source = 'catalogs/CIS_controls_v8/catalog.json'
    self._example_profile_description = 'CIS catalog v8'
    self._example_component_name = 'Db2 11'
execute() ¤

Provide an actual outcome.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
136
137
138
139
140
141
142
def execute(self) -> TaskOutcome:
    """Provide an actual outcome."""
    try:
        return self._execute()
    except Exception:
        logger.info(traceback.format_exc())
        return TaskOutcome('failure')
print_info() ¤

Print the help string.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def print_info(self) -> None:
    """Print the help string."""
    logger.info(f'Help information for {self.name} task.')
    logger.info('')
    logger.info('Purpose: Create component definition from standard CIS benchmark')
    logger.info('')
    logger.info('Configuration flags sit under [task.cis-xlsx-to-oscal-cd]:')
    text1 = '  benchmark-file             = '
    text2 = f'(required) path of file to read the CIS benchmark .xlsx, e.g., "{self._example_benchmark_file}".'
    logger.info(text1 + text2)
    text1 = '  benchmark-title            = '
    text2 = f'(required) title of the CIS benchmark, e.g., "{self._example_benchmark_title}".'
    logger.info(text1 + text2)
    text1 = '  benchmark-version          = '
    text2 = f'(required) version of the CIS benchmark .xlsx, e.g., "{self._example_benchmark_version}".'
    logger.info(text1 + text2)
    text1 = '  benchmark-control-prefix   = '
    text2 = f'(optional) benchmark control prefix, default = "{default_benchmark_control_prefix}".'
    logger.info(text1 + text2)
    text1 = '  benchmark-rule-prefix      = '
    text2 = f'(optional) benchmark rule prefix, default = "{default_benchmark_rule_prefix}".'
    logger.info(text1 + text2)
    text1 = '  benchmark-sheet-name       = '
    text2 = f'(optional) benchmark sheet name, default = "{self._default_benchmark_sheet_name}".'
    logger.info(text1 + text2)
    text1 = '  component-name             = '
    text2 = f'(required) component name, e.g., "{self._example_component_name}".'
    logger.info(text1 + text2)
    text1 = '  component-description      = '
    text2 = f'(required) component description, e.g., "{self._example_component_name}".'
    logger.info(text1 + text2)
    text1 = '  component-type             = '
    text2 = f'(required) component type, e.g., "{self._default_component_type}".'
    logger.info(text1 + text2)
    text1 = '  namespace                  = '
    text2 = f'(required) namespace, e.g., "{self._example_namespace}".'
    logger.info(text1 + text2)
    text1 = '  output-dir                 = '
    text2 = f'(required) path of folder to write the OSCAL {output_file}, e.g., "{self._example_oscal_cd_dir}".'
    logger.info(text1 + text2)
    text1 = '  output-overwrite           = '
    text2 = f'(optional) output overwrite, default = "{self._default_output_overwrite}".'
    logger.info(text1 + text2)
    text1 = '  profile-version            = '
    text2 = f'(required) profile version, e.g., "{self._example_profile_version}".'
    logger.info(text1 + text2)
    text1 = '  profile-source             = '
    text2 = f'(required) profile source, e.g., "{self._example_profile_source}".'
    logger.info(text1 + text2)
    text1 = '  profile-description        = '
    text2 = f'(required) profile description, e.g., "{self._example_profile_description}".'
    logger.info(text1 + text2)
simulate() ¤

Provide a simulated outcome.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
132
133
134
def simulate(self) -> TaskOutcome:
    """Provide a simulated outcome."""
    return TaskOutcome('simulated-success')

ColHelper ¤

Col Helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
276
277
278
279
280
281
282
283
284
285
286
287
class ColHelper:
    """Col Helper."""

    @staticmethod
    def get_section() -> int:
        """Get section col no."""
        return 1

    @staticmethod
    def get_recommendation() -> int:
        """Get recommendation col no."""
        return 2
Functions¤
get_recommendation() staticmethod ¤

Get recommendation col no.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
284
285
286
287
@staticmethod
def get_recommendation() -> int:
    """Get recommendation col no."""
    return 2
get_section() staticmethod ¤

Get section col no.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
279
280
281
282
@staticmethod
def get_section() -> int:
    """Get section col no."""
    return 1

CombineHelper ¤

Combine helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
class CombineHelper:
    """Combine helper."""

    tgt_col_profile = 3

    def __init__(self, config: SectionProxy, tmpdir: str) -> None:
        """Initialize."""
        benchmark_file = config['benchmark-file']
        self.ipath = pathlib.Path(benchmark_file)
        self.opath = pathlib.Path(tmpdir) / self.ipath.name
        self.wb = load_workbook(self.ipath)
        self.ws_map = {}
        self.combined_map = {}

    def run(self) -> None:
        """Run."""
        self._add_sheet_combined_profiles()
        self._save()

    def _gather_sheets(self) -> None:
        """Gather sheets."""
        for sn in self.wb.sheetnames:
            for pn in self.sheetnames_prefixes:
                if sn.startswith(pn):
                    self.ws_map[sn] = SheetHelper(self.wb, sn)
                    logger.debug(f'input sheet {sn} to be combined.')
                    break

    def _validate_columns_count(self) -> None:
        """Validate columns count."""
        columns = -1
        for sn in self.ws_map.keys():
            sheet_helper = self.ws_map[sn]
            if columns < 0:
                columns = sheet_helper.get_max_col()
            if columns != sheet_helper.get_max_col():
                raise RuntimeError(f'{sn} unexpected columns count {sheet_helper.get_max_col()} for sheet {sn}')

    def _populate_combined_map(self) -> int:
        """Populate combined map."""
        src_col_section_no = ColHelper.get_section()
        src_col_recommendation_no = ColHelper.get_recommendation()
        rec_count_sheets = 0
        # populate combined map
        for sn in self.ws_map.keys():
            sheet_helper = SheetHelper(self.wb, sn)
            # process all rows from individual sheet
            rec_count_sheets += self._process_sheet(sheet_helper, src_col_section_no, src_col_recommendation_no)
        return rec_count_sheets

    def _process_sheet(self, sheet_helper: SheetHelper, src_col_section_no: int, src_col_recommendation_no: int) -> int:
        """Process sheet."""
        rec_count = 0
        for row in sheet_helper.row_generator():
            # section
            section_no = sheet_helper.get_cell_value(row, src_col_section_no)
            if section_no not in self.combined_map.keys():
                self.combined_map[section_no] = {}
            # recommendation
            recommendation_no = sheet_helper.get_cell_value(row, src_col_recommendation_no)
            if recommendation_no not in self.combined_map[section_no].keys():
                self.combined_map[section_no][recommendation_no] = {}
            # combine head or data
            if row == 1:
                self._combine_head(sheet_helper, row, section_no, recommendation_no, CombineHelper.tgt_col_profile)
            else:
                self._combine_data(sheet_helper, row, section_no, recommendation_no, CombineHelper.tgt_col_profile)
                if recommendation_no:
                    rec_count += 1
        return rec_count

    def _handle_head_row(
        self, combined_helper: SheetHelper, row: Int, kvset: Dict, section_no: str, recommendation_no: str
    ) -> None:
        """Handle head row."""
        for col in kvset.keys():
            value = self.combined_map[section_no][recommendation_no][col]
            if col == CombineHelper.tgt_col_profile:
                value = value[0]
            combined_helper.put_cell_value(row.get_value(), col, value)
        row.inc_value()

    def _handle_data_row_control(
        self,
        combined_helper: SheetHelper,
        row: Int,
        kvset: Dict,
        section_no: str,
        recommendation_no: str,
        rec_count_merged: Int
    ) -> None:
        """Handle data row control."""
        profiles = kvset[CombineHelper.tgt_col_profile]
        for profile in profiles:
            for col in kvset.keys():
                value = self.combined_map[section_no][recommendation_no][col]
                if col == CombineHelper.tgt_col_profile:
                    value = profile
                combined_helper.put_cell_value(row.get_value(), col, value)
            row.inc_value()
            rec_count_merged.inc_value()

    def _handle_data_row_non_control(
        self, combined_helper: SheetHelper, row: Int, kvset: Dict, section_no: str, recommendation_no: str
    ) -> None:
        """Handle data row non-control."""
        for col in kvset.keys():
            value = self.combined_map[section_no][recommendation_no][col]
            if col == CombineHelper.tgt_col_profile:
                value = None
            combined_helper.put_cell_value(row.get_value(), col, value)
        row.inc_value()

    def _handle_data_row(
        self,
        combined_helper: SheetHelper,
        row: Int,
        kvset: Dict,
        section_no: str,
        recommendation_no: str,
        rec_count_merged: Int
    ) -> None:
        """Handle data row."""
        if recommendation_no:
            self._handle_data_row_control(combined_helper, row, kvset, section_no, recommendation_no, rec_count_merged)
        else:
            self._handle_data_row_non_control(combined_helper, row, kvset, section_no, recommendation_no)

    def _populate_combined_sheet(self, combined_helper: SheetHelper) -> int:
        """Populate combined sheet."""
        rec_count_merged = Int(0)
        row = Int(1)
        keys1 = list(self.combined_map.keys())
        keys1.sort(key=cmp_to_key(SortHelper.compare))
        for section_no in keys1:
            section = self.combined_map[section_no]
            keys2 = list(section.keys())
            keys2.sort(key=cmp_to_key(SortHelper.compare))
            for recommendation_no in keys2:
                kvset = self.combined_map[section_no][recommendation_no]
                if row.get_value() == 1:
                    self._handle_head_row(combined_helper, row, kvset, section_no, recommendation_no)
                else:
                    self._handle_data_row(combined_helper, row, kvset, section_no, recommendation_no, rec_count_merged)
        return rec_count_merged.get_value()

    def _add_sheet_combined_profiles(self) -> None:
        """Add sheet combined profiles."""
        # output sheet
        self.sheetname_output = SheetHelper.get_sheetname()
        exists = self.sheetname_output in self.wb.sheetnames
        if exists:
            logger.debug(f'output sheet {self.sheetname_output} exists.')
            return
        # input sheets
        self.sheetnames_prefixes = SheetHelper.get_sheetname_prefixes()
        # sheets
        self._gather_sheets()
        # validate
        self._validate_columns_count()
        # key columns mappings
        rec_count_sheets = self._populate_combined_map()
        # add combined sheet
        sn = self.sheetname_output
        self.wb.create_sheet(sn)
        combined_helper = SheetHelper(self.wb, sn)
        self.ws_map[sn] = combined_helper
        # populate combined sheet
        rec_count_merged = self._populate_combined_sheet(combined_helper)
        # correctness check
        if rec_count_sheets != rec_count_merged:
            raise RuntimeError(f'recommendation counts original: {rec_count_sheets} merged: {rec_count_merged}')

    def _combine_head(
        self, sheet_helper: SheetHelper, row: int, section_no: str, recommendation_no: str, tgt_col_profile: int
    ) -> None:
        """Combine head."""
        if not len(self.combined_map[section_no][recommendation_no].keys()):
            self.combined_map[section_no][recommendation_no][tgt_col_profile] = ['profile']
            for col in range(1, sheet_helper.get_max_col() + 1):
                if col < tgt_col_profile:
                    tcol = col
                else:
                    tcol = col + 1
                value = sheet_helper.get_cell_value(row, col)
                self.combined_map[section_no][recommendation_no][tcol] = value

    def _combine_data(
        self, sheet_helper: SheetHelper, row: int, section_no: str, recommendation_no: str, tgt_col_profile: int
    ) -> None:
        """Combine data."""
        if not len(self.combined_map[section_no][recommendation_no].keys()):
            self.combined_map[section_no][recommendation_no][tgt_col_profile] = []
        sn = sheet_helper.get_sn()
        self.combined_map[section_no][recommendation_no][tgt_col_profile].append(sn)
        for col in range(1, sheet_helper.get_max_col() + 1):
            if col < tgt_col_profile:
                tcol = col
            else:
                tcol = col + 1
            self.combined_map[section_no][recommendation_no][tcol] = sheet_helper.get_cell_value(row, col)

    def _save(self) -> None:
        """Save."""
        self.wb.save(self.opath)
        logger.debug(f'{self.opath} saved')
Attributes¤
combined_map = {} instance-attribute ¤
ipath = pathlib.Path(benchmark_file) instance-attribute ¤
opath = pathlib.Path(tmpdir) / self.ipath.name instance-attribute ¤
tgt_col_profile = 3 class-attribute instance-attribute ¤
wb = load_workbook(self.ipath) instance-attribute ¤
ws_map = {} instance-attribute ¤
Functions¤
__init__(config, tmpdir) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
311
312
313
314
315
316
317
318
def __init__(self, config: SectionProxy, tmpdir: str) -> None:
    """Initialize."""
    benchmark_file = config['benchmark-file']
    self.ipath = pathlib.Path(benchmark_file)
    self.opath = pathlib.Path(tmpdir) / self.ipath.name
    self.wb = load_workbook(self.ipath)
    self.ws_map = {}
    self.combined_map = {}
run() ¤

Run.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
320
321
322
323
def run(self) -> None:
    """Run."""
    self._add_sheet_combined_profiles()
    self._save()

CsvHelper ¤

Csv Helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
class CsvHelper:
    """Csv Helper."""

    def __init__(self, path: pathlib.Path) -> None:
        """Initialize."""
        self.path = path
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.rows = []

    def add_row(self, row: List[str]) -> None:
        """Add row."""
        self.rows.append(row)

    def delete_last_row(self) -> None:
        """Delete last row."""
        self.rows = self.rows[:-1]

    def write(self) -> None:
        """Write csv file."""
        with open(self.path, 'w', newline='', encoding='utf-8') as output:
            csv_writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
            for row in self.rows:
                csv_writer.writerow(row)

    def save(self) -> None:
        """Save csv file."""
        self.write()
        logger.debug(f'{self.path} saved')

    @staticmethod
    def columns() -> Dict:
        """Columns."""
        return {
            'Component_Title': 'A human readable name for the component.',  # noqa
            'Component_Description': 'A description of the component including information about its function.',  # noqa
            'Component_Type': 'A category describing the purpose of the component. ALLOWED VALUES interconnection:software:hardware:service:physical:process-procedure:plan:guidance:standard:validation:',  # noqa
            'Profile': 'List of CIS profiles',  # noqa
            'Rule_Id': 'A textual label that uniquely identifies a policy (desired state) that can be used to reference it elsewhere in this or other documents.',  # noqa
            'Rule_Description': 'A description of the policy (desired state) including information about its purpose and scope.',  # noqa
            'Profile_Source': 'A URL reference to the source catalog or profile for which this component is implementing controls for. A profile designates a selection and configuration of controls from one or more catalogs.',  # noqa
            'Profile_Description': 'A description of the profile.',  # noqa
            'Control_Id_List': 'A list of textual labels that uniquely identify the controls or statements that the component implements.',  # noqa
            'Namespace': 'A namespace qualifying the property\'s name. This allows different organizations to associate distinct semantics with the same name. Used in conjunction with "class" as the ontology concept.',  # noqa
        }
Attributes¤
path = path instance-attribute ¤
rows = [] instance-attribute ¤
Functions¤
__init__(path) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
529
530
531
532
533
def __init__(self, path: pathlib.Path) -> None:
    """Initialize."""
    self.path = path
    self.path.parent.mkdir(parents=True, exist_ok=True)
    self.rows = []
add_row(row) ¤

Add row.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
535
536
537
def add_row(self, row: List[str]) -> None:
    """Add row."""
    self.rows.append(row)
columns() staticmethod ¤

Columns.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
@staticmethod
def columns() -> Dict:
    """Columns."""
    return {
        'Component_Title': 'A human readable name for the component.',  # noqa
        'Component_Description': 'A description of the component including information about its function.',  # noqa
        'Component_Type': 'A category describing the purpose of the component. ALLOWED VALUES interconnection:software:hardware:service:physical:process-procedure:plan:guidance:standard:validation:',  # noqa
        'Profile': 'List of CIS profiles',  # noqa
        'Rule_Id': 'A textual label that uniquely identifies a policy (desired state) that can be used to reference it elsewhere in this or other documents.',  # noqa
        'Rule_Description': 'A description of the policy (desired state) including information about its purpose and scope.',  # noqa
        'Profile_Source': 'A URL reference to the source catalog or profile for which this component is implementing controls for. A profile designates a selection and configuration of controls from one or more catalogs.',  # noqa
        'Profile_Description': 'A description of the profile.',  # noqa
        'Control_Id_List': 'A list of textual labels that uniquely identify the controls or statements that the component implements.',  # noqa
        'Namespace': 'A namespace qualifying the property\'s name. This allows different organizations to associate distinct semantics with the same name. Used in conjunction with "class" as the ontology concept.',  # noqa
    }
delete_last_row() ¤

Delete last row.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
539
540
541
def delete_last_row(self) -> None:
    """Delete last row."""
    self.rows = self.rows[:-1]
save() ¤

Save csv file.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
550
551
552
553
def save(self) -> None:
    """Save csv file."""
    self.write()
    logger.debug(f'{self.path} saved')
write() ¤

Write csv file.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
543
544
545
546
547
548
def write(self) -> None:
    """Write csv file."""
    with open(self.path, 'w', newline='', encoding='utf-8') as output:
        csv_writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for row in self.rows:
            csv_writer.writerow(row)

CsvRowMgr ¤

Csv row manager.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
class CsvRowMgr:
    """Csv row manager."""

    def __init__(self, row_names: List) -> None:
        """Initialize."""
        self.row_names = row_names
        self.map = {}

    def put(self, key: str, val: str) -> None:
        """Put."""
        if key not in self.row_names:
            raise RuntimeError(f'{key} not found')
        self.map[key] = val

    def get(self) -> List[str]:
        """Get."""
        row = []
        for name in self.row_names:
            if name in self.map.keys():
                row.append(self.map[name])
            else:
                row.append('')
        return row
Attributes¤
map = {} instance-attribute ¤
row_names = row_names instance-attribute ¤
Functions¤
__init__(row_names) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
575
576
577
578
def __init__(self, row_names: List) -> None:
    """Initialize."""
    self.row_names = row_names
    self.map = {}
get() ¤

Get.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
586
587
588
589
590
591
592
593
594
def get(self) -> List[str]:
    """Get."""
    row = []
    for name in self.row_names:
        if name in self.map.keys():
            row.append(self.map[name])
        else:
            row.append('')
    return row
put(key, val) ¤

Put.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
580
581
582
583
584
def put(self, key: str, val: str) -> None:
    """Put."""
    if key not in self.row_names:
        raise RuntimeError(f'{key} not found')
    self.map[key] = val

CsvToJsonHelper ¤

Csv to json helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
class CsvToJsonHelper:
    """Csv to json helper."""

    def __init__(self, config_object: Optional[configparser.SectionProxy], tmpdir: str) -> None:
        """Initialize trestle task."""
        self.config_object = config_object
        benchmark_file = self.config_object['benchmark-file']
        self.ipath = pathlib.Path(benchmark_file)
        self.xpath = pathlib.Path(tmpdir) / self.ipath.name
        path = pathlib.Path(tmpdir) / self.xpath.name
        self.opath = path.with_suffix('.csv')
        self.config_object['csv-file'] = str(self.opath)
        self.csv_to_oscal_cd = CsvToOscalComponentDefinition(self.config_object)
        self.config_object['title'] = self.config_object['benchmark-title']
        self.config_object['version'] = self.config_object['benchmark-version']

    def run(self) -> None:
        """Run."""
        return self.csv_to_oscal_cd.execute()
Attributes¤
config_object = config_object instance-attribute ¤
csv_to_oscal_cd = CsvToOscalComponentDefinition(self.config_object) instance-attribute ¤
ipath = pathlib.Path(benchmark_file) instance-attribute ¤
opath = path.with_suffix('.csv') instance-attribute ¤
xpath = pathlib.Path(tmpdir) / self.ipath.name instance-attribute ¤
Functions¤
__init__(config_object, tmpdir) ¤

Initialize trestle task.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
950
951
952
953
954
955
956
957
958
959
960
961
def __init__(self, config_object: Optional[configparser.SectionProxy], tmpdir: str) -> None:
    """Initialize trestle task."""
    self.config_object = config_object
    benchmark_file = self.config_object['benchmark-file']
    self.ipath = pathlib.Path(benchmark_file)
    self.xpath = pathlib.Path(tmpdir) / self.ipath.name
    path = pathlib.Path(tmpdir) / self.xpath.name
    self.opath = path.with_suffix('.csv')
    self.config_object['csv-file'] = str(self.opath)
    self.csv_to_oscal_cd = CsvToOscalComponentDefinition(self.config_object)
    self.config_object['title'] = self.config_object['benchmark-title']
    self.config_object['version'] = self.config_object['benchmark-version']
run() ¤

Run.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
963
964
965
def run(self) -> None:
    """Run."""
    return self.csv_to_oscal_cd.execute()

Int ¤

Int.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
class Int:
    """Int."""

    def __init__(self, value=0):
        """Initialize."""
        self.value = value

    def inc_value(self) -> None:
        """Increment."""
        self.value += 1

    def get_value(self) -> int:
        """Get."""
        return self.value
Attributes¤
value = value instance-attribute ¤
Functions¤
__init__(value=0) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
293
294
295
def __init__(self, value=0):
    """Initialize."""
    self.value = value
get_value() ¤

Get.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
301
302
303
def get_value(self) -> int:
    """Get."""
    return self.value
inc_value() ¤

Increment.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
297
298
299
def inc_value(self) -> None:
    """Increment."""
    self.value += 1

NonRuleHelper ¤

Non-rule Helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
class NonRuleHelper:
    """Non-rule Helper."""

    def __init__(self, config: SectionProxy, xlsx_helper: XlsxToCsvHelper) -> None:
        """Initialize."""
        self.col_prefix = 'Group'
        self.col_level = 'Level'
        self.config = config
        self.xlsx_helper = xlsx_helper
        default_columns_carry_forward = [head_section_no, 'Title', 'Description']
        self.columns_carry_forward = self.config.get('columns-carry-forward', default_columns_carry_forward)
        self.col_list = []
        self.sec_map = {}
        if self.columns_carry_forward:
            self._init_col_list()
            self._init_sec_map()

    def _init_col_list(self) -> None:
        """Init col list."""
        biggest = -1
        for row in self.xlsx_helper.row_generator():
            rec_no = self.xlsx_helper.get(row, head_recommendation_no)
            if rec_no:
                continue
            sec_no = self.xlsx_helper.get(row, head_section_no)
            count = sec_no.count('.')
            if count > biggest:
                biggest = count
        for i in range(biggest + 1):
            for col_name in self.columns_carry_forward:
                name = f'{self.col_prefix}_{col_name}_{self.col_level}_{i}'
                name = PropertyHelper.normalize_name(name)
                self.col_list.append(name)

    def _init_sec_map(self) -> None:
        """Init sec map."""
        for row in self.xlsx_helper.row_generator():
            rec_no = self.xlsx_helper.get(row, head_recommendation_no)
            if rec_no:
                continue
            sec_no = self.xlsx_helper.get(row, head_section_no)
            _map = {}
            for name in self.columns_carry_forward:
                _map[name] = self.xlsx_helper.get(row, name)
            self.sec_map[sec_no] = _map

    def get_all_columns(self) -> List:
        """Get all columns."""
        return self.col_list

    def add_group_levels(self, rec_no: str, csv_row_mgr: CsvRowMgr) -> None:
        """Add group levels."""
        parts = rec_no.split('.')[:-1]
        for i, part in enumerate(parts):
            if not i:
                sec_no = f'{part}'
            else:
                sec_no = f'{sec_no}.{part}'
            if sec_no in self.sec_map.keys():
                _map = self.sec_map[sec_no]
                for key in _map.keys():
                    val = _map[key]
                    name = f'{self.col_prefix}_{key}_{self.col_level}_{i}'
                    name = PropertyHelper.normalize_name(name)
                    csv_row_mgr.put(name, val)
Attributes¤
col_level = 'Level' instance-attribute ¤
col_list = [] instance-attribute ¤
col_prefix = 'Group' instance-attribute ¤
columns_carry_forward = self.config.get('columns-carry-forward', default_columns_carry_forward) instance-attribute ¤
config = config instance-attribute ¤
sec_map = {} instance-attribute ¤
xlsx_helper = xlsx_helper instance-attribute ¤
Functions¤
__init__(config, xlsx_helper) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
883
884
885
886
887
888
889
890
891
892
893
894
895
def __init__(self, config: SectionProxy, xlsx_helper: XlsxToCsvHelper) -> None:
    """Initialize."""
    self.col_prefix = 'Group'
    self.col_level = 'Level'
    self.config = config
    self.xlsx_helper = xlsx_helper
    default_columns_carry_forward = [head_section_no, 'Title', 'Description']
    self.columns_carry_forward = self.config.get('columns-carry-forward', default_columns_carry_forward)
    self.col_list = []
    self.sec_map = {}
    if self.columns_carry_forward:
        self._init_col_list()
        self._init_sec_map()
add_group_levels(rec_no, csv_row_mgr) ¤

Add group levels.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def add_group_levels(self, rec_no: str, csv_row_mgr: CsvRowMgr) -> None:
    """Add group levels."""
    parts = rec_no.split('.')[:-1]
    for i, part in enumerate(parts):
        if not i:
            sec_no = f'{part}'
        else:
            sec_no = f'{sec_no}.{part}'
        if sec_no in self.sec_map.keys():
            _map = self.sec_map[sec_no]
            for key in _map.keys():
                val = _map[key]
                name = f'{self.col_prefix}_{key}_{self.col_level}_{i}'
                name = PropertyHelper.normalize_name(name)
                csv_row_mgr.put(name, val)
get_all_columns() ¤

Get all columns.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
926
927
928
def get_all_columns(self) -> List:
    """Get all columns."""
    return self.col_list

PropertyHelper ¤

Property Helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
514
515
516
517
518
519
520
521
522
523
class PropertyHelper:
    """Property Helper."""

    @staticmethod
    def normalize_name(name: str) -> str:
        """Normalize name."""
        rval = name.replace('(', '').replace(')', '').replace('#', '').strip()
        rval = rval.replace(' ', '_')
        rval = rval.replace('__', '_')
        return rval
Functions¤
normalize_name(name) staticmethod ¤

Normalize name.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
517
518
519
520
521
522
523
@staticmethod
def normalize_name(name: str) -> str:
    """Normalize name."""
    rval = name.replace('(', '').replace(')', '').replace('#', '').strip()
    rval = rval.replace(' ', '_')
    rval = rval.replace('__', '_')
    return rval

SheetHelper ¤

SheetHelper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
class SheetHelper:
    """SheetHelper."""

    def __init__(self, wb: Workbook, sn: str) -> None:
        """Initialize."""
        self.wb = wb
        self.sn = sn
        self.ws = self.wb[self.sn]

    def get_sn(self) -> int:
        """Get sheet name."""
        return self.sn

    def get_max_col(self) -> int:
        """Get max column."""
        return self.ws.max_column

    def row_generator(self) -> Iterator[int]:
        """Generate rows until max reached."""
        row = 1
        while row <= self.ws.max_row:
            yield row
            row += 1

    def get_cell_value(self, row: int, col: int) -> str:
        """Get cell value for given row and column name."""
        cell = self.ws.cell(row, col)
        return cell.value

    def put_cell_value(self, row: int, col: int, value: str) -> None:
        """Get cell value for given row and column name."""
        cell = self.ws.cell(row, col)
        cell.value = value

    @staticmethod
    def get_sheetname_prefixes() -> List[str]:
        """Get sheetnames prefixes."""
        rval = ['Level 1', 'Level 2']
        return rval

    @staticmethod
    def get_sheetname() -> str:
        """Get sheetname output."""
        rval = 'Combined Profiles'
        return rval
Attributes¤
sn = sn instance-attribute ¤
wb = wb instance-attribute ¤
ws = self.wb[self.sn] instance-attribute ¤
Functions¤
__init__(wb, sn) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
232
233
234
235
236
def __init__(self, wb: Workbook, sn: str) -> None:
    """Initialize."""
    self.wb = wb
    self.sn = sn
    self.ws = self.wb[self.sn]
get_cell_value(row, col) ¤

Get cell value for given row and column name.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
253
254
255
256
def get_cell_value(self, row: int, col: int) -> str:
    """Get cell value for given row and column name."""
    cell = self.ws.cell(row, col)
    return cell.value
get_max_col() ¤

Get max column.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
242
243
244
def get_max_col(self) -> int:
    """Get max column."""
    return self.ws.max_column
get_sheetname() staticmethod ¤

Get sheetname output.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
269
270
271
272
273
@staticmethod
def get_sheetname() -> str:
    """Get sheetname output."""
    rval = 'Combined Profiles'
    return rval
get_sheetname_prefixes() staticmethod ¤

Get sheetnames prefixes.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
263
264
265
266
267
@staticmethod
def get_sheetname_prefixes() -> List[str]:
    """Get sheetnames prefixes."""
    rval = ['Level 1', 'Level 2']
    return rval
get_sn() ¤

Get sheet name.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
238
239
240
def get_sn(self) -> int:
    """Get sheet name."""
    return self.sn
put_cell_value(row, col, value) ¤

Get cell value for given row and column name.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
258
259
260
261
def put_cell_value(self, row: int, col: int, value: str) -> None:
    """Get cell value for given row and column name."""
    cell = self.ws.cell(row, col)
    cell.value = value
row_generator() ¤

Generate rows until max reached.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
246
247
248
249
250
251
def row_generator(self) -> Iterator[int]:
    """Generate rows until max reached."""
    row = 1
    while row <= self.ws.max_row:
        yield row
        row += 1

SortHelper ¤

SortHelper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
class SortHelper:
    """SortHelper."""

    @staticmethod
    def compare(item1: str, item2: str) -> int:
        """Compare."""
        # get parts
        parts1 = ''.split('.')
        if item1 is not None:
            parts1 = str(item1).split('.')
        parts2 = ''.split('.')
        if item2 is not None:
            parts2 = str(item2).split('.')
        # normalize parts length
        while len(parts1) < len(parts2):
            parts1.append('0')
        while len(parts2) < len(parts1):
            parts2.append('0')
        # comparison
        rval = 0
        for i in range(len(parts1)):
            try:
                v1 = int(parts1[i])
            except Exception:
                rval = -1
                break
            try:
                v2 = int(parts2[i])
            except Exception:
                rval = 1
                break
            if v1 < v2:
                rval = -1
                break
            if v1 > v2:
                rval = 1
                break
        text = f'compare rval: {rval} item1: {item1} item2: {item2}'
        logger.debug(f'{text}')
        return rval
Functions¤
compare(item1, item2) staticmethod ¤

Compare.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
@staticmethod
def compare(item1: str, item2: str) -> int:
    """Compare."""
    # get parts
    parts1 = ''.split('.')
    if item1 is not None:
        parts1 = str(item1).split('.')
    parts2 = ''.split('.')
    if item2 is not None:
        parts2 = str(item2).split('.')
    # normalize parts length
    while len(parts1) < len(parts2):
        parts1.append('0')
    while len(parts2) < len(parts1):
        parts2.append('0')
    # comparison
    rval = 0
    for i in range(len(parts1)):
        try:
            v1 = int(parts1[i])
        except Exception:
            rval = -1
            break
        try:
            v2 = int(parts2[i])
        except Exception:
            rval = 1
            break
        if v1 < v2:
            rval = -1
            break
        if v1 > v2:
            rval = 1
            break
    text = f'compare rval: {rval} item1: {item1} item2: {item2}'
    logger.debug(f'{text}')
    return rval

XlsxToCsvHelper ¤

Xlsx to csv helper.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
class XlsxToCsvHelper:
    """Xlsx to csv helper."""

    def __init__(self, config_object: SectionProxy, tmpdir: str) -> None:
        """Initialize."""
        self.config_object = config_object
        benchmark_file = self.config_object['benchmark-file']
        self.ipath = pathlib.Path(benchmark_file)
        self.xpath = pathlib.Path(tmpdir) / self.ipath.name
        path = pathlib.Path(tmpdir) / self.xpath.name
        self.opath = path.with_suffix('.csv')
        self.wb = load_workbook(self.xpath)
        # worksheet
        self.ws = self.wb[SheetHelper.get_sheetname()]
        self._create_maps()
        # excluded columns
        default_columns_exclude = [f'"{head_recommendation_no}"', '"Profile"', '"Description"']
        columns_exclude = self.config_object.get('columns-exclude')
        if columns_exclude:
            columns_exclude = columns_exclude.strip().split(',')
        else:
            columns_exclude = default_columns_exclude
        self._columns_exclude = []
        for col in columns_exclude:
            name = PropertyHelper.normalize_name(col.replace('"', ''))
            self._columns_exclude.append(name)
        # benchmark control prefix
        self._benchmark_control_prefix = self.config_object.get(
            'benchmark-control-prefix', default_benchmark_control_prefix
        )
        if not self._benchmark_control_prefix.endswith('-'):
            self._benchmark_control_prefix = f'{self._benchmark_control_prefix}-'
        # benchmark rule prefix
        self._benchmark_rule_prefix = self.config_object.get('benchmark-rule-prefix', default_benchmark_rule_prefix)
        if not self._benchmark_rule_prefix.endswith('-'):
            self._benchmark_rule_prefix = f'{self._benchmark_rule_prefix}-'

    def _create_maps(self) -> Dict:
        """Create maps."""
        self._map_col_key_to_number = {}
        self._map_name_to_col_key = {}
        row = 1
        cols = self.ws.max_column + 1
        for col in range(row, cols):
            cell = self.ws.cell(row, col)
            if cell.value:
                key = self._name_to_key(cell.value)
                self._map_col_key_to_number[key] = col
                self._map_name_to_col_key[cell.value] = key

    def _name_to_key(self, name: str) -> str:
        """Name to key."""
        rval = name.lower()
        return rval

    def _sanitize(self, value: str) -> str:
        """Sanitize value."""
        rval = value
        if value:
            rval = value.replace('\n', ' ')
        return rval

    def _get_map(self) -> Dict:
        """Get map."""
        return self._map_name_to_col_key

    def get_all_columns(self) -> List:
        """Get all columns."""
        return self._get_map().keys()

    def row_generator(self) -> Iterator[int]:
        """Generate rows until max reached."""
        row = 2
        while row <= self.ws.max_row:
            yield row
            row += 1

    def get(self, row: int, name: str) -> str:
        """Get cell value for given row and column name."""
        key = self._name_to_key(name)
        col = self._map_col_key_to_number[key]
        cell = self.ws.cell(row, col)
        return self._sanitize(cell.value)

    def is_same_rule(self, row_a: int, row_b: str) -> str:
        """Is same rule."""
        rule_a = self.get(row_a, head_recommendation_no)
        rule_b = self.get(row_b, head_recommendation_no)
        rval = rule_a == rule_b
        logger.debug(f'{rval} {rule_a} {rule_b}')
        return rval

    def is_excluded_column(self, column: str) -> bool:
        """Is excluded column."""
        for item in self._columns_exclude:
            if item.lower() == column.lower():
                return True
        return False

    def merge_row(self, prev_row: int, curr_row: int) -> bool:
        """Merge row."""
        rval = False
        if prev_row and self.is_same_rule(prev_row, curr_row):
            prof2 = self.get(prev_row, 'Profile')
            prof1 = self.get(curr_row, 'Profile')
            prof = f'"{prof1}; {prof2}"'
            self.csv_helper.delete_last_row()
            # col Profile
            self.csv_row_mgr.put('Profile', prof)
            # add body row
            row_body = self.csv_row_mgr.get()
            self.csv_helper.add_row(row_body)
            rval = True
        return rval

    def _is_column(self, c1: str, c2: str) -> bool:
        """Is column."""
        if c1.lower() == c2.lower():
            rval = True
        else:
            rval = False
        return rval

    def heading_row_1(self) -> None:
        """Heading row 1."""
        self.row_names = []
        for col_name in CsvHelper.columns().keys():
            name = PropertyHelper.normalize_name(col_name)
            self.row_names.append(name)

    def heading_row_2(self) -> None:
        """Heading row 2."""
        self.row_descs = []
        for col_desc in CsvHelper.columns().values():
            desc = col_desc
            self.row_descs.append(desc)
        # additional user columns
        for col in self.get_all_columns():
            name = PropertyHelper.normalize_name(col)
            if self.is_excluded_column(col):
                continue
            self.row_names.append(name)
            self.row_descs.append(name)
        # additional non-rule columns
        for col in self.non_rule_helper.get_all_columns():
            name = PropertyHelper.normalize_name(col)
            self.row_names.append(name)
            self.row_descs.append(name)

    def _get_ctl_list(self, prev_row: int, curr_row: int) -> List[str]:
        """Get_ctl_list."""
        ctl_list = []
        # if merged row, list is empty
        if not self.merge_row(prev_row, curr_row):
            # if non-rule row, list is empty
            rec_no = self.get(curr_row, head_recommendation_no)
            if rec_no is not None:
                # get list
                cis_controls = self.get(curr_row, 'CIS Controls')
                cis_control_helper = CisControlsHelper(cis_controls)
                ctl_list = cis_control_helper.get_ctl_list(
                    self._benchmark_control_prefix, self.config_object['profile-version']
                )
        return ctl_list

    def run(self) -> None:
        """Run."""
        self.csv_helper = CsvHelper(self.opath)
        self.non_rule_helper = NonRuleHelper(self.config_object, self)
        # heading row 1 - names
        self.heading_row_1()
        # heading row 2 - descriptions
        self.heading_row_2()
        # add heading rows
        self.csv_helper.add_row(self.row_names)
        self.csv_helper.add_row(self.row_descs)
        # body
        user_columns = []
        for col in self.get_all_columns():
            if self.is_excluded_column(col):
                continue
            user_columns.append(col)
        # process each data row of CIS Benchmark file
        prev_row = None
        for curr_row in self.row_generator():
            ctl_list = self._get_ctl_list(prev_row, curr_row)
            if not ctl_list:
                continue
            # create new row
            self.csv_row_mgr = CsvRowMgr(self.row_names)
            # col Component_Title
            self.csv_row_mgr.put('Component_Title', self.config_object['component-name'])
            # col Component_Description
            self.csv_row_mgr.put('Component_Description', self.config_object['component-description'])
            # col Component_Type
            self.csv_row_mgr.put('Component_Type', self.config_object['component-type'])
            # col Rule_ID
            rec_no = self.get(curr_row, head_recommendation_no)
            rule_id = f'{self._benchmark_rule_prefix}{rec_no}'
            self.csv_row_mgr.put('Rule_Id', rule_id)
            # col Rule_Description
            rule_desc = self.get(curr_row, 'Description')
            self.csv_row_mgr.put('Rule_Description', rule_desc)
            # col Profile_Source
            self.csv_row_mgr.put('Profile_Source', self.config_object['profile-source'])
            # col Profile_Description
            self.csv_row_mgr.put('Profile_Description', self.config_object['profile-description'])
            # col Control_Id_List
            ctl_list = ' '.join(ctl_list)
            self.csv_row_mgr.put('Control_Id_List', ctl_list)
            # col Namespace
            self.csv_row_mgr.put('Namespace', self.config_object['namespace'])
            # col Profile
            prof = self.get(curr_row, 'Profile')
            self.csv_row_mgr.put('Profile', prof)
            # col user
            for col in user_columns:
                val = self.get(curr_row, col)
                if val:
                    if self._is_column(col, 'cis controls'):
                        val = f'"{val}"'
                    name = PropertyHelper.normalize_name(col)
                    self.csv_row_mgr.put(name, val)
            # col group levels
            self.non_rule_helper.add_group_levels(rec_no, self.csv_row_mgr)
            # add body row
            row_body = self.csv_row_mgr.get()
            self.csv_helper.add_row(row_body)
            # previous row
            prev_row = curr_row
        # write body
        self.csv_helper.save()
Attributes¤
config_object = config_object instance-attribute ¤
ipath = pathlib.Path(benchmark_file) instance-attribute ¤
opath = path.with_suffix('.csv') instance-attribute ¤
wb = load_workbook(self.xpath) instance-attribute ¤
ws = self.wb[SheetHelper.get_sheetname()] instance-attribute ¤
xpath = pathlib.Path(tmpdir) / self.ipath.name instance-attribute ¤
Functions¤
__init__(config_object, tmpdir) ¤

Initialize.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def __init__(self, config_object: SectionProxy, tmpdir: str) -> None:
    """Initialize."""
    self.config_object = config_object
    benchmark_file = self.config_object['benchmark-file']
    self.ipath = pathlib.Path(benchmark_file)
    self.xpath = pathlib.Path(tmpdir) / self.ipath.name
    path = pathlib.Path(tmpdir) / self.xpath.name
    self.opath = path.with_suffix('.csv')
    self.wb = load_workbook(self.xpath)
    # worksheet
    self.ws = self.wb[SheetHelper.get_sheetname()]
    self._create_maps()
    # excluded columns
    default_columns_exclude = [f'"{head_recommendation_no}"', '"Profile"', '"Description"']
    columns_exclude = self.config_object.get('columns-exclude')
    if columns_exclude:
        columns_exclude = columns_exclude.strip().split(',')
    else:
        columns_exclude = default_columns_exclude
    self._columns_exclude = []
    for col in columns_exclude:
        name = PropertyHelper.normalize_name(col.replace('"', ''))
        self._columns_exclude.append(name)
    # benchmark control prefix
    self._benchmark_control_prefix = self.config_object.get(
        'benchmark-control-prefix', default_benchmark_control_prefix
    )
    if not self._benchmark_control_prefix.endswith('-'):
        self._benchmark_control_prefix = f'{self._benchmark_control_prefix}-'
    # benchmark rule prefix
    self._benchmark_rule_prefix = self.config_object.get('benchmark-rule-prefix', default_benchmark_rule_prefix)
    if not self._benchmark_rule_prefix.endswith('-'):
        self._benchmark_rule_prefix = f'{self._benchmark_rule_prefix}-'
get(row, name) ¤

Get cell value for given row and column name.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
723
724
725
726
727
728
def get(self, row: int, name: str) -> str:
    """Get cell value for given row and column name."""
    key = self._name_to_key(name)
    col = self._map_col_key_to_number[key]
    cell = self.ws.cell(row, col)
    return self._sanitize(cell.value)
get_all_columns() ¤

Get all columns.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
712
713
714
def get_all_columns(self) -> List:
    """Get all columns."""
    return self._get_map().keys()
heading_row_1() ¤

Heading row 1.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
769
770
771
772
773
774
def heading_row_1(self) -> None:
    """Heading row 1."""
    self.row_names = []
    for col_name in CsvHelper.columns().keys():
        name = PropertyHelper.normalize_name(col_name)
        self.row_names.append(name)
heading_row_2() ¤

Heading row 2.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
def heading_row_2(self) -> None:
    """Heading row 2."""
    self.row_descs = []
    for col_desc in CsvHelper.columns().values():
        desc = col_desc
        self.row_descs.append(desc)
    # additional user columns
    for col in self.get_all_columns():
        name = PropertyHelper.normalize_name(col)
        if self.is_excluded_column(col):
            continue
        self.row_names.append(name)
        self.row_descs.append(name)
    # additional non-rule columns
    for col in self.non_rule_helper.get_all_columns():
        name = PropertyHelper.normalize_name(col)
        self.row_names.append(name)
        self.row_descs.append(name)
is_excluded_column(column) ¤

Is excluded column.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
738
739
740
741
742
743
def is_excluded_column(self, column: str) -> bool:
    """Is excluded column."""
    for item in self._columns_exclude:
        if item.lower() == column.lower():
            return True
    return False
is_same_rule(row_a, row_b) ¤

Is same rule.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
730
731
732
733
734
735
736
def is_same_rule(self, row_a: int, row_b: str) -> str:
    """Is same rule."""
    rule_a = self.get(row_a, head_recommendation_no)
    rule_b = self.get(row_b, head_recommendation_no)
    rval = rule_a == rule_b
    logger.debug(f'{rval} {rule_a} {rule_b}')
    return rval
merge_row(prev_row, curr_row) ¤

Merge row.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
def merge_row(self, prev_row: int, curr_row: int) -> bool:
    """Merge row."""
    rval = False
    if prev_row and self.is_same_rule(prev_row, curr_row):
        prof2 = self.get(prev_row, 'Profile')
        prof1 = self.get(curr_row, 'Profile')
        prof = f'"{prof1}; {prof2}"'
        self.csv_helper.delete_last_row()
        # col Profile
        self.csv_row_mgr.put('Profile', prof)
        # add body row
        row_body = self.csv_row_mgr.get()
        self.csv_helper.add_row(row_body)
        rval = True
    return rval
row_generator() ¤

Generate rows until max reached.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
716
717
718
719
720
721
def row_generator(self) -> Iterator[int]:
    """Generate rows until max reached."""
    row = 2
    while row <= self.ws.max_row:
        yield row
        row += 1
run() ¤

Run.

Source code in trestle/tasks/cis_xlsx_to_oscal_cd.py
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def run(self) -> None:
    """Run."""
    self.csv_helper = CsvHelper(self.opath)
    self.non_rule_helper = NonRuleHelper(self.config_object, self)
    # heading row 1 - names
    self.heading_row_1()
    # heading row 2 - descriptions
    self.heading_row_2()
    # add heading rows
    self.csv_helper.add_row(self.row_names)
    self.csv_helper.add_row(self.row_descs)
    # body
    user_columns = []
    for col in self.get_all_columns():
        if self.is_excluded_column(col):
            continue
        user_columns.append(col)
    # process each data row of CIS Benchmark file
    prev_row = None
    for curr_row in self.row_generator():
        ctl_list = self._get_ctl_list(prev_row, curr_row)
        if not ctl_list:
            continue
        # create new row
        self.csv_row_mgr = CsvRowMgr(self.row_names)
        # col Component_Title
        self.csv_row_mgr.put('Component_Title', self.config_object['component-name'])
        # col Component_Description
        self.csv_row_mgr.put('Component_Description', self.config_object['component-description'])
        # col Component_Type
        self.csv_row_mgr.put('Component_Type', self.config_object['component-type'])
        # col Rule_ID
        rec_no = self.get(curr_row, head_recommendation_no)
        rule_id = f'{self._benchmark_rule_prefix}{rec_no}'
        self.csv_row_mgr.put('Rule_Id', rule_id)
        # col Rule_Description
        rule_desc = self.get(curr_row, 'Description')
        self.csv_row_mgr.put('Rule_Description', rule_desc)
        # col Profile_Source
        self.csv_row_mgr.put('Profile_Source', self.config_object['profile-source'])
        # col Profile_Description
        self.csv_row_mgr.put('Profile_Description', self.config_object['profile-description'])
        # col Control_Id_List
        ctl_list = ' '.join(ctl_list)
        self.csv_row_mgr.put('Control_Id_List', ctl_list)
        # col Namespace
        self.csv_row_mgr.put('Namespace', self.config_object['namespace'])
        # col Profile
        prof = self.get(curr_row, 'Profile')
        self.csv_row_mgr.put('Profile', prof)
        # col user
        for col in user_columns:
            val = self.get(curr_row, col)
            if val:
                if self._is_column(col, 'cis controls'):
                    val = f'"{val}"'
                name = PropertyHelper.normalize_name(col)
                self.csv_row_mgr.put(name, val)
        # col group levels
        self.non_rule_helper.add_group_levels(rec_no, self.csv_row_mgr)
        # add body row
        row_body = self.csv_row_mgr.get()
        self.csv_helper.add_row(row_body)
        # previous row
        prev_row = curr_row
    # write body
    self.csv_helper.save()

Functions¤

handler: python