/**
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 {
  SINK_TYPES,
  IMPORTANCE,
  CMD_INJECTION_SEMANTIC_TYPES
} = require('../../../constants');
const Rule = require('../');
const BackdoorDetector = require('./backdoor-detector');

class CMDInjectionCommandBackdoorsRule extends Rule {
  constructor(policy) {
    super(policy);
    this.id = 'cmd-injection-command-backdoors';
    this.name = 'Command Injection Command Backdoors';
    this.applicableSinks = [SINK_TYPES.COMMAND];
  }

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

  /**
   * Performs an input tracing search w/ semantic analysis. Input tracing is not
   * performed by looking at samples captured by input analysis; request fields
   * are checked directly.
   * @param {ApplicationContext} event Sink event
   * @param {Request} request Request model
   * @param {Samples} samples Samples cache
   */
  evaluateAtSink({ event, request, samples }) {
    const { data: command } = event;
    const backdoor = new BackdoorDetector({
      command,
      event,
      request: event.request || request
    });
    const input = backdoor.findInjection();

    if (input) {
      const sample = this.createAndSaveSample({
        input,
        attributes: { effective: true },
        classification: IMPORTANCE.DEFINITE,
        event,
        samples,
        request
      });

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

      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 = CMDInjectionCommandBackdoorsRule;
