All files / src/validators CreateRuletInputValidator.ts

100% Statements 107/107
100% Branches 54/54
100% Functions 9/9
100% Lines 105/105

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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 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                              5x 5x 5x 5x   5x 5x 5x   5x 5x 5x 5x   5x                           5x 59x           59x   59x   59x 59x       58x 1x 1x     58x 1x 1x     58x 58x 1x 1x   57x     57x 1x     1x           58x   58x 58x       116x 2x 2x 2x     114x 2x     2x     2x     112x 2x     2x       110x 110x 110x 45x 2x     2x           110x 55x 55x 10x           55x 2x 2x   53x       65x 65x 4x     4x     61x 6x     6x       65x     10x 2x 2x   8x 8x 6x 6x 6x 2x     2x         2x     2x               58x 2x 2x   56x     56x 1x 1x     56x     56x 1x     1x               58x   18x 1x 1x     17x 17x 1x 1x     17x 11x 11x     17x 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 'reflect-metadata';
import { FlowRulePort, FLOW_TARGET_TYPES_STR, Logger, LoggerFactory } from 'shared_types';
import { ObjectsDataSourceService } from 'src/service/ObjectsDataSourceService';
import { RuleBundleDataSourceService } from 'src/service/RuleBundleDataSourceService';
import { FlowRuleInput } from 'src/types/FlowRule';
import { inject, injectable } from 'tsyringe';
import { InputValidator } from './InputValidator';
import * as _ from 'lodash';
 
const SUPPORTED_PROTOCOLS = ['tcp', 'udp', 'icmp'];
const SUPPORTED_ACTIONS = ['pass', 'drop', 'alert'];
const RESERVED_OPTIONS = ['msg', 'sid'];
const MAX_PORT_NUMBER = 65535;
// key in known unsupported list https://docs.aws.amazon.com/network-firewall/latest/developerguide/suricata-limitations-caveats.html
const KNOWN_UNSUPPORTED_OPTIONS = [
    'iprep',
    'lua',
    'geoip',
    'filestore',
    'fileext',
    'filemagic',
    'threshold',
    'enip_command',
    'cip_service',
    'datarep',
    'dataset',
];
@injectable()
export class CreateRuleInputValidator extends InputValidator<FlowRuleInput> {
    PORT_RANGE_REGX = /\[(\d+):(\d.+)\]/;
 
    logger: Logger;
    constructor(
        @inject('LoggerFactory') loggerFactory: LoggerFactory,
        @inject('RuleBundleDataSourceService')
        private ruleGroupDataSourceService: RuleBundleDataSourceService,
        @inject('ObjectsDataSourceService')
        private targetsDataSourceService: ObjectsDataSourceService
    ) {
        super();
        this.logger = loggerFactory.getLogger('CreateRuleInputValidator');
    }
 
    protected async validate(input: FlowRuleInput): Promise<void> {
        if (!SUPPORTED_PROTOCOLS.includes(input.protocol)) {
            this.logger.info(`rule : protocol ${input.protocol} is not supported.`);
            this.errors.push(`rule : protocol ${input.protocol} is not supported.`);
        }
 
        if (!SUPPORTED_ACTIONS.includes(input.action)) {
            this.logger.info(`rule : action ${input.action} is not supported.`);
            this.errors.push(`rule : action ${input.action} is not supported.`);
        }
 
        this.validOptionFields(input);
        if (!input.ruleBundleId) {
            this.logger.info(`rule : rulebundle is missing`);
            this.errors.push(`rule : rulebundle is missing`);
        } else {
            const ruleBundle = await this.ruleGroupDataSourceService.getRuleBundleBy(
                input.ruleBundleId
            );
            if (!ruleBundle) {
                this.logger.info(
                    `rule : rule bundle ${input.ruleBundleId} does not exists.`
                );
                this.errors.push(
                    `rule : rule bundle ${input.ruleBundleId} does not exists.`
                );
            }
        }
 
        await this.validSrcAndDst(input);
 
        this.validRulePorts(input.sourcePort, 'sourcePort');
        this.validRulePorts(input.destinationPort, 'destinationPort');
    }
 
