/**
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 common = require('../../../common');
const Builder = require('../../../attack-patterns');
const { CustomSearcher } = require('../../signature');

const { SCORES } = common;

const COMPARISON_OPERATORS = ['<', '>', '!=', '>=', '<=', '=', '<>'];
const MAX_ALLOWED_OR_CONDITION_DISTANCE = 10;

const operatorsPatternText = COMPARISON_OPERATORS.map(
  (chars) => `(${chars})`
).join('|');

const commentSearch = Builder()
  .SQL()
  .commentStart()
  .build();

// Looks for numbers with infix operator, like ' 1 < 2 '
const numericSearch = Builder()
  .literally('^', true)
  .whitespaces()
  .oneOrMoreOf()
  .alphanumeric()
  .whitespaces()
  .literally(`(${operatorsPatternText})`, true)
  .whitespaces()
  .oneOrMoreOf()
  .alphanumeric()
  .build();

// Looks for quoted strings with infix operators, like ' "a" != "b" '
const quotesSearch = Builder()
  .literally('^', true)
  .whitespaces()
  .quote()
  .oneOrMoreOf()
  .alphanumeric()
  .quote()
  .whitespaces()
  .literally(`(${operatorsPatternText})`, true)
  .whitespaces()
  .quote()
  .oneOrMoreOf()
  .alphanumeric()
  .quote()
  .build();

// Checks the index from the end of the or-search and
// makes sure it's within reasonable limits.
const matchIndexInLimit = function(matchIndex) {
  return matchIndex < MAX_ALLOWED_OR_CONDITION_DISTANCE;
};

// Does the string have any comments?
const hasComments = function(string) {
  return commentSearch.test(string);
};

/**
 * Searches text for SQL truing string injections using "or" operator.
 */
class SimpleOrSearcher extends CustomSearcher {
  constructor() {
    super({
      description: 'Searches for truing string injections using OR',
      id: 'TRUING_STRING_INJ',
      name: 'SimpleOrSearcher'
    });
  }

  getImpact(userInput) {
    let found = false;

    // Looks for instances of "or".
    // Instantiate here because of RegExp state with `exec()`.
    const orRegex = Builder({ flags: 'gim' })
      .whitespacesRequired()
      .literally('or')
      .whitespacesRequired()
      .build();

    while (orRegex.exec(userInput.value)) {
      const afterOrSegment = userInput.value.substring(orRegex.lastIndex);
      const quotedStringIndex = afterOrSegment.search(quotesSearch);

      if (0 <= quotedStringIndex) {
        matchIndexInLimit(quotedStringIndex) && (found = true);
        if (hasComments(afterOrSegment)) {
          return SCORES.CRITICAL;
        }
      }

      const numericIndex = afterOrSegment.search(numericSearch);
      if (0 <= numericIndex) {
        matchIndexInLimit(numericIndex) && (found = true);
        if (hasComments(afterOrSegment)) {
          return SCORES.CRITICAL;
        }
      }
    }

    // If we found matches, just not with comments, we still score.
    return found ? SCORES.HIGH : SCORES.NONE;
  }
}

module.exports = new SimpleOrSearcher();
