All files / src/rules unsecure_fae.ts

96.47% Statements 219/227
85.45% Branches 94/110
100% Functions 12/12
96.47% Lines 219/227

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 2281x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21137x 21137x 21137x 21137x 21137x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 103482x 21137x 21137x 20227x 20227x 21137x 21137x 413x 413x 413x 21137x 21137x 374x 374x 21137x 21137x 623x 623x 208x 208x 415x 415x 623x 10x 10x 405x 623x 415x 415x 13x 13x 415x 2983x 37x 15x 15x 22x 22x 22x 22x 2983x 402x 405x 405x 405x 21137x 21137x 21137x 21137x 37x 37x 37x 37x     37x 37x     37x 37x 37x 173x 173x 173x 21x 21x 173x 173x 173x 173x 173x 24x 24x 24x 24x 11x 11x 24x 141x 141x 141x 141x 173x 173x 49x 132x 45x 45x 87x 132x 132x 132x 132x 4x 4x 132x 45x 173x 158x 158x 21137x 21137x 21137x 37x     37x 37x 37x 37x 37x 37x 2x 2x 37x 37x 21137x 21137x 21137x 87x 81x 81x 81x 6x 6x 87x     87x 87x 1x 1x 87x 87x 87x 21137x 21137x 21137x 21137x 23x 23x 23x 23x 379x 364x 364x 379x 8x 8x 379x 15x 15x 21137x 21137x 15x 15x 9x 9x 7x 7x 9x 8x 8x 21137x 21137x 1x 1x 1x 1x 1x 21137x 21137x  
import * as Expressions from "../abap/2_statements/expressions";
import * as Statements from "../abap/2_statements/statements";
import * as Structures from "../abap/3_structures/structures";
import {Issue} from "../issue";
import {BasicRuleConfig} from "./_basic_rule_config";
import {IRegistry} from "../_iregistry";
import {IRule, IRuleMetadata, RuleTag} from "./_irule";
import {IObject} from "../objects/_iobject";
import {ABAPObject} from "../objects/_abap_object";
import {SyntaxLogic} from "../abap/5_syntax/syntax";
import {ExpressionNode, StatementNode, StructureNode} from "../abap/nodes";
import {ABAPFile} from "../abap/abap_file";
import {ISpaghettiScope} from "../abap/5_syntax/_spaghetti_scope";
import {ScopeType} from "../abap/5_syntax/_scope_type";
import {Position} from "../position";
import {condImpliesNotInitial, negationImpliesNotInitial} from "./_initial_condition";
import {structurePath} from "./_structure_path";
import {isLoopStructure} from "../abap/5_syntax/_loop_structures";
 
export class UnsecureFAEConf extends BasicRuleConfig {
}
 
const PROCEDURES = [Structures.Method, Structures.Form, Structures.FunctionModule];
const CALLS = [Statements.Call, Statements.CallFunction, Statements.Perform, Statements.Submit,
  Statements.RaiseEvent, Statements.CallTransaction];
 
export class UnsecureFAE implements IRule {
  private reg: IRegistry;
  private conf = new UnsecureFAEConf();
 
  public getMetadata(): IRuleMetadata {
    return {
      key: "unsecure_fae",
      title: "Unsecure FAE",
      shortDescription: `Checks for unsecure FAE`,
      extendedInformation: `Issues from rule check_syntax must be fixed before this rule takes effect
 
The driver table of FOR ALL ENTRIES is considered checked, and no issue is reported, if
* the SELECT is in the IF or ELSEIF branch of a condition "itab IS NOT INITIAL", "NOT itab IS INITIAL"
  or "lines( itab ) > 0", also combined with AND, or
* "IF itab IS INITIAL. RETURN. ENDIF." or "CHECK itab IS NOT INITIAL." precedes the SELECT in the same method,
  form or function module, at the same or an outer block level, not inside a loop,
 
and the driver table is not changed between the check and the SELECT, or in a loop around the SELECT inside the
checked region. If the driver table is not a local variable or parameter, a method, function or form call in
between also invalidates the check.`,
      tags: [RuleTag.Experimental, RuleTag.Performance],
      badExample: `SELECT * FROM t000 FOR ALL ENTRIES IN @lt_list
  WHERE mandt = @lt_list-table_line INTO TABLE @DATA(lt_t000).`,
      goodExample: `IF lt_list IS NOT INITIAL.
  SELECT * FROM t000 FOR ALL ENTRIES IN @lt_list
    WHERE mandt = @lt_list-table_line INTO TABLE @DATA(lt_t000).
ENDIF.`,
    };
  }
 
  public getConfig() {
    return this.conf;
  }
 
  public initialize(reg: IRegistry) {
    this.reg = reg;
    return this;
  }
 
  public setConfig(conf: UnsecureFAEConf) {
    this.conf = conf;
  }
 
  public run(obj: IObject): Issue[] {
    const issues: Issue[] = [];
    if (!(obj instanceof ABAPObject)) {
      return issues;
    }
 
    const syntaxResult = new SyntaxLogic(this.reg, obj).run();
    if (syntaxResult.issues.length > 0) {
      return issues;
    }
 
    for (const f of obj.getABAPFiles()) {
      const structure = f.getStructure();
      if (structure === undefined) {
        continue;
      }
      for (const statement of structure.findAllStatementNodes()) {
        for (const e of statement.findAllExpressions(Expressions.SQLForAllEntries)) {
          if (this.isChecked(f, structure, statement, e, syntaxResult.spaghetti)) {
            continue;
          }
          const token = e.getFirstToken();
          const message = "Unsecure FAE";
          issues.push(Issue.atToken(f, token, message, this.getMetadata().key, this.getConfig().severity));
        }
      }
    }
 
    return issues;
  }
 
////////////////
 