    private validRulePorts(port: FlowRulePort, portName: string) {
        if (!port) {
            this.logger.error(`Invalid ${portName} : port is missing in the request.`);
            this.errors.push(`Invalid ${portName} : port is missing in the request.`);
            return;
        }
 
        if (!port.type) {
            this.logger.error(
                `Invalid ${portName} : port type is missing in the request.`
            );
            this.errors.push(
                `Invalid ${portName} : port type is missing in the request.`
            );
            return;
        }
 
        if (!FLOW_TARGET_TYPES_STR.includes(port.type)) {
            this.logger.error(
                `Invalid ${portName} : port type [${port.type}] is not supported.`
            );
            this.errors.push(
                `Invalid ${portName} : port type [${port.type}] is not supported.`
            );
        } else {
            const portType = port.type;
            const portValue = port.value;
            if (portType === 'Any') {
                if (portValue) {
                    this.logger.error(
                        `Invalid ${portName} : port type [${port.type}] should not associated any value but port value provided [${portValue}].`
                    );
                    this.errors.push(
                        `Invalid ${portName} : port type [${port.type}] should not associated any value but port value provided [${portValue}].`
                    );
                }
            }
 
            if (portType === 'SinglePort') {
                this.validSinglePort(portValue, portName);
            } else if (portType === 'PortRange') {
                this.validPortRange(portValue, portName);
            }
        }
    }
 
    private validSinglePort(portValue: string | undefined, portName: string) {
        if (!portValue) {
            this.logger.error(`Invalid ${portName} : port value is empty`);
            this.errors.push(`Invalid ${portName} : port value is empty`);
        } else {
            this.validPort(portValue, portName);
        }
    }
    private validPort(rawPortValue: string, portName: string): number {
        const port = parseInt(rawPortValue);
        if (isNaN(port)) {
            this.logger.error(
                `Invalid ${portName} : port value [${rawPortValue}] is not a valid port value.`
            );
            this.errors.push(
                `Invalid ${portName} : port value [${rawPortValue}] is not a valid port value.`
            );
        } else if (port < 0 || port > MAX_PORT_NUMBER) {
            this.logger.error(
                `Invalid ${portName} : port value [${rawPortValue}] is not in range [0, ${MAX_PORT_NUMBER}].`
            );
            this.errors.push(
                `Invalid ${portName} : port value [${rawPortValue}] is not in range [0, ${MAX_PORT_NUMBER}].`
            );
        }
        return port;
    }
    private validPortRange(portValue: string | undefined, portName: string) {
        if (!portValue) {
            this.logger.error(`Invalid ${portName} : port value is empty`);
            this.errors.push(`Invalid ${portName} : port value is empty`);
        } else {
            const match = portValue.match(this.PORT_RANGE_REGX);
            if (match) {
                const from = this.validPort(match[1], portName);
                const to = this.validPort(match[2], portName);
                if (from > to) {
                    this.logger.error(
                        `Invalid ${portName} : port value ${portValue} contain from port greater than to port value.`
                    );
                    this.errors.push(
                        `Invalid ${portName} : port value ${portValue} contain from port greater than to port value.`
                    );
                }
            } else {
                this.logger.error(
                    `Invalid ${portName} : port value ${portValue} is not a valid port range value.`
                );
                this.errors.push(
                    `Invalid ${portName} : port value ${portValue} is not a valid port range value.`
                );
            }
        }
    }
 
    private async validSrcAndDst(input: FlowRuleInput) {
        if (!(input.source && input.destination)) {
            this.logger.info(`rule : source and/or destination is missing`);
            this.errors.push(`rule : source and/or destination is missing`);
        } else {
            const sourceObj = await this.targetsDataSourceService.getObjectBy(
                input.source
            );
            if (!sourceObj) {
                this.logger.info(`rule : source target ${input.source} does not exists.`);
                this.errors.push(`rule : source target ${input.source} does not exists.`);
            }
 
            const destinationObj = await this.targetsDataSourceService.getObjectBy(
                input.destination
            );
            if (!destinationObj) {
                this.logger.info(
                    `rule : destination target ${input.destination} does not exists.`
                );
                this.errors.push(
                    `rule : destination target ${input.destination} does not exists.`
                );
            }
        }
    }
 
    private validOptionFields(input: FlowRuleInput) {
        if (input.optionFields) {
            // check is valid pairs
            if (!_.isArray(input.optionFields)) {
                this.logger.info('rule : option is not a valid key value pair.');
                this.errors.push('rule : option is not a valid key value pair.');
            } else {
                // check is allowed field
                input.optionFields.forEach((kp) => {
                    if (!kp.key) {
                        this.logger.info(`rule : option key is missing in ${kp}.`);
                        this.errors.push(`rule : option key is missing in ${kp}.`);
                    }
                    // key is
                    if (KNOWN_UNSUPPORTED_OPTIONS.includes(kp.key)) {
                        this.logger.info(`rule : option key ${kp.key} is not supported.`);
                        this.errors.push(`rule : option key ${kp.key} is not supported.`);
                    }
 
                    if (RESERVED_OPTIONS.includes(kp.key)) {
                        this.logger.info(
                            `rule : option key ${kp.key} is reserved, can not be assigned.`
                        );
                        this.errors.push(
                            `rule : option key ${kp.key} is reserved, can not be assigned.`
                        );
                    }
                });
            }
        }
    }
}