Skip to content

Commit e105889

Browse files
dhensbyclaude
andcommitted
fix: reject unsafe table and column names in msnodesqlv8 bulk loads
With the msnodesqlv8 driver, a bulk load finds its table through the driver's table manager. The table manager writes the table name into the text of a query of its own, then writes an INSERT from what it found. Neither is quoted in a way that a name cannot end. So a table, schema or database name could end the quoting it was written into, and the rest of the name ran as SQL. The same was true of a column name, or a table name as the server reported it, in the INSERT. The name is now read once, without its brackets as before, and checked before a connection is taken. The table manager is given the string that was checked: - The table and schema names must not hold a single `'`, because they are written into quoted strings. A doubled `''` is still accepted. - The database name must be made of identifier characters. Space around it, or double quotes, are allowed. It must not hold a `'`. - Every part of a temporary table name must be made of identifier characters, because it is written unquoted into the INSERT. - No part may hold a `$` followed by a backtick, a `'` or a `&`. The table manager replaces each of these pairs with a part of its own query, so such a name never named the table it seemed to. When the table manager has found the table, the names it will write are checked too. The name of a table in tempdb is written unquoted into the INSERT, so each of its parts must pass the rule for the database name. This applies also when the name does not say tempdb. A table or a writable column whose name, as the server reports it, holds a `]` is rejected, because the driver writes it in brackets without doubling the `]`. A rejection at this point releases the connection. A rejected name raises EINJECT. A name that passes the checks reaches the table manager unchanged. The tedious driver is not changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 703de08 commit e105889

3 files changed

Lines changed: 443 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 53 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1008,7 +1008,7 @@ __Errors__
10081008
- ECONNCLOSED (`ConnectionError`) - Connection is closed.
10091009
- ENOTBEGUN (`TransactionError`) - Transaction has not begun.
10101010
- EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
1011-
- EINJECT (`RequestError`) - Column name or parameter type is not a valid identifier. See [Identifiers](#identifiers).
1011+
- EINJECT (`RequestError`) - Table name, column name or parameter type is not a valid identifier. See [Identifiers](#identifiers).
10121012

10131013
---------------------------------------
10141014

@@ -1848,9 +1848,9 @@ Results in:
18481848
## Identifiers
18491849

18501850
Values are sent to the server as parameters and may hold anything. A few things
1851-
are not values, and cannot be: the name of a parameter, the name of a column in a
1852-
bulk load, the type a parameter is declared as, the name of a stored procedure, and
1853-
the name of a transaction. Those are *identifiers*, and
1851+
are not values, and cannot be: the name of a parameter, the name of a table or a
1852+
column in a bulk load, the type a parameter is declared as, the name of a stored
1853+
procedure, and the name of a transaction. Those are *identifiers*, and
18541854
no SQL database can bind them, so this library builds them into the statement it
18551855
sends. It checks them, and rejects anything that could end the identifier and have
18561856
the rest of the value read as SQL.
@@ -1892,6 +1892,10 @@ table.columns.add('a]]b', sql.Int) // the column named a]b
18921892
A single `]` raises `EINJECT`. Column names are not otherwise restricted: spaces,
18931893
punctuation and reserved words are all fine, because the quoting handles them.
18941894

1895+
With the `msnodesqlv8` driver, a bulk load into a column whose name holds a `]`
1896+
raises `EINJECT`, because that driver cannot write such a name. See
1897+
[Bulk load table names](#bulk-load-table-names).
1898+
18951899
The keys of `options.order` are also identifiers, but the driver writes them into the bulk
18961900
statement's `ORDER (...)` clause *unquoted* rather than as `[name]`. They follow the type
18971901
name rule instead: bare, or quoted with brackets or double quotes.
@@ -1901,6 +1905,50 @@ request.bulk(table, { order: { created_at: 'ASC' } })
19011905
request.bulk(table, { order: { '[Created At]': 'DESC' } }) // quote a spaced name yourself
19021906
```
19031907

