ai-secure-audit 0.0.15 → 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/coverage.js +100 -5
- 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/coverage.js
CHANGED
|
@@ -23,6 +23,11 @@ const LANGUAGES = {
|
|
|
23
23
|
cpp: ['.cpp', '.cc', '.cxx', '.hpp', '.hh'],
|
|
24
24
|
dart: ['.dart'],
|
|
25
25
|
swift: ['.swift'],
|
|
26
|
+
scala: ['.scala'],
|
|
27
|
+
elixir: ['.ex', '.exs'],
|
|
28
|
+
lua: ['.lua'],
|
|
29
|
+
// Smart contracts: a language this kit does not read must still be named, or its files look checked.
|
|
30
|
+
solidity: ['.sol'],
|
|
26
31
|
// Single-file components: the JavaScript rules do not read the <script> block inside them.
|
|
27
32
|
vue: ['.vue'],
|
|
28
33
|
svelte: ['.svelte'],
|
|
@@ -131,7 +136,9 @@ const named = (files) => `${files.slice(0, 5).join(', ')}${files.length > 5 ? `
|
|
|
131
136
|
export const NO_LIBRARY_CHECK = 'Libraries not checked:';
|
|
132
137
|
|
|
133
138
|
// Languages the kit's own code rules read, taken from the rule files so the list cannot fall behind them.
|
|
134
|
-
|
|
139
|
+
const RULES_DIR = fileURLToPath(new URL('../rules/', import.meta.url));
|
|
140
|
+
|
|
141
|
+
export function ruleLanguages(rulesDir = RULES_DIR) {
|
|
135
142
|
const langs = new Set();
|
|
136
143
|
for (const f of readdirSync(rulesDir).filter((n) => /\.ya?ml$/.test(n)).sort()) {
|
|
137
144
|
for (const m of readFileSync(join(rulesDir, f), 'utf8').matchAll(/languages:\s*\[([^\]]*)\]/g)) {
|
|
@@ -141,6 +148,33 @@ export function ruleLanguages(rulesDir = fileURLToPath(new URL('../rules/', impo
|
|
|
141
148
|
return langs;
|
|
142
149
|
}
|
|
143
150
|
|
|
151
|
+
// The rules a user sees findings from, with the one-line summary the report lists. Helper rules marked
|
|
152
|
+
// `internal: true` only filter other findings, so they are left out.
|
|
153
|
+
export function ruleSummaries(rulesDir = RULES_DIR) {
|
|
154
|
+
const rules = [];
|
|
155
|
+
for (const f of readdirSync(rulesDir).filter((n) => /\.ya?ml$/.test(n)).sort()) {
|
|
156
|
+
for (const block of readFileSync(join(rulesDir, f), 'utf8').split(/^ {2}- id:/m).slice(1)) {
|
|
157
|
+
if (/^\s+internal:\s*true\b/m.test(block)) continue;
|
|
158
|
+
const id = block.slice(0, block.indexOf('\n')).trim();
|
|
159
|
+
const languages = (/languages:\s*\[([^\]]*)\]/.exec(block)?.[1] ?? '').split(',').map((l) => l.trim()).filter(Boolean);
|
|
160
|
+
const summary = /^\s+summary:\s*'([^']*)'/m.exec(block)?.[1] ?? /^\s+summary:\s*"([^"]*)"/m.exec(block)?.[1] ?? null;
|
|
161
|
+
rules.push({ id, languages, summary });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return rules;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Common mistakes that no code rule of this kit looks for yet. Keep this list true: drop an item once a rule covers it.
|
|
168
|
+
export const NOT_LOOKED_FOR = [
|
|
169
|
+
'NoSQL queries or shell commands built from user input',
|
|
170
|
+
'HTML put on the page from values whose names do not look like text people type, or through other variables (XSS)',
|
|
171
|
+
'redirects or server-side requests to a URL the user chose',
|
|
172
|
+
'folders served as file lists',
|
|
173
|
+
'passwords stored with a fast hash such as MD5 or SHA-1',
|
|
174
|
+
];
|
|
175
|
+
|
|
176
|
+
const extOf = (name) => (name.includes('.') ? name.slice(name.lastIndexOf('.')).toLowerCase() : '');
|
|
177
|
+
|
|
144
178
|
function walk(dir, rel, out, limit) {
|
|
145
179
|
let entries;
|
|
146
180
|
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
@@ -152,26 +186,38 @@ function walk(dir, rel, out, limit) {
|
|
|
152
186
|
}
|
|
153
187
|
}
|
|
154
188
|
|
|
155
|
-
export function projectCoverage(root, { rulesDir, limit = 200_000 } = {}) {
|
|
189
|
+
export function projectCoverage(root, { rulesDir = RULES_DIR, limit = 200_000 } = {}) {
|
|
156
190
|
const files = [];
|
|
157
191
|
walk(root, '', files, limit);
|
|
158
192
|
const covered = ruleLanguages(rulesDir);
|
|
193
|
+
const rules = ruleSummaries(rulesDir);
|
|
159
194
|
const counts = new Map();
|
|
160
195
|
const lockfiles = [];
|
|
161
196
|
const compose = [];
|
|
162
197
|
for (const f of files) {
|
|
163
198
|
const name = basename(f);
|
|
164
|
-
const
|
|
165
|
-
const lang = BY_EXT.get(ext);
|
|
199
|
+
const lang = BY_EXT.get(extOf(name));
|
|
166
200
|
if (lang) counts.set(lang, (counts.get(lang) ?? 0) + 1);
|
|
167
201
|
if (LOCKFILES[name]) lockfiles.push({ file: f, ...LOCKFILES[name] });
|
|
168
202
|
if (isComposeFile(name)) compose.push(f);
|
|
169
203
|
}
|
|
170
204
|
const languages = [...counts].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
|
|
171
205
|
.map(([language, n]) => ({ language, files: n, code_rules: covered.has(language) }));
|
|
172
|
-
|
|
206
|
+
// Only the rules that can match a language found here: a NestJS rule says nothing about a PHP project.
|
|
207
|
+
const present = new Set(languages.filter((l) => l.code_rules).map((l) => l.language));
|
|
208
|
+
// opengrep's built-in ignore list leaves out folders named test or tests at any depth, and *.min.js files, so the
|
|
209
|
+
// code rules never read them. Files in a language with no rules are already named above.
|
|
210
|
+
const ruled = (f) => present.has(BY_EXT.get(extOf(basename(f))));
|
|
211
|
+
const code_skipped = {
|
|
212
|
+
test_folders: files.filter((f) => ruled(f) && /(?:^|\/)tests?\//.test(f)),
|
|
213
|
+
minified: files.filter((f) => ruled(f) && /\.min\.js$/i.test(f) && !/(?:^|\/)tests?\//.test(f)),
|
|
214
|
+
};
|
|
215
|
+
const code_rules = rules.filter((r) => r.languages.some((l) => present.has(l))).map(({ id, summary }) => ({ id, summary }));
|
|
216
|
+
return { languages, code_rules, code_skipped, lockfiles, compose, unlocked: manifestsWithoutLockfile(root, files), truncated: files.length >= limit };
|
|
173
217
|
}
|
|
174
218
|
|
|
219
|
+
const list = (items) => (items.length < 2 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`);
|
|
220
|
+
|
|
175
221
|
// Plain sentences for the report and for the AI assistant. Empty when everything found is covered.
|
|
176
222
|
export function coverageGaps(cov) {
|
|
177
223
|
const gaps = [];
|
|
@@ -182,6 +228,55 @@ export function coverageGaps(cov) {
|
|
|
182
228
|
'AI assistant with the prompt in https://github.com/surapas3022/ai-secure-audit/blob/main/docs/ai-review-prompt.md ' +
|
|
183
229
|
'(its results are leads to check, not findings).');
|
|
184
230
|
}
|
|
231
|
+
// Languages that do have rules: say how few, so "code rules: yes" is not read as "the code was checked".
|
|
232
|
+
const withRules = cov.languages.filter((l) => l.code_rules).map((l) => l.language);
|
|
233
|
+
if (withRules.length && cov.code_rules) {
|
|
234
|
+
const n = cov.code_rules.length;
|
|
235
|
+
gaps.push(`Code rules: ${list(withRules)} code was checked with only ${n} rule${n === 1 ? '' : 's'} from this kit` +
|
|
236
|
+
(n ? `: ${cov.code_rules.map((r) => r.summary ?? r.id).join('; ')}` : '') + '. ' +
|
|
237
|
+
`Other mistakes were not looked for, such as ${list(NOT_LOOKED_FOR)}; "0 findings" says nothing about them. ` +
|
|
238
|
+
'To review them, ask an AI assistant with the prompt in ' +
|
|
239
|
+
'https://github.com/surapas3022/ai-secure-audit/blob/main/docs/ai-review-prompt.md (its results are leads to check, not findings).');
|
|
240
|
+
}
|
|
241
|
+
const skipped = cov.code_skipped ?? { test_folders: [], minified: [] };
|
|
242
|
+
const parts = [];
|
|
243
|
+
const files = (n) => `${n} ${n === 1 ? 'file' : 'files'}`;
|
|
244
|
+
if (skipped.test_folders.length) parts.push(`${files(skipped.test_folders.length)} in test or tests folders (${named(skipped.test_folders)})`);
|
|
245
|
+
if (skipped.minified.length) {
|
|
246
|
+
const n = skipped.minified.length;
|
|
247
|
+
parts.push(`${n} minified ${n === 1 ? 'file' : 'files'} (${named(skipped.minified)})`);
|
|
248
|
+
}
|
|
249
|
+
if (parts.length) {
|
|
250
|
+
const total = skipped.test_folders.length + skipped.minified.length;
|
|
251
|
+
const what = [skipped.test_folders.length && 'folders named test or tests', skipped.minified.length && '*.min.js files'].filter(Boolean);
|
|
252
|
+
const why = [
|
|
253
|
+
skipped.test_folders.length && 'Test code usually does not run as the app; if a folder named test or tests holds code that does, review it by hand.',
|
|
254
|
+
skipped.minified.length && 'A minified file does run, but it is usually a library copied in or build output whose source is elsewhere; if it is code you wrote, check the source instead.',
|
|
255
|
+
].filter(Boolean);
|
|
256
|
+
gaps.push(`Code rules: ${parts.join(' and ')} ${total === 1 ? 'was' : 'were'} not checked by the code rules: opengrep ` +
|
|
257
|
+
`leaves ${what.join(' and ')} out on its own. ${why.join(' ')} The secret check still read these files.`);
|
|
258
|
+
}
|
|
259
|
+
const read = cov.code_read ?? { not_read: [], read_in_part: [], stopped: [] };
|
|
260
|
+
const n = (k, one, many) => `${k} ${k === 1 ? one : many}`;
|
|
261
|
+
if (read.not_read.length) {
|
|
262
|
+
const list = named(read.not_read.map((x) => (x.line ? `${x.file} (syntax error at line ${x.line})` : x.file)));
|
|
263
|
+
gaps.push(`Code rules: ${n(read.not_read.length, 'file', 'files')} could not be read by the code checker (${list}), so ` +
|
|
264
|
+
`${read.not_read.length === 1 ? 'it was' : 'they were'} not checked by the code rules at all. This happens with syntax ` +
|
|
265
|
+
'the checker does not know, or a file that is only part of a program. If one of them is app code, review it by hand ' +
|
|
266
|
+
'(full list in findings.json under coverage.code_read).');
|
|
267
|
+
}
|
|
268
|
+
if (read.read_in_part.length) {
|
|
269
|
+
const list = named(read.read_in_part.map((x) => (x.lines.length ? `${x.file} (${x.lines.length === 1 ? 'line' : 'lines'} ${x.lines.join(', ')})` : x.file)));
|
|
270
|
+
gaps.push(`Code rules: ${n(read.read_in_part.length, 'file was', 'files were')} read only in part (${list}): the code ` +
|
|
271
|
+
'checker skipped the code around those lines, so a finding there can be missing. Review those parts by hand ' +
|
|
272
|
+
'(full list in findings.json under coverage.code_read).');
|
|
273
|
+
}
|
|
274
|
+
if (read.stopped.length) {
|
|
275
|
+
const list = named(read.stopped.map((x) => (x.rules.length ? `${x.file} (${x.rules.join(', ')})` : x.file)));
|
|
276
|
+
gaps.push(`Code rules: the check stopped on ${n(read.stopped.length, 'file', 'files')} before it finished (${list}), ` +
|
|
277
|
+
'because a rule took too long; those rules did not finish on that file. Large or generated files cause this ' +
|
|
278
|
+
'(full list in findings.json under coverage.code_read).');
|
|
279
|
+
}
|
|
185
280
|
if (cov.unlocked?.length) {
|
|
186
281
|
gaps.push(`${NO_LIBRARY_CHECK} no lockfile (the file that records exact library versions) was found for ${named(cov.unlocked)}, ` +
|
|
187
282
|
'so the libraries listed there were not looked at; "0 findings" says nothing about them. Create the lockfile with your ' +
|
package/src/report-simple.js
CHANGED
|
@@ -104,6 +104,7 @@ export function reportSimple(result, date) {
|
|
|
104
104
|
lines.push('These tools cannot see the following, so "nothing found" does not cover them:', '');
|
|
105
105
|
lines.push('- Whether one user can open or change another user\'s data');
|
|
106
106
|
lines.push('- Rules of your business: prices, coupons, payments, approvals');
|
|
107
|
+
lines.push('- How signing in, signing up and resetting a password work, for example whether someone can make themselves an admin when signing up, or guess the answer to a reset question');
|
|
107
108
|
lines.push('- Anything about your live website or server');
|
|
108
109
|
for (const g of result.coverage?.gaps ?? []) lines.push(`- ${g}`);
|
|
109
110
|
lines.push('');
|