  private isChecked(file: ABAPFile, root: StructureNode, statement: StatementNode, fae: ExpressionNode,
                    spaghetti: ISpaghettiScope): boolean {
    const source = fae.findDirectExpression(Expressions.SQLSource);
    const name = source?.concatTokens().replace(/^@/, "").replace(/\s/g, "").toUpperCase();
    if (name === undefined || /^[\w/<>~]+((->|=>)[\w/~]+)?$/.test(name) === false) {
      return false;
    }
    const path = structurePath(root, statement);
    if (path === undefined) {
      return false;
    }
    const local = this.isLocal(file, name, statement.getStart(), spaghetti);
 
    for (let i = path.length - 1; i >= 0; i--) {
      const node = path[i];
      const type = node.get();
      if (PROCEDURES.some(p => type instanceof p)) {
        break;
      }
      const child = path[i + 1] ?? statement;
      const inner = path.slice(i + 1);
 
      // IF itab IS NOT INITIAL. SELECT ... ENDIF.
      if ((type instanceof Structures.If || type instanceof Structures.ElseIf) && child.get() instanceof Structures.Body) {
        const header = node.findDirectStatement(type instanceof Structures.If ? Statements.If : Statements.ElseIf);
        const cond = header?.findDirectExpression(Expressions.Cond);
        if (header && cond && condImpliesNotInitial(cond, name)
            && this.unchanged(file, inner, statement, header.getEnd(), name, local)) {
          return true;
        }
      }
 
      // IF itab IS INITIAL. RETURN. ENDIF. or CHECK itab IS NOT INITIAL. before the SELECT
      const outer = path.slice(0, i + 1);
      if (type instanceof Structures.Body
          && outer.some(n => PROCEDURES.some(p => n.get() instanceof p))
          && outer.some(n => isLoopStructure(n.get())) === false) {
        for (const sibling of node.getChildren()) {
          if (sibling === child) {
            break;
          }
          const content = sibling instanceof StructureNode && sibling.get() instanceof Structures.Normal
            ? sibling.getFirstChild() : sibling;
          if ((content instanceof StructureNode || content instanceof StatementNode)
              && this.leavesIfInitial(content, name)
              && this.unchanged(file, inner, statement, sibling.getLastToken().getEnd(), name, local)) {
            return true;
          }
        }
      }
    }
    return false;
  }
 
  /** local variable or parameter of the procedure, calls cannot change it */
  private isLocal(file: ABAPFile, name: string, position: Position, spaghetti: ISpaghettiScope): boolean {
    if (name.includes("->") || name.includes("=>") || name.startsWith("<")) {
      return false;
    }
    let scope = spaghetti.lookupPosition(position, file.getFilename());
    while (scope?.getIdentifier().stype === ScopeType.OpenSQL) {
      scope = scope.getParent();
    }
    const stype = scope?.getIdentifier().stype;
    if (stype !== ScopeType.Method && stype !== ScopeType.Form && stype !== ScopeType.FunctionModule) {
      return false;
    }
    return scope?.getData().vars[name] !== undefined;
  }
 
  /** "IF itab IS INITIAL. RETURN. ENDIF." or "CHECK itab IS NOT INITIAL." */
  private leavesIfInitial(node: StructureNode | StatementNode, name: string): boolean {
    if (node instanceof StatementNode) {
      const cond = node.get() instanceof Statements.Check ? node.findDirectExpression(Expressions.Cond) : undefined;
      return cond !== undefined && condImpliesNotInitial(cond, name);
    }
    if (!(node.get() instanceof Structures.If)
        || node.findDirectStructure(Structures.Else) !== undefined
        || node.findDirectStructure(Structures.ElseIf) !== undefined) {
      return false;
    }
    const statements = node.findDirectStructure(Structures.Body)?.findAllStatementNodes() ?? [];
    if (statements.length !== 1 || !(statements[0].get() instanceof Statements.Return)) {
      return false;
    }
    const cond = node.findDirectStatement(Statements.If)?.findDirectExpression(Expressions.Cond);
    return cond !== undefined && negationImpliesNotInitial(cond, name);
  }
 
  /** the driver table is not changed after the check and before the SELECT, nor in a loop around the SELECT
   * inside the checked region */
  private unchanged(file: ABAPFile, inner: StructureNode[], statement: StatementNode, from: Position,
                    name: string, local: boolean): boolean {
    const loop = inner.find(n => isLoopStructure(n.get()));
    const to = loop === undefined ? statement.getStart() : loop.getLastToken().getEnd();
    for (const s of file.getStatements()) {
      if (s === statement || !s.getStart().isAfter(from) || !s.getStart().isBefore(to)) {
        continue;
      }
      if (this.writes(s, name) || (local === false && this.calls(s))) {
        return false;
      }
    }
    return true;
  }
 
  private writes(statement: StatementNode, name: string): boolean {
    for (const target of [...statement.findAllExpressions(Expressions.Target),
      ...statement.findAllExpressions(Expressions.FSTarget)]) {
      const text = target.concatTokens().replace(/\s/g, "").toUpperCase();
      if (text === name || (text.startsWith(name) && /^[^\w/]/.test(text.substring(name.length)))) {
        return true;
      }
    }
    return false;
  }
 
  private calls(statement: StatementNode): boolean {
    const type = statement.get();
    return CALLS.some(c => type instanceof c)
      || statement.findFirstExpression(Expressions.MethodCall) !== undefined
      || statement.findFirstExpression(Expressions.MethodSource) !== undefined;
  }
 
}