1908+
### Bulk load table names
1909+
1910+
With the `msnodesqlv8` driver, a bulk load finds its table through the driver's table
1911+
manager. The table manager writes the table name into a query of its own, and then
1912+
writes an `INSERT` from what it found. This library gives it the name without its
1913+
brackets, and the table manager splits that name on every `.`. Before a connection is
1914+
taken, this library checks each part:
1915+
1916+
- The table and schema names are written into a quoted string, so they must not hold a
1917+
single `'`. The table manager reads a doubled `''` as one `'`. The `tedious` driver
1918+
does not, so there the same name is a different table.
1919+
- The database name is written unquoted. It may hold the characters a parameter name
1920+
may, with space around it, or it may be in double quotes. It must not hold a `'`. Any
1921+
part before the database is checked in the same way. The table manager reads double
1922+
quotes as quoting, but the `tedious` driver reads them as part of the name.
1923+
- The name of a temporary table, one that starts with `#`, is written unquoted into the
1924+
`INSERT`, so every part may hold only the characters a parameter name may.
1925+
- No part may hold a `$` followed by a backtick, a `'` or a `&`. The table manager
1926+
replaces each of these pairs with a part of its own query.
1927+
1928+
```javascript
1929+
// what request.bulk(table) does with the msnodesqlv8 driver, for each of these tables
1930+
new sql.Table('dbo.[My Table]') // fine
1931+
new sql.Table("[O'Brien]") // EINJECT: a single ' in the table name
1932+
new sql.Table('[my db].dbo.orders') // EINJECT: a space in an unquoted database name
1933+
new sql.Table('[#my temp]') // EINJECT: a space in a temporary table name
1934+
```
1935+
1936+
When the table manager has found the table, this library checks what it found. A
1937+
failure here releases the connection:
1938+
1939+
- A table in `tempdb` is written into the `INSERT` as the name you gave, so each part of
1940+
that name is checked as the database name is. This applies when the connection's own
1941+
database is `tempdb`, too.
1942+
- Any other table is written as `[database].[schema].[table]`, from the names the
1943+
server reported, without doubling a `]`. A table whose database, schema or table name
1944+
holds a `]` is rejected.
1945+
- Each column the driver writes to is written as `[name]`, without doubling a `]`, so a
1946+
column whose name holds one is rejected. The driver does not write to identity,
1947+
computed and other read-only columns, so their names may hold one.
1948+
1949+
A name that fails one of these checks raises `EINJECT`. The `tedious` driver does not
1950+
make these checks.
1951+
19041952
### Type names and sizes
19051953

19061954
`sql.TVP()` takes the name of a table type, optionally qualified with a schema and
@@ -1992,7 +2040,7 @@ Name | Code | Message
19922040
`RequestError` | ECANCEL | Cancelled.
19932041
`RequestError` | ETIMEOUT | Request timeout.
19942042
`RequestError` | EARGS | Invalid number of arguments.
1995-
`RequestError` | EINJECT | Parameter name, column name or type is not a valid identifier.
2043+
`RequestError` | EINJECT | Parameter name, table name, column name or type is not a valid identifier.
19962044
`RequestError` | ENOCONN | No connection is specified for that request.
19972045
`PreparedStatementError` | EARGS | Invalid number of arguments.
19982046
`PreparedStatementError` | EINJECT | Parameter name is not a valid identifier.

