/**
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.
*/
/**
 * @module lib/rules/protect/cmd-injection/CMDInjectionRule
 */

'use strict';

const Rule = require('../');
const { INPUT_TYPES, SINK_TYPES } = require('../common');
const logger = require('../../../core/logger')('contrast:rules:protect');

class CMDInjectionRule extends Rule {
  constructor(policy, agent) {
    super(policy, agent);

    this.id = 'cmd-injection';
    this.name = 'Command Injection';
    this.applicableInputs = [
      INPUT_TYPES.BODY,
      INPUT_TYPES.COOKIE_NAME,
      INPUT_TYPES.COOKIE_VALUE,
      INPUT_TYPES.HEADER,
      INPUT_TYPES.JSON_VALUE,
      INPUT_TYPES.JSON_ARRAYED_VALUE,
      INPUT_TYPES.PARAMETER_NAME,
      INPUT_TYPES.PARAMETER_VALUE,
      INPUT_TYPES.QUERYSTRING,
      INPUT_TYPES.XML_VALUE,
      INPUT_TYPES.URI,
      INPUT_TYPES.URL_PARAMETER
    ];
    this.applicableSinks = [SINK_TYPES.COMMAND];

    this.usesLibInputAnalysis = true;
  }

  /**
   * Calls down to the agent analysis library for evaluation with the
   * @param {Samples} applicableSamples Samples cache
   * @param {Set} params.applicableSamples samples applicable to rule id
   */
  evaluateAtSinkForLib({ event, applicableSamples }) {
    if (applicableSamples.size == 0 || !event.data) {
      return;
    }

    for (const sample of applicableSamples) {
      let evalResult = null;
      try {
        const input = sample.input.value;
        const sinkData = event.data;
        const inputIndex = sinkData.indexOf(input);

        if (inputIndex !== -1) {
          evalResult = this.agent.agentLib.checkCommandInjectionSink(
            inputIndex,
            input.length,
            sinkData,
          );
        }
      } catch (e) {
        logger.info(`Failed to evaluate command-injection sink: ${e}`);
      }

      if (evalResult) {
        this.appendAttackDetails(sample, evalResult);
        sample.captureAppContext(event);
        logger.warn(`EFFECTIVE - rule: ${this.id}, mode: ${this.mode}`);
        this.blockRequest(sample);
      }
    }
  }

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

  /**
   * Builds the details for TS UI rendering based on agent lib findings.
   * @param   {Sample} sample   relevant protect sample
   * @param   {Object} findings The results from the agent library
   * @returns {Object}
   */
  buildDetailsForLib(sample, findings) {
    return {
      command: sample.input.value.substring(
        findings.startIndex,
        findings.endIndex
      )
    };
  }
}

module.exports = CMDInjectionRule;
