ai-secure-audit 0.0.14 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +1 -1
- package/rules/express-route-no-rate-limit.yml +2 -0
- package/rules/express-session-lookup-plain-object.yml +2 -0
- package/rules/express-vote-route-no-identity.yml +2 -0
- package/rules/js-code-from-text.js +136 -0
- package/rules/js-code-from-text.yml +81 -0
- package/rules/js-html-from-user-text.js +206 -0
- package/rules/js-html-from-user-text.yml +143 -0
- package/rules/nestjs-route-no-throttle.yml +2 -0
- package/rules/sql-built-from-parameter.js +115 -0
- package/rules/sql-built-from-parameter.yml +81 -0
- package/rules/sql-built-from-request.ts +196 -0
- package/rules/sql-built-from-request.yml +103 -0
- package/src/cli.js +6 -2
- package/src/coverage.js +100 -5
- package/src/findings.js +1 -1
- package/src/live/ports.js +136 -0
- package/src/live.js +30 -7
- package/src/report-simple.js +1 -0
- package/src/report.js +2 -1
- package/src/scan.js +4 -1
- package/src/scanners/opengrep.js +44 -1
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Test cases for sql-built-from-parameter. Run: opengrep scan --test --taint-intrafile rules/
|
|
2
|
+
// Written before the rule. A db helper in its own file builds SQL from what its caller passed in: the route that
|
|
3
|
+
// calls it (with req.body) is in another file, so sql-built-from-request cannot see the request.
|
|
4
|
+
const pool = require('./pool');
|
|
5
|
+
const db = require('./db');
|
|
6
|
+
|
|
7
|
+
// --- SQL text built from a parameter ---
|
|
8
|
+
|
|
9
|
+
function login(username, password) {
|
|
10
|
+
const q = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
|
|
11
|
+
// ruleid: sql-built-from-parameter
|
|
12
|
+
return pool.query(q);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function search(term) {
|
|
16
|
+
// ruleid: sql-built-from-parameter
|
|
17
|
+
return pool.query(`SELECT * FROM products WHERE name ILIKE '%${term}%'`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const ordersFor = (userId, sort) =>
|
|
21
|
+
// ruleid: sql-built-from-parameter
|
|
22
|
+
pool.query(`SELECT * FROM orders WHERE user_id = $1 ORDER BY ${sort} DESC`, [userId]);
|
|
23
|
+
|
|
24
|
+
class UserRepo {
|
|
25
|
+
constructor(conn) { this.conn = conn; }
|
|
26
|
+
byEmail(email) {
|
|
27
|
+
// ruleid: sql-built-from-parameter
|
|
28
|
+
return this.conn.query(`SELECT * FROM users WHERE email = '${email}'`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
module.exports.update = function (id, fields) {
|
|
33
|
+
const sets = Object.keys(fields).map((k) => `${k} = '${fields[k]}'`);
|
|
34
|
+
// ruleid: sql-built-from-parameter
|
|
35
|
+
return db.query(`UPDATE users SET ${sets.join(', ')} WHERE id = ${id}`);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
async function remove(prisma, id) {
|
|
39
|
+
// ruleid: sql-built-from-parameter
|
|
40
|
+
return prisma.$executeRawUnsafe(`DELETE FROM "Post" WHERE id = ${id}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// --- Safe: placeholders, numbers, escaped names ---
|
|
44
|
+
|
|
45
|
+
function byId(id) {
|
|
46
|
+
// ok: sql-built-from-parameter
|
|
47
|
+
return pool.query('SELECT * FROM users WHERE id = $1', [id]);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function page(limit, offset) {
|
|
51
|
+
// ok: sql-built-from-parameter
|
|
52
|
+
return pool.query(`SELECT * FROM t LIMIT ${Number(limit)} OFFSET ${parseInt(offset, 10)}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function exportTable(client, table) {
|
|
56
|
+
// ok: sql-built-from-parameter
|
|
57
|
+
return client.query(`SELECT * FROM ${quoteIdent(table)}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function inList(ids) {
|
|
61
|
+
const marks = ids.map(() => '?').join(',');
|
|
62
|
+
// ok: sql-built-from-parameter
|
|
63
|
+
return db.all(`SELECT * FROM t WHERE id IN (${marks})`, ids);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function savepoint(tx) {
|
|
67
|
+
const name = 'sp_1';
|
|
68
|
+
// ok: sql-built-from-parameter
|
|
69
|
+
return tx.query(`SAVEPOINT ${name}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// --- Request objects are sql-built-from-request's job: not reported here ---
|
|
73
|
+
|
|
74
|
+
function handler(req, res) {
|
|
75
|
+
// ok: sql-built-from-parameter
|
|
76
|
+
return pool.query(`SELECT * FROM t WHERE id = ${req.query.id}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// --- Not SQL ---
|
|
80
|
+
|
|
81
|
+
function greet(name) {
|
|
82
|
+
// ok: sql-built-from-parameter
|
|
83
|
+
return console.log(`hello ${name}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function cached(cache, key) {
|
|
87
|
+
// ok: sql-built-from-parameter
|
|
88
|
+
return cache.get(`user = '${key}'`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// A fragment joined with +: fixed text the caller wrote, like WHERE ${where}.
|
|
92
|
+
function filtered(db, frag) {
|
|
93
|
+
// ok: sql-built-from-parameter
|
|
94
|
+
return db.query('SELECT * FROM t WHERE ' + frag);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// --- Seen as false findings on two apps: the SQL is not built from a value here ---
|
|
98
|
+
|
|
99
|
+
// A wrapper that takes the whole SQL text and its values: the caller decides, and placeholders are the norm.
|
|
100
|
+
function shopQuery(client, text, params) {
|
|
101
|
+
// ok: sql-built-from-parameter
|
|
102
|
+
return client.query(text, params);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A fragment of SQL the code put together (the caller passes fixed text such as "status = 'open'").
|
|
106
|
+
function userWhere(client, where, params) {
|
|
107
|
+
// ok: sql-built-from-parameter
|
|
108
|
+
return client.query(`SELECT * FROM users WHERE ${where} LIMIT 1`, params);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// An HTTP client is not a database.
|
|
112
|
+
function download(client, url, options) {
|
|
113
|
+
// ok: sql-built-from-parameter
|
|
114
|
+
return client.get(url, options);
|
|
115
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
rules:
|
|
2
|
+
- id: sql-built-from-parameter
|
|
3
|
+
languages: [javascript, typescript]
|
|
4
|
+
severity: WARNING
|
|
5
|
+
message: >-
|
|
6
|
+
SQL text is built from a value this function was given (a parameter), not sent apart from it. If any caller
|
|
7
|
+
passes something a person typed (a form field, a URL, a header), for example a route in another file that calls
|
|
8
|
+
this helper with req.body, that person can change the query: read every row, log in as anyone, or delete data.
|
|
9
|
+
Find where this function is called and where the value comes from; whatever you find, send the value with a
|
|
10
|
+
placeholder (db.query('... WHERE email = $1', [email]), '?' with mysql2 or sqlite, Sequelize replacements, or
|
|
11
|
+
the tagged prisma.$queryRaw), and pick names that cannot be placeholders (a column to sort by) from a fixed list.
|
|
12
|
+
metadata:
|
|
13
|
+
category: code
|
|
14
|
+
# Shown in the report's list of what the code rules look for.
|
|
15
|
+
summary: 'SQL text built from a function parameter, for db helpers called from another file (same calls as above)'
|
|
16
|
+
cwe: "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"
|
|
17
|
+
asvs: 'OWASP ASVS 5.0 V1.2.4 (parameterized queries)'
|
|
18
|
+
confidence: MEDIUM
|
|
19
|
+
# When sql-built-from-request reports the same line, that finding (high, the request is visible) is enough.
|
|
20
|
+
suppressed-on-same-line-by: sql-built-from-request
|
|
21
|
+
limitations: >-
|
|
22
|
+
Does not know what callers pass: a parameter that only ever holds a value from the code itself (a tenant id
|
|
23
|
+
from a signed token, a value checked against a fixed list) is reported too, so read the callers before
|
|
24
|
+
changing anything. Only a parameter used as a value is matched (in quotes, or after =, <, >, IN (, ORDER BY,
|
|
25
|
+
LIMIT, OFFSET); a parameter that is a whole SQL fragment or a property of an object parameter (fields[k]) is
|
|
26
|
+
missed.
|
|
27
|
+
mode: taint
|
|
28
|
+
pattern-sources:
|
|
29
|
+
# A parameter put into SQL text where it is a value: inside quotes ('${email}', "= '" + name), or right after
|
|
30
|
+
# =, <, >, IN (, ORDER BY, LIMIT or OFFSET. A parameter that is a whole fragment (WHERE ${where}) or the whole
|
|
31
|
+
# SQL text (query(text, params)) is left out: in real code those are fixed text the caller wrote.
|
|
32
|
+
- patterns:
|
|
33
|
+
- pattern-either:
|
|
34
|
+
- patterns:
|
|
35
|
+
- pattern: "`...${$X}...`"
|
|
36
|
+
- pattern-regex: (?i)(['%]|(=|<>|!=|<|>|\bin\s*\(|\border\s+by|\blimit|\boffset)\s*)\$\{\s*[\w$.\[\]'"]+\s*\}
|
|
37
|
+
- patterns:
|
|
38
|
+
- pattern: '"$S" + $X'
|
|
39
|
+
- metavariable-regex:
|
|
40
|
+
metavariable: $S
|
|
41
|
+
regex: (?is).*(['%]|(=|<>|!=|<|>|\bin\s*\(|\border\s+by|\blimit|\boffset)\s*)$
|
|
42
|
+
# $X is a parameter of the function around it. req.body.x is a property, not a parameter: request values are
|
|
43
|
+
# sql-built-from-request's.
|
|
44
|
+
- pattern-either:
|
|
45
|
+
- pattern-inside: |
|
|
46
|
+
function $F(..., $X, ...) { ... }
|
|
47
|
+
- pattern-inside: |
|
|
48
|
+
function (..., $X, ...) { ... }
|
|
49
|
+
# No sanitizers: a source is a parameter written straight into the SQL text, so Number(x), escape(x) or a
|
|
50
|
+
# placeholder list are not sources in the first place.
|
|
51
|
+
pattern-sinks:
|
|
52
|
+
# The first argument is the SQL text. Values passed in later arguments are safe.
|
|
53
|
+
- patterns:
|
|
54
|
+
- pattern-either:
|
|
55
|
+
- pattern: $DB.query($SQL, ...)
|
|
56
|
+
- pattern: $DB.execute($SQL, ...)
|
|
57
|
+
- pattern: $DB.raw($SQL, ...)
|
|
58
|
+
# Only receivers named like a database handle, so other objects' query() are not matched.
|
|
59
|
+
- metavariable-regex:
|
|
60
|
+
metavariable: $DB
|
|
61
|
+
regex: (?i)(.*\.)?(\w*db|database|sqlite\w*|conn|connection|pool|client|knex|sequelize|sql|tx|trx|manager|entitymanager|datasource|queryrunner|\w*repo(sitory)?)$
|
|
62
|
+
- focus-metavariable: $SQL
|
|
63
|
+
# get, all, run, exec and prepare are common names (an HTTP client's get, Map.get, RegExp.exec): only on a
|
|
64
|
+
# receiver named like a SQLite handle or statement.
|
|
65
|
+
- patterns:
|
|
66
|
+
- pattern-either:
|
|
67
|
+
- pattern: $DB.all($SQL, ...)
|
|
68
|
+
- pattern: $DB.get($SQL, ...)
|
|
69
|
+
- pattern: $DB.run($SQL, ...)
|
|
70
|
+
- pattern: $DB.exec($SQL, ...)
|
|
71
|
+
- pattern: $DB.prepare($SQL, ...)
|
|
72
|
+
- metavariable-regex:
|
|
73
|
+
metavariable: $DB
|
|
74
|
+
regex: (?i)(.*\.)?(\w*db|database|sqlite\w*|stmt|statement)$
|
|
75
|
+
- focus-metavariable: $SQL
|
|
76
|
+
- patterns:
|
|
77
|
+
- pattern-either:
|
|
78
|
+
- pattern: $P.$queryRawUnsafe($SQL, ...)
|
|
79
|
+
- pattern: $P.$executeRawUnsafe($SQL, ...)
|
|
80
|
+
- pattern: Prisma.raw($SQL)
|
|
81
|
+
- focus-metavariable: $SQL
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// Test cases for sql-built-from-request. Run: opengrep scan --test --taint-intrafile rules/
|
|
2
|
+
// Written before the rule. Each case is a shape seen in AI-written code or in public examples of SQL injection.
|
|
3
|
+
import express from 'express';
|
|
4
|
+
import { Controller, Get, Post, Body, Query, Param } from '@nestjs/common';
|
|
5
|
+
import { NextRequest } from 'next/server';
|
|
6
|
+
import { Prisma, PrismaClient } from '@prisma/client';
|
|
7
|
+
|
|
8
|
+
const app = express();
|
|
9
|
+
const prisma = new PrismaClient();
|
|
10
|
+
declare const db: any, pool: any, sequelize: any, models: any, knex: any, connection: any, sql: any;
|
|
11
|
+
|
|
12
|
+
// --- Express: value from the request put into the SQL text ---
|
|
13
|
+
|
|
14
|
+
app.post('/login', async (req, res) => {
|
|
15
|
+
// ruleid: sql-built-from-request
|
|
16
|
+
const user = await models.sequelize.query(`SELECT * FROM Users WHERE email = '${req.body.email}' AND password = '${req.body.password}'`);
|
|
17
|
+
res.json(user);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
app.get('/search', async (req, res) => {
|
|
21
|
+
const criteria = req.query.q;
|
|
22
|
+
// ruleid: sql-built-from-request
|
|
23
|
+
const rows = await sequelize.query(`SELECT * FROM Products WHERE name LIKE '%${criteria}%'`);
|
|
24
|
+
res.json(rows);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
app.get('/users/:id', async (req, res) => {
|
|
28
|
+
// ruleid: sql-built-from-request
|
|
29
|
+
const r = await pool.query('SELECT * FROM users WHERE id = ' + req.params.id);
|
|
30
|
+
res.json(r.rows);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
app.get('/orders', async (req, res) => {
|
|
34
|
+
const { sort } = req.query;
|
|
35
|
+
const text = `SELECT * FROM orders ORDER BY ${sort}`;
|
|
36
|
+
// ruleid: sql-built-from-request
|
|
37
|
+
const r = await db.query(text);
|
|
38
|
+
res.json(r);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
app.get('/sqlite', (req, res) => {
|
|
42
|
+
// ruleid: sql-built-from-request
|
|
43
|
+
db.all(`SELECT * FROM notes WHERE owner = '${req.cookies.user}'`, (err: any, rows: any) => res.json(rows));
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
app.post('/mysql', async (req, res) => {
|
|
47
|
+
// ruleid: sql-built-from-request
|
|
48
|
+
const [rows] = await connection.execute("SELECT * FROM t WHERE name = '" + req.body.name + "'");
|
|
49
|
+
res.json(rows);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
app.get('/knex', async (req, res) => {
|
|
53
|
+
// ruleid: sql-built-from-request
|
|
54
|
+
res.json(await knex.raw(`SELECT * FROM t WHERE id = ${req.query.id}`));
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
app.get('/header', async (req, res) => {
|
|
58
|
+
// ruleid: sql-built-from-request
|
|
59
|
+
res.json(await db.query(`SELECT * FROM t WHERE tenant = '${req.get('x-tenant')}'`));
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// --- Prisma: the Unsafe raw functions and Prisma.raw take plain strings ---
|
|
63
|
+
|
|
64
|
+
app.get('/prisma', async (req, res) => {
|
|
65
|
+
// ruleid: sql-built-from-request
|
|
66
|
+
res.json(await prisma.$queryRawUnsafe(`SELECT * FROM "User" WHERE email = '${req.query.email}'`));
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
app.post('/prisma-exec', async (req, res) => {
|
|
70
|
+
// ruleid: sql-built-from-request
|
|
71
|
+
await prisma.$executeRawUnsafe('DELETE FROM "Post" WHERE id = ' + req.body.id);
|
|
72
|
+
res.end();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
app.get('/prisma-raw', async (req, res) => {
|
|
76
|
+
// ruleid: sql-built-from-request
|
|
77
|
+
res.json(await prisma.$queryRaw`SELECT * FROM t ORDER BY ${Prisma.raw(req.query.sort as string)}`);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// --- A helper in the same file that builds the SQL ---
|
|
81
|
+
|
|
82
|
+
async function findByName(name: string) {
|
|
83
|
+
// ruleid: sql-built-from-request
|
|
84
|
+
return db.query(`SELECT * FROM t WHERE name = '${name}'`);
|
|
85
|
+
}
|
|
86
|
+
app.get('/by-name', async (req, res) => res.json(await findByName(req.query.name as string)));
|
|
87
|
+
|
|
88
|
+
// --- NestJS: decorated parameters are request values ---
|
|
89
|
+
|
|
90
|
+
@Controller('items')
|
|
91
|
+
export class ItemsController {
|
|
92
|
+
constructor(private readonly dataSource: any) {}
|
|
93
|
+
|
|
94
|
+
@Get()
|
|
95
|
+
find(@Query('q') q: string) {
|
|
96
|
+
// ruleid: sql-built-from-request
|
|
97
|
+
return this.dataSource.query(`SELECT * FROM items WHERE title LIKE '%${q}%'`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
@Post()
|
|
101
|
+
create(@Body() body: any) {
|
|
102
|
+
// ruleid: sql-built-from-request
|
|
103
|
+
return this.dataSource.query("INSERT INTO items (title) VALUES ('" + body.title + "')");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
@Get(':id')
|
|
107
|
+
one(@Param('id') id: string) {
|
|
108
|
+
// ok: sql-built-from-request
|
|
109
|
+
return this.dataSource.query('SELECT * FROM items WHERE id = $1', [id]);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// --- Next.js route handler ---
|
|
114
|
+
|
|
115
|
+
export async function POST(request: NextRequest) {
|
|
116
|
+
const { email } = await request.json();
|
|
117
|
+
// ruleid: sql-built-from-request
|
|
118
|
+
const rows = await sql.query(`SELECT * FROM users WHERE email = '${email}'`);
|
|
119
|
+
return Response.json(rows);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function GET(request: NextRequest) {
|
|
123
|
+
const id = request.nextUrl.searchParams.get('id');
|
|
124
|
+
// ruleid: sql-built-from-request
|
|
125
|
+
return Response.json(await db.query('SELECT * FROM t WHERE id = ' + id));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// --- Safe: the value is sent apart from the SQL text ---
|
|
129
|
+
|
|
130
|
+
app.get('/safe1', async (req, res) => {
|
|
131
|
+
// ok: sql-built-from-request
|
|
132
|
+
res.json(await pool.query('SELECT * FROM users WHERE id = $1', [req.params.id]));
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
app.get('/safe2', async (req, res) => {
|
|
136
|
+
// ok: sql-built-from-request
|
|
137
|
+
res.json(await sequelize.query('SELECT * FROM t WHERE name = :name', { replacements: { name: req.query.name } }));
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
app.get('/safe3', async (req, res) => {
|
|
141
|
+
// ok: sql-built-from-request
|
|
142
|
+
res.json(await prisma.$queryRaw`SELECT * FROM t WHERE email = ${req.query.email}`);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
app.get('/safe4', async (req, res) => {
|
|
146
|
+
// ok: sql-built-from-request
|
|
147
|
+
res.json(await prisma.$queryRawUnsafe('SELECT * FROM t WHERE id = $1', req.query.id));
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
app.get('/safe5', async (req, res) => {
|
|
151
|
+
const ids: string[] = req.body.ids;
|
|
152
|
+
const marks = ids.map(() => '?').join(',');
|
|
153
|
+
// ok: sql-built-from-request
|
|
154
|
+
res.json(await db.all(`SELECT * FROM t WHERE id IN (${marks})`, ids));
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
app.get('/safe6', async (req, res) => {
|
|
158
|
+
const limit = Number(req.query.limit);
|
|
159
|
+
// ok: sql-built-from-request
|
|
160
|
+
res.json(await db.query(`SELECT * FROM t LIMIT ${limit}`));
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
app.get('/safe7', async (req, res) => {
|
|
164
|
+
const page = parseInt(req.query.page as string, 10);
|
|
165
|
+
// ok: sql-built-from-request
|
|
166
|
+
res.json(await db.query(`SELECT * FROM t OFFSET ${page * 10}`));
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
app.get('/safe8', async (req, res) => {
|
|
170
|
+
// ok: sql-built-from-request
|
|
171
|
+
res.json(await db.query(`SELECT * FROM t WHERE name = ${connection.escape(req.query.name)}`));
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const TABLE = 'products';
|
|
175
|
+
app.get('/safe9', async (req, res) => {
|
|
176
|
+
// ok: sql-built-from-request
|
|
177
|
+
res.json(await db.query(`SELECT * FROM ${TABLE} WHERE id = $1`, [req.query.id]));
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
// --- Not SQL: request values given to other get/run/exec methods ---
|
|
181
|
+
|
|
182
|
+
const cache = new Map<string, string>();
|
|
183
|
+
app.get('/not-sql', (req, res) => {
|
|
184
|
+
// ok: sql-built-from-request
|
|
185
|
+
const v = cache.get(req.query.key as string);
|
|
186
|
+
// ok: sql-built-from-request
|
|
187
|
+
const m = /a(b)/.exec(req.query.s as string);
|
|
188
|
+
res.json({ v, m });
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// --- An HTTP client is not a database: .get on a client is a request, not a query ---
|
|
192
|
+
declare const client: any;
|
|
193
|
+
app.get('/fetch', (req, res) => {
|
|
194
|
+
// ok: sql-built-from-request
|
|
195
|
+
client.get(req.query.url as string, () => res.end());
|
|
196
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
rules:
|
|
2
|
+
- id: sql-built-from-request
|
|
3
|
+
languages: [javascript, typescript]
|
|
4
|
+
severity: ERROR
|
|
5
|
+
message: >-
|
|
6
|
+
A value from the request (a form field, URL, cookie or header) is put into the text of an SQL query. Someone can
|
|
7
|
+
send a value such as ' OR '1'='1 or '; DROP TABLE users; -- and the database runs it as part of the query: read
|
|
8
|
+
every row, log in as anyone, or change and delete data. Send the value apart from the SQL text with a
|
|
9
|
+
placeholder: db.query('SELECT * FROM users WHERE email = $1', [email]) (pg), '?' with mysql2 or sqlite,
|
|
10
|
+
replacements with Sequelize, or the tagged prisma.$queryRaw`... ${email}` instead of $queryRawUnsafe. Names that
|
|
11
|
+
cannot be placeholders (a column to sort by) must be picked from a fixed list in the code.
|
|
12
|
+
metadata:
|
|
13
|
+
category: code
|
|
14
|
+
# Shown in the report's list of what the code rules look for.
|
|
15
|
+
summary: 'SQL text built from request values (raw SQL with pg, mysql2, sqlite, Sequelize, Knex, TypeORM, Prisma)'
|
|
16
|
+
cwe: "CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')"
|
|
17
|
+
asvs: 'OWASP ASVS 5.0 V1.2.4 (parameterized queries)'
|
|
18
|
+
confidence: HIGH
|
|
19
|
+
limitations: >-
|
|
20
|
+
Follows a request value within one file (needs opengrep --taint-intrafile, which this kit passes). A value
|
|
21
|
+
handed to a function in another file that builds the SQL there is missed, and so are query builders and ORMs
|
|
22
|
+
used with raw fragments other than the calls listed in pattern-sinks. NoSQL queries are not covered.
|
|
23
|
+
mode: taint
|
|
24
|
+
pattern-sources:
|
|
25
|
+
# Express, Koa, Fastify and similar: request objects named req, request or ctx. The name check keeps db.query
|
|
26
|
+
# (a method) from being read as req.query (a request value).
|
|
27
|
+
- patterns:
|
|
28
|
+
- pattern-either:
|
|
29
|
+
- pattern: $REQ.body
|
|
30
|
+
- pattern: $REQ.query
|
|
31
|
+
- pattern: $REQ.params
|
|
32
|
+
- pattern: $REQ.cookies
|
|
33
|
+
- pattern: $REQ.signedCookies
|
|
34
|
+
- pattern: $REQ.headers
|
|
35
|
+
- pattern: $REQ.get(...)
|
|
36
|
+
- pattern: $REQ.header(...)
|
|
37
|
+
- pattern: $REQ.request.body
|
|
38
|
+
# Next.js and Fetch-style handlers.
|
|
39
|
+
- pattern: await $REQ.json()
|
|
40
|
+
- pattern: await $REQ.formData()
|
|
41
|
+
- pattern: $REQ.nextUrl.searchParams
|
|
42
|
+
- metavariable-regex:
|
|
43
|
+
metavariable: $REQ
|
|
44
|
+
regex: ^(req|request|ctx|context|c\.req|event)$
|
|
45
|
+
# NestJS: parameters taken from the request with a decorator.
|
|
46
|
+
- patterns:
|
|
47
|
+
- pattern-either:
|
|
48
|
+
- pattern: |
|
|
49
|
+
function $F(..., @Body(...) $P, ...) { ... }
|
|
50
|
+
- pattern: |
|
|
51
|
+
function $F(..., @Query(...) $P, ...) { ... }
|
|
52
|
+
- pattern: |
|
|
53
|
+
function $F(..., @Param(...) $P, ...) { ... }
|
|
54
|
+
- pattern: |
|
|
55
|
+
function $F(..., @Headers(...) $P, ...) { ... }
|
|
56
|
+
- focus-metavariable: $P
|
|
57
|
+
pattern-propagators:
|
|
58
|
+
- pattern: $DST = $SRC
|
|
59
|
+
from: $SRC
|
|
60
|
+
to: $DST
|
|
61
|
+
pattern-sanitizers:
|
|
62
|
+
- pattern: Number(...)
|
|
63
|
+
- pattern: parseInt(...)
|
|
64
|
+
- pattern: parseFloat(...)
|
|
65
|
+
- pattern: $X.escape(...)
|
|
66
|
+
- pattern: $X.escapeId(...)
|
|
67
|
+
- pattern: $X.escapeLiteral(...)
|
|
68
|
+
- pattern: $X.escapeIdentifier(...)
|
|
69
|
+
# Placeholders built from a list: ids.map(() => '?').join(',')
|
|
70
|
+
- pattern: '$X.map(() => "?")'
|
|
71
|
+
- pattern: '$X.map(($A) => "?")'
|
|
72
|
+
- pattern: '$X.map(($A, $I) => `$${$E}`)'
|
|
73
|
+
pattern-sinks:
|
|
74
|
+
# The first argument is the SQL text. Values passed in later arguments are safe.
|
|
75
|
+
- patterns:
|
|
76
|
+
- pattern-either:
|
|
77
|
+
- pattern: $DB.query($SQL, ...)
|
|
78
|
+
- pattern: $DB.execute($SQL, ...)
|
|
79
|
+
- pattern: $DB.raw($SQL, ...)
|
|
80
|
+
# Only receivers named like a database handle, so other objects' query() are not matched.
|
|
81
|
+
- metavariable-regex:
|
|
82
|
+
metavariable: $DB
|
|
83
|
+
regex: (?i)(.*\.)?(\w*db|database|sqlite\w*|conn|connection|pool|client|knex|sequelize|sql|tx|trx|manager|entitymanager|datasource|queryrunner|\w*repo(sitory)?)$
|
|
84
|
+
- focus-metavariable: $SQL
|
|
85
|
+
# get, all, run, exec and prepare are common names (an HTTP client's get, Map.get, RegExp.exec): only on a
|
|
86
|
+
# receiver named like a SQLite handle or statement.
|
|
87
|
+
- patterns:
|
|
88
|
+
- pattern-either:
|
|
89
|
+
- pattern: $DB.all($SQL, ...)
|
|
90
|
+
- pattern: $DB.get($SQL, ...)
|
|
91
|
+
- pattern: $DB.run($SQL, ...)
|
|
92
|
+
- pattern: $DB.exec($SQL, ...)
|
|
93
|
+
- pattern: $DB.prepare($SQL, ...)
|
|
94
|
+
- metavariable-regex:
|
|
95
|
+
metavariable: $DB
|
|
96
|
+
regex: (?i)(.*\.)?(\w*db|database|sqlite\w*|stmt|statement)$
|
|
97
|
+
- focus-metavariable: $SQL
|
|
98
|
+
- patterns:
|
|
99
|
+
- pattern-either:
|
|
100
|
+
- pattern: $P.$queryRawUnsafe($SQL, ...)
|
|
101
|
+
- pattern: $P.$executeRawUnsafe($SQL, ...)
|
|
102
|
+
- pattern: Prisma.raw($SQL)
|
|
103
|
+
- focus-metavariable: $SQL
|
package/src/cli.js
CHANGED
|
@@ -26,6 +26,8 @@ Options
|
|
|
26
26
|
--report simple also write report-simple.md: a short to-do list in plain words
|
|
27
27
|
--targets <file> for live: the list of hosts you may check (default: targets.yml)
|
|
28
28
|
--zap for live: also run the ZAP baseline web check in Docker (passive: reads responses only)
|
|
29
|
+
--ports for live: also check well-known risky ports (databases, Docker, remote desktop, dev servers): connect and close, nothing is sent
|
|
30
|
+
--no-tls for live: skip the TLS check (it takes about 2 minutes), for example when you only want --ports
|
|
29
31
|
--allow-prod for live: also allow hosts marked prod in the targets file
|
|
30
32
|
--fail-on <level> exit 1 if a finding is at or above: ${SEVERITY_ORDER.slice(0, 4).join(', ')}
|
|
31
33
|
--advanced add the Docker-based advanced tools (not available yet)
|
|
@@ -35,7 +37,7 @@ Options
|
|
|
35
37
|
Results are written to <path>/.audit/out/ (git-ignored automatically).`;
|
|
36
38
|
|
|
37
39
|
function parseArgs(argv) {
|
|
38
|
-
const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false, report: null, targets: 'targets.yml', allowProd: false, zap: false };
|
|
40
|
+
const opts = { command: 'scan', path: '.', json: false, failOn: null, advanced: false, report: null, targets: 'targets.yml', allowProd: false, zap: false, ports: false, noTls: false };
|
|
39
41
|
const rest = [];
|
|
40
42
|
for (let i = 0; i < argv.length; i++) {
|
|
41
43
|
const a = argv[i];
|
|
@@ -43,6 +45,8 @@ function parseArgs(argv) {
|
|
|
43
45
|
else if (a === '--advanced') opts.advanced = true;
|
|
44
46
|
else if (a === '--allow-prod') opts.allowProd = true;
|
|
45
47
|
else if (a === '--zap') opts.zap = true;
|
|
48
|
+
else if (a === '--ports') opts.ports = true;
|
|
49
|
+
else if (a === '--no-tls') opts.noTls = true;
|
|
46
50
|
else if (a === '--targets') opts.targets = argv[++i];
|
|
47
51
|
else if (a === '--report') opts.report = argv[++i];
|
|
48
52
|
else if (a.startsWith('--report=')) opts.report = a.slice(9);
|
|
@@ -127,7 +131,7 @@ export async function main(argv) {
|
|
|
127
131
|
case 'live': {
|
|
128
132
|
if (opts.path === '.') throw new Error('live needs a host: npx ai-secure-audit live <host[:port]>');
|
|
129
133
|
const log = opts.json ? () => {} : (m) => process.stderr.write(`${m}\n`);
|
|
130
|
-
const { out, result } = await live(opts.path, { targetsFile: opts.targets, allowProd: opts.allowProd, zap: opts.zap, log, version: pkg.version });
|
|
134
|
+
const { out, result } = await live(opts.path, { targetsFile: opts.targets, allowProd: opts.allowProd, zap: opts.zap, ports: opts.ports, noTls: opts.noTls, log, version: pkg.version });
|
|
131
135
|
const r = relative(process.cwd(), out).split('\\').join('/');
|
|
132
136
|
process.stdout.write(opts.json ? JSON.stringify(result, null, 2) + '\n' : liveSummary(result, r) + '\n');
|
|
133
137
|
if (result.tools.some((t) => t.status === 'failed')) return 2;
|