‎lib/msnodesqlv8/request.js‎

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ const msnodesql = require('msnodesqlv8')
44
const debug = require('debug')('mssql:msv8')
55
const BaseRequest = require('../base/request')
66
const RequestError = require('../error/request-error')
7-
const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
7+
const MSSQLError = require('../error/mssql-error')
8+
const { IDS, objectHasProperty, isValidParameterName, assertSafeColumnName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
89
const { TYPES, DECLARATIONS, declare } = require('../datatypes')
910
const { PARSERS: UDT } = require('../udt')
1011
const Table = require('../table')
@@ -14,6 +15,81 @@ const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
1415
const XML_COLUMN_ID = 'XML_F52E2B61-18A1-11d1-B105-00805F49916B'
1516
const EMPTY_BUFFER = Buffer.alloc(0)
1617

18+
// msnodesqlv8 bulk loads through its table manager, which looks the table up by writing the
19+
// name it is given into the text of a query of its own, splitting it on every `.` to do so.
20+
// The last part, the table, and the one before it, the schema, are written inside quoted
21+
// strings, which only a `'` can end, and a doubled one is how a string holds it. The part
22+
// before the schema is the database, which is written bare, as an identifier, and also inside
23+
// one of those strings. Any part before the database is held to the same rule, although the
24+
// table manager drops it. The name of a table in tempdb is also written bare, whole, as the
25+
// target of the INSERT that the table manager builds once it has found the table. A bare part
26+
// may hold the characters a parameter name may (see lib/utils.js): those that cannot end an
27+
// identifier.
28+
const isBarePart = part => isValidParameterName(part)
29+
// The database, and each part of the name of a table in tempdb, may also have space around it,
30+
// which is read as space between words, or be in double quotes. In double quotes it is a quoted
31+
// identifier, which only a `"` can end, or, with QUOTED_IDENTIFIER off, a string where no string
32+
// is allowed, so the query does not compile and nothing in it runs. Neither form may hold a `'`.
33+
// The database is also written inside a string, which a `'` would end, and in the INSERT a `'`
34+
// would start one. The server reads NEL and ZERO WIDTH SPACE as space too, but `\s` does not
35+
// match them.
36+
const PADDING = /^[\s\u0085\u200b]+|[\s\u0085\u200b]+$/g
37+
const isDatabasePart = part => {
38+
const trimmed = part.replace(PADDING, '')
39+
return isBarePart(trimmed) || /^"[^"']+"$/.test(trimmed)
40+
}
41+
const endsQuotedString = part => part.replace(/''/g, '').includes('\'')
42+
// The table manager puts each part into its query with String.prototype.replace. That reads $`
43+
// in the part as the text of the query before the placeholder, $' as the text after it, and $&
44+
// as the placeholder. A name that holds one of these does not name the table it seems to. The
45+
// text it copies brings the quotes of the query with it, so these are rejected in every part.
46+
const COPIES_QUERY = /\$[`'&]/
47+
48+
// Takes the name the table manager is to be given, and returns what was read, so the name it
49+
// is given is the one that was checked.
50+
const assertSafeBulkTable = (name) => {
51+
const table = String(name)
52+
const parts = table.split('.')
53+
if (parts[parts.length - 1].charAt(0) === '#') {
54+
if (!parts.every(isBarePart)) {
55+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the name of a temporary table unquoted, so it may only contain identifier characters.`, 'EINJECT')
56+
}
57+
} else if (!parts.slice(0, -2).every(isDatabasePart)) {
58+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the database name unquoted, so it may only contain identifier characters, or be in double quotes and contain no '.`, 'EINJECT')
59+
} else if (parts.slice(-2).some(endsQuotedString)) {
60+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the table and schema names into a quoted string, which a ' would end.`, 'EINJECT')
61+
} else if (COPIES_QUERY.test(table)) {
62+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 replaces $\`, $' and $& in a table name with parts of its own query.`, 'EINJECT')
63+
}
64+
return table
65+
}
66+
67+
// Checked once the table manager has found the table, against what it found, since that is
68+
// what it builds its INSERT from. A table in tempdb is written as the name it was given, so
69+
// each part of that name is held to the database rule above. The connection's own database
70+
// can be tempdb, so the name need not say so. Any other table is written as
71+
// `[database].[schema].[table]`, from the names the server reported, and each column it writes
72+
// to as `[name]`. In both, any `]` in a name is left as it is. The columns it writes to are
73+
// those it does not count as read only. A driver without `isReadOnly()` on its columns, such
74+
// as 2.0.0, counts these flags instead.
75+
const isReadOnlyColumn = col => typeof col.isReadOnly === 'function'
76+
? col.isReadOnly()
77+
: (col.is_identity || col.is_computed || col.is_hidden || col.generated_always_type)
78+
79+
const assertSafeBulkInsert = (table, columns) => {
80+
if (columns[0].table_catalog === 'tempdb' && !table.split('.').every(isDatabasePart)) {
81+
throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the name of a table in tempdb unquoted, so each part may only contain identifier characters, or be in double quotes and contain no '.`, 'EINJECT')
82+
}
83+
if (columns[0].table_catalog !== 'tempdb' && ['table_catalog', 'table_schema', 'table_name'].some(k => String(columns[0][k]).includes(']'))) {
84+
throw new MSSQLError(`Invalid table name '${columns[0].table_catalog}.${columns[0].table_schema}.${columns[0].table_name}'. msnodesqlv8 cannot bulk load into a table whose name contains ']'.`, 'EINJECT')
85+
}
86+
for (const col of columns) {
87+
if (!isReadOnlyColumn(col) && String(col.name).includes(']')) {
88+
throw new MSSQLError(`Invalid column name '${col.name}'. msnodesqlv8 cannot bulk load into a column whose name contains ']'.`, 'EINJECT')
89+
}
90+
}
91+
}
92+
1793
const castParameter = function (value, type) {
1894
if (value == null) {
1995
if ((type === TYPES.Binary) || (type === TYPES.VarBinary) || (type === TYPES.Image)) {
@@ -182,6 +258,17 @@ class Request extends BaseRequest {
182258
return setImmediate(callback, new RequestError("You can't use table variables for bulk insert.", 'ENAME'))
183259
}
184260

261+
// The table manager is given the path with its brackets removed, as before, and it is
262+
// given the string that is checked here. The check is made before a connection is
263+
// borrowed, and on the path rather than where the table is built, because `path` is a
264+
// plain property that can be changed after the table is built.
265+
let target
266+
try {
267+
target = assertSafeBulkTable(table.path.replace(/\[|\]/g, ''))
268+
} catch (e) {
269+
return callback(new RequestError(e, 'EREQUEST'))
270+
}
271+
185272
this.parent.acquire(this, (err, connection) => {
186273
let hasReturned = false
187274
if (!err) {
@@ -224,7 +311,7 @@ class Request extends BaseRequest {
224311
const go = () => {
225312
const tm = connection.tableMgr()
226313
// the table manager reports a failed lookup as (null, err), not error first
227-
return tm.bind(table.path.replace(/\[|\]/g, ''), (mgr, err) => {
314+
return tm.bind(target, (mgr, err) => {
228315
if (err) {
229316
return done(err)
230317
}
@@ -235,6 +322,8 @@ class Request extends BaseRequest {
235322

236323
const rows = []
237324
try {
325+
assertSafeBulkInsert(target, mgr.columns)
326+
238327
for (const col of table.columns) {
239328
// re-checked here for the same reason as the name below, in case the
240329
// definition changed since it was checked above

0 commit comments

Comments
 (0)