|
| 1 | +/** |
| 2 | + * Provides Ruby-specific imports and classes needed for `TaintedFormatStringQuery` and `TaintedFormatStringCustomizations`. |
| 3 | + */ |
| 4 | + |
| 5 | +import ruby |
| 6 | +import codeql.ruby.DataFlow |
| 7 | +import codeql.ruby.dataflow.RemoteFlowSources |
| 8 | +import codeql.ruby.ApiGraphs |
| 9 | +import codeql.ruby.TaintTracking |
| 10 | +private import codeql.ruby.frameworks.Files::IO |
| 11 | +private import codeql.ruby.controlflow.CfgNodes |
| 12 | + |
| 13 | +/** |
| 14 | + * A call to `printf` or `sprintf`. |
| 15 | + */ |
| 16 | +abstract class PrintfStyleCall extends DataFlow::CallNode { |
| 17 | + // We assume that most printf-like calls have the signature f(format_string, args...) |
| 18 | + /** |
| 19 | + * Gets the format string of this call. |
| 20 | + */ |
| 21 | + DataFlow::Node getFormatString() { result = this.getArgument(0) } |
| 22 | + |
| 23 | + /** |
| 24 | + * Gets then `n`th formatted argument of this call. |
| 25 | + */ |
| 26 | + DataFlow::Node getFormatArgument(int n) { n >= 0 and result = this.getArgument(n + 1) } |
| 27 | +} |
| 28 | + |
| 29 | +/** |
| 30 | + * A call to `Kernel.printf`. |
| 31 | + */ |
| 32 | +class KernelPrintfCall extends PrintfStyleCall { |
| 33 | + KernelPrintfCall() { |
| 34 | + this = API::getTopLevelMember("Kernel").getAMethodCall("printf") |
| 35 | + or |
| 36 | + this.asExpr().getExpr() instanceof UnknownMethodCall and |
| 37 | + this.getMethodName() = "printf" |
| 38 | + } |
| 39 | + |
| 40 | + // Kernel#printf supports two signatures: |
| 41 | + // printf(io, string, ...) |
| 42 | + // printf(string, ...) |
| 43 | + override DataFlow::Node getFormatString() { |
| 44 | + // Because `printf` has two different signatures, we can't be sure which |
| 45 | + // argument is the format string, so we use a heuristic: |
| 46 | + // If the first argument has a string value, then we assume it is the format string. |
| 47 | + // Otherwise we treat both the first and second args as the format string. |
| 48 | + if this.getArgument(0).getExprNode().getConstantValue().isString(_) |
| 49 | + then result = this.getArgument(0) |
| 50 | + else result = this.getArgument([0, 1]) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * A call to `Kernel.sprintf`. |
| 56 | + */ |
| 57 | +class KernelSprintfCall extends PrintfStyleCall { |
| 58 | + KernelSprintfCall() { |
| 59 | + this = API::getTopLevelMember("Kernel").getAMethodCall("sprintf") |
| 60 | + or |
| 61 | + this.asExpr().getExpr() instanceof UnknownMethodCall and |
| 62 | + this.getMethodName() = "sprintf" |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * A call to `IO#printf`. |
| 68 | + */ |
| 69 | +class IOPrintfCall extends PrintfStyleCall { |
| 70 | + IOPrintfCall() { this.getReceiver() instanceof IOInstance and this.getMethodName() = "printf" } |
| 71 | +} |
0 commit comments