/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';
const { INPUT_TYPES } = require('../common');
const SINK_EXPLOIT_PATTERN_START = /(?:^|\\|\/)(?:sh|bash|zsh|ksh|tcsh|csh|fish|cmd)/;
const stripWhiteSpace = (str) => str.replace(/\s/g, '');
const REQUEST_KEYS = {
  queryParams: INPUT_TYPES.QUERYSTRING,
  body: INPUT_TYPES.BODY,
  parameters: INPUT_TYPES.PARAMETER_VALUE,
  headers: INPUT_TYPES.HEADER,
  cookies: INPUT_TYPES.COOKIE_VALUE
};
const UserInput = require('../../../reporter/models/app-activity/user-input');
const { isString } = require('../../../util/is-string');
const { traverse } = require('../../../util/traverse');

module.exports = class BackdoorDetector {
  constructor({ command, request, event }) {
    this.command = command;
    this.request = request;
    this.normalizedCmd = stripWhiteSpace(command);
    this.event = event;
  }

  /**
   * Backdoor detection logic:
   *  - command is >= 2 chars
   *  - iterates over every piece of request and checks
   *    - the full value is the param to sink
   *    - the value matches a regex and ends the param to the sink
   *
   */
  findInjection() {
    if (this.command && this.command.length < 2) {
      return null;
    }

    let found = false;
    for (const part in REQUEST_KEYS) {
      const values = this.request[part];
      if (values) {
        let docPath = [];
        traverse(values, (key, value, depth) => {
          if (depth === 1) {
            docPath = [key];
          } else if (depth > 1) {
            docPath.push(key);
          }

          if (
            !found &&
            value &&
            isString(value) &&
            this.isBackdoorDetected(value)
          ) {
            const type =
              docPath.length > 1 ? INPUT_TYPES.JSON_VALUE : REQUEST_KEYS[part];
            const path = docPath.join('.');

            found = new UserInput({
              path,
              name: path,
              value: this.command,
              type
            });
          }
        });
      }
    }

    return found;
  }

  /**
   * strips the whitespace of the request value
   * checks if the param equals the request value
   * or if the command looks like the start of a shell execution
   * and ends the command passed to sink
   *
   * @param {string} value from request key
   */
  isBackdoorDetected(requestValue) {
    const normalizedParam = stripWhiteSpace(requestValue);
    return (
      normalizedParam === this.normalizedCmd ||
      (this.normalizedCmd.endsWith(normalizedParam) &&
        SINK_EXPLOIT_PATTERN_START.test(this.normalizedCmd))
    );
  }
};
