All files / src/resolvers RuleDefinitionResolver.ts

96.36% Statements 53/55
87.5% Branches 28/32
100% Functions 14/14
96.08% Lines 49/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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 185 186 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                                              4x 4x 4x     4x           3x   3x                   6x   6x                               12x 7x 6x 6x 1x         1x 1x     1x   5x 5x         5x       1x           4x   4x 4x                   4x 4x       9x 9x               4x     4x                     8x 8x 2x 2x                         2x             2x                   4x   4x   4x   4x       4x   2x     4x     4x             10x 10x       8x 8x               2x 2x        
/* 
  Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  
  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
import {
    FlowObject,
    FlowRule,
    FlowRuleBundle,
    Logger,
    LoggerFactory,
    ResolvedFlowObject,
} from 'shared_types';
import { ObjectDefinitionResolver } from 'shared_types/src/resolvers/ObjectDefinitionResolver';
import UnderlyingServiceError from 'src/common/UnderlyingServiceError';
import { inject, injectable } from 'tsyringe';
 
@injectable()
export class RuleDefinitionResolver {
    logger: Logger;
 
    constructor(
        @inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('ObjectDefinitionResolver')
        private objectDefinitionResolver: ObjectDefinitionResolver
    ) {
        this.logger = loggerFactory.getLogger('RuleDefinitionResolver');
    }
 
    async resolveRules(
        ruleBundle: FlowRuleBundle,
        rules: FlowRule[],
        objects: FlowObject[],
        overallIndex: number
    ): Promise<FlowRule[]> {
        // check if all object can be referenced
        return Promise.all(
            rules.map((rule) =>
                this.resolveRule(
                    ruleBundle,
                    rule,
                    objects,
                    overallIndex + rules.indexOf(rule)
                )
            )
        );
    }
 
    private async resolveRule(
        ruleBundle: FlowRuleBundle,
        rule: FlowRule,
        objects: FlowObject[],
        index: number
    ): Promise<FlowRule> {
        const destinationTarget = objects.find((tgt) => tgt.id === rule.destination);
        const sourceTarget = objects.find((tgt) => tgt.id === rule.source);
        this.logger.info('resolving ', rule);
        if (!destinationTarget || !sourceTarget) {
            this.logger.error(
                'invalid reference objects',
                destinationTarget,
                sourceTarget
            );
            rule.status = 'FAILED';
            rule.failureReasons = [
                'Unable to resolve reference object of source and/or destination',
            ];
            return rule;
        }
        const resolvedSource = await this.resolveTarget(ruleBundle, sourceTarget);
        const resolvedDestination = await this.resolveTarget(
            ruleBundle,
            destinationTarget
        );
 
        if (
            this.encounterUnderlyingServiceError(resolvedSource.failureReasons) ||
            this.encounterUnderlyingServiceError(resolvedDestination.failureReasons)
        ) {
            throw new UnderlyingServiceError(
                'An error occurred when saving the new object',
                503,
                true
            );
        }
        this.updateRuleStatus(resolvedSource, rule, resolvedDestination);
 
        const sid = index + 1;
        const result = {
            ...rule,
 
            suricataString: this.createSuricataRuleString(
                rule,
                resolvedSource,
                resolvedDestination,
                sid
            ),
        };
        this.logger.info('resolveRules -> resolveRule', result);
        return result;
    }
 
    encounterUnderlyingServiceError(failureReasons?: string[]): boolean {
        const hasReasons = failureReasons && failureReasons.length > 0;
        return hasReasons ?? false;
    }
 
    private updateRuleStatus(
        resolvedSource: ResolvedFlowObject,
        rule: FlowRule,
        resolvedDestination: ResolvedFlowObject
    ) {
        this.tryUpdateRuleWithAssociatedFailure(resolvedSource, rule, [
            `Can not resolve source object to address ${resolvedSource.id}`,
        ]);
        this.tryUpdateRuleWithAssociatedFailure(resolvedDestination, rule, [
            `Can not resolve destination object to address ${resolvedDestination.id}`,
        ]);
    }
 
    private tryUpdateRuleWithAssociatedFailure(
        resolvedSource: ResolvedFlowObject,
        rule: FlowRule,
        defaultReasons: [string]
    ) {
        const hasReasons =
            resolvedSource.failureReasons && resolvedSource.failureReasons.length > 0;
        if (resolvedSource.addresses.length === 0 || hasReasons) {
            rule.status = 'FAILED';
            rule.failureReasons = this.getFailedReasonPhrases(
                resolvedSource,
                hasReasons,
                defaultReasons
            );
        }
    }
 
    private getFailedReasonPhrases(
        resolvedSource: ResolvedFlowObject,
        hasReasons: boolean | undefined,
        canNotResolveToAddress: string[]
    ) {
        Iif (hasReasons) {
            this.logger.info(
                'Update rule with original failure reasons',
                resolvedSource.failureReasons
            );
            return resolvedSource.failureReasons;
        } else {
            return canNotResolveToAddress;
        }
    }
 
    private createSuricataRuleString(
        rule: FlowRule,
        resolvedSource: FlowObject,
        resolvedDestination: FlowObject,
        sid: number
    ): string {
        const options = this.createRuleOptions(rule, sid);
        const sourcePortValue =
            rule.sourcePort.type === 'Any' ? 'any' : rule.sourcePort.value;
        const destinationPortValue =
            rule.destinationPort.type === 'Any' ? 'any' : rule.destinationPort.value;
 
        return `${rule.action} ${rule.protocol} ${resolvedSource.value} ${sourcePortValue} ->  ${resolvedDestination.value} ${destinationPortValue} ${options} `;
    }
 
    private createRuleOptions(rule: FlowRule, sid: number) {
        const allAdditionalOptions = rule.optionFields
            ?.map((kp) => {
                return `${kp.key}: ${kp.value}`;
            })
            .join('; ');
        const appendedOptions = allAdditionalOptions
            ? ' ' + allAdditionalOptions + ';'
            : '';
        return `(msg: "${rule.id}"; sid: ${sid};${appendedOptions})`;
    }
 
    private async resolveTarget(
        ruleBundle: FlowRuleBundle,
        originalTarget: FlowObject
    ): Promise<ResolvedFlowObject> {
        try {
            const resolvedTarget = await this.objectDefinitionResolver.resolveTarget(
                originalTarget,
                ruleBundle
            );
            this.logger.info('RuleDefinitionResolver resolved object', resolvedTarget);
            return {
                id: resolvedTarget.id,
                type: resolvedTarget.type,
                value: resolvedTarget.addresses,
                addresses: resolvedTarget.addresses,
                failureReasons: resolvedTarget.failureReasons,
            };
        } catch (e) {
            this.logger.error('got exception', e);
            return { ...originalTarget, addresses: [], failureReasons: [e.message] };
        }
    }
}