/**
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 Rule = require('../');
const {
  SINK_TYPES,
  IMPORTANCE,
  CMD_INJECTION_SEMANTIC_TYPES
} = require('../../../constants');
const UserInputFactory = require('../../../reporter/models/utils/user-input-factory');
const ChainedCommandScanner = require('./chained-command-scanner');

class CMDInjectionSemanticChainedCommandsRule extends Rule {
  constructor(policy, agent) {
    super(policy, agent);
    this.id = 'cmd-injection-semantic-chained-commands';
    this.name = 'Command Injection Chained Commands';
    this.applicableSinks = [SINK_TYPES.COMMAND];
  }

  /**
   * By returning `false` this rule will bypass input classification stage.
   * @returns {Boolean}
   */
  appliesToInputType() {
    return false;
  }

  /**
   * Performs semantic analysis to determine if there are chained subcommands
   * @param {ApplicationContext} event Sink event
   * @param {Request} request Request model
   * @param {Samples} samples Samples cache
   */
  evaluateAtSink({ event, request, samples }) {
    const { data: command } = event;
    const scanner = new ChainedCommandScanner({ command });
    const index = scanner.findChaining();
    if (index != -1) {
      // create an UNKNOWN UserInput type
      // TODO attempt to map the command back to an input on the request
      // and use that as the input.  Recommended by spec, but no languages
      // implement
      const sample = this.createAndSaveSample({
        input: UserInputFactory.makeOne({ value: command }),
        attributes: { effective: true },
        classification: IMPORTANCE.DEFINITE,
        event,
        samples,
        request
      });

      this.appendAttackDetails(sample, {
        command,
        findings: [CMD_INJECTION_SEMANTIC_TYPES.CHAINING]
      });

      this.blockRequest(sample);
    }
  }

  /**
   * Performs semantic analysis to determine if there are chained subcommands
   * using agent-lib
   * @param {ApplicationContext} event Sink event
   * @param {Request} request Request model
   * @param {Samples} samples Samples cache
   */
  evaluateAtSinkForLib({ event, request, samples }) {
    const { data: command } = event;
    const index = this.agent.agentLib.indexOfChaining(command);
    if (index != -1) {
      const sample = this.createAndSaveSample({
        input: UserInputFactory.makeOne({ value: command }),
        attributes: { effective: true },
        classification: IMPORTANCE.DEFINITE,
        event,
        samples,
        request
      });

      this.appendAttackDetails(sample, {
        command,
        findings: [CMD_INJECTION_SEMANTIC_TYPES.CHAINING]
      });

      this.blockRequest(sample);
    }
  }

  /**
   * Builds the details for TS UI rendering.
   * @param   {Sample} sample   N/a in this rule's case
   * @param   {Object} sinkData
   * @param   {String} sinkData.command The command string
   * @param   {String[]} sinkData.findings Backdoor flag
   * @returns {Object}
   */
  buildDetails(sample, { command, findings }) {
    return { command, findings };
  }
}

module.exports = CMDInjectionSemanticChainedCommandsRule;
