@contrast/assess 1.6.0 → 1.8.0

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.
Files changed (35) hide show
  1. package/lib/dataflow/propagation/index.js +3 -0
  2. package/lib/dataflow/propagation/install/JSON/index.js +33 -0
  3. package/lib/dataflow/propagation/install/JSON/stringify.js +290 -0
  4. package/lib/dataflow/propagation/install/buffer.js +79 -0
  5. package/lib/dataflow/propagation/install/contrast-methods/string.js +5 -1
  6. package/lib/dataflow/propagation/install/encode-uri-component.js +5 -2
  7. package/lib/dataflow/propagation/install/pug-runtime-escape.js +5 -2
  8. package/lib/dataflow/propagation/install/sequelize.js +310 -0
  9. package/lib/dataflow/propagation/install/sql-template-strings.js +5 -4
  10. package/lib/dataflow/propagation/install/string/match.js +2 -2
  11. package/lib/dataflow/propagation/install/string/replace.js +9 -4
  12. package/lib/dataflow/sinks/common.js +10 -1
  13. package/lib/dataflow/sinks/index.js +30 -1
  14. package/lib/dataflow/sinks/install/express/index.js +29 -0
  15. package/lib/dataflow/sinks/install/express/unvalidated-redirect.js +134 -0
  16. package/lib/dataflow/sinks/install/fastify/unvalidated-redirect.js +96 -69
  17. package/lib/dataflow/sinks/install/http.js +20 -5
  18. package/lib/dataflow/sinks/install/koa/unvalidated-redirect.js +33 -9
  19. package/lib/dataflow/sinks/install/mongodb.js +297 -82
  20. package/lib/dataflow/sinks/install/mssql.js +9 -4
  21. package/lib/dataflow/sinks/install/mysql.js +20 -4
  22. package/lib/dataflow/sinks/install/postgres.js +25 -12
  23. package/lib/dataflow/sinks/install/sequelize.js +142 -0
  24. package/lib/dataflow/sinks/install/sqlite3.js +9 -4
  25. package/lib/dataflow/sources/handler.js +144 -26
  26. package/lib/dataflow/sources/index.js +6 -8
  27. package/lib/dataflow/sources/install/body-parser1.js +133 -0
  28. package/lib/dataflow/sources/install/cookie-parser1.js +101 -0
  29. package/lib/dataflow/sources/install/express/index.js +31 -0
  30. package/lib/dataflow/sources/install/express/params.js +81 -0
  31. package/lib/dataflow/sources/install/express/parsedUrl.js +87 -0
  32. package/lib/dataflow/sources/install/http.js +32 -18
  33. package/lib/dataflow/sources/install/querystring.js +75 -0
  34. package/lib/dataflow/tag-utils.js +68 -1
  35. package/package.json +3 -3
@@ -27,6 +27,7 @@ module.exports = function(core) {
27
27
  require('./install/url')(core);
28
28
  require('./install/validator')(core);
29
29
  require('./install/array-prototype-join')(core);
30
+ require('./install/buffer')(core);
30
31
  require('./install/decode-uri-component')(core);
31
32
  require('./install/encode-uri-component')(core);
32
33
  require('./install/escape-html')(core);
@@ -37,6 +38,8 @@ module.exports = function(core) {
37
38
  require('./install/sql-template-strings')(core);
38
39
  require('./install/unescape')(core);
39
40
  require('./install/querystring')(core);
41
+ require('./install/sequelize')(core);
42
+ require('./install/JSON')(core);
40
43
 
41
44
  propagation.install = function() {
42
45
  callChildComponentMethodsSync(propagation, 'install');
@@ -0,0 +1,33 @@
1
+ /*
2
+ * Copyright: 2022 Contrast Security, Inc
3
+ * Contact: support@contrastsecurity.com
4
+ * License: Commercial
5
+
6
+ * NOTICE: This Software and the patented inventions embodied within may only be
7
+ * used as part of Contrast Security’s commercial offerings. Even though it is
8
+ * made available through public repositories, use of this Software is subject to
9
+ * the applicable End User Licensing Agreement found at
10
+ * https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
11
+ * between Contrast Security and the End User. The Software may not be reverse
12
+ * engineered, modified, repackaged, sold, redistributed or otherwise used in a
13
+ * way not consistent with the End User License Agreement.
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ const { callChildComponentMethodsSync } = require('@contrast/common');
19
+
20
+ module.exports = function(core) {
21
+ const jsonInstrumentation = core.assess.dataflow.propagation.jsonInstrumentation = {
22
+ install() {
23
+ callChildComponentMethodsSync(jsonInstrumentation, 'install');
24
+ },
25
+ uninstall() {
26
+ callChildComponentMethodsSync(jsonInstrumentation, 'uninstall');
27
+ }
28
+ };
29
+
30
+ require('./stringify')(core);
31
+
32
+ return jsonInstrumentation;
33
+ };
@@ -0,0 +1,290 @@
1
+ /*
2
+ * Copyright: 2022 Contrast Security, Inc
3
+ * Contact: support@contrastsecurity.com
4
+ * License: Commercial
5
+
6
+ * NOTICE: This Software and the patented inventions embodied within may only be
7
+ * used as part of Contrast Security’s commercial offerings. Even though it is
8
+ * made available through public repositories, use of this Software is subject to
9
+ * the applicable End User Licensing Agreement found at
10
+ * https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
11
+ * between Contrast Security and the End User. The Software may not be reverse
12
+ * engineered, modified, repackaged, sold, redistributed or otherwise used in a
13
+ * way not consistent with the End User License Agreement.
14
+ */
15
+
16
+ 'use strict';
17
+
18
+ const {
19
+ createMergedTags
20
+ } = require('../../../tag-utils');
21
+ const { isString, inspect, replace, match, matchAll, slice } = require('@contrast/common');
22
+ const { patchType } = require('../../common');
23
+ const crypto = require('crypto');
24
+
25
+ function makeCanary() {
26
+ return replace(
27
+ crypto
28
+ .randomBytes(12)
29
+ .toString('base64'),
30
+ /[+\\]/g,
31
+ (match) => match === '+' ? '%' : '#'
32
+ );
33
+ }
34
+
35
+ const canary = makeCanary();
36
+ const regex = new RegExp(`"${canary}(\\d+)~`, 'g');
37
+ function identity(_key, val) {
38
+ return val;
39
+ }
40
+
41
+ function patchReplacer(replacer) {
42
+ if (Array.isArray(replacer)) {
43
+ // keys that are numbers get cast to string when they come through the replacer
44
+ // add '' to the list of keys as that's always the first iteration of replacer, the entire json string
45
+ const filterKeys = replacer
46
+ .filter((key) => isString(key) || typeof key === 'number')
47
+ .concat('')
48
+ .map((value) => value.toString());
49
+
50
+ let nextArray = [];
51
+ replacer = function(key, value) {
52
+ // we need to keep track of arrays
53
+ // and shift each element as the replacer hits it
54
+ // so we can compare those values are expected
55
+ // when filtering
56
+ const nextEl = nextArray.shift();
57
+ if (Array.isArray(value)) {
58
+ nextArray = [...value];
59
+ }
60
+
61
+ if (filterKeys.includes(key) || value === nextEl) {
62
+ return value;
63
+ }
64
+ };
65
+ } else if (typeof replacer === 'function') {
66
+ // do nothing!
67
+ } else {
68
+ replacer = identity;
69
+ }
70
+
71
+ return replacer;
72
+ }
73
+
74
+ module.exports = function(core) {
75
+ const {
76
+ scopes: { sources, instrumentation },
77
+ patcher,
78
+ assess: {
79
+ dataflow: { tracker, eventFactory: { createPropagationEvent } }
80
+ }
81
+ } = core;
82
+
83
+ function getUntrustedSpaceProps(space) {
84
+ // it can't be a problem if it's not a string, if the string is all spaces, or
85
+ // if the string is zero length.
86
+ if (!isString(space) || match(space, /^\s+$/) || !space) {
87
+ return null;
88
+ }
89
+
90
+
91
+ const props = tracker.getData(slice(space, 0, 10));
92
+ if (!props || !Object.keys(props.tags).length) {
93
+ return null;
94
+ }
95
+
96
+ return props;
97
+ }
98
+
99
+
100
+ function createSpaceTagRanges(result, metadata) {
101
+ const tags = {};
102
+ const spaceValue = slice(metadata.origArgs[2], 0, 10);
103
+ const { spaceProps: { tags: spacePropsTags } } = metadata;
104
+
105
+ const spaces = Array.from(matchAll(result, new RegExp(`(?<=\\n)(${spaceValue})+?(?=\\d|"|null|]|})`, 'g')));
106
+
107
+ for (const space of spaces) {
108
+ const match = space[0];
109
+ const { index } = space;
110
+ for (const tagKey of Object.keys(spacePropsTags)) {
111
+ if (!tags[tagKey]) {
112
+ tags[tagKey] = [];
113
+ }
114
+
115
+ if (space !== spaceValue && (spacePropsTags[tagKey].length !== 2 || spacePropsTags[tagKey][1] !== spaceValue.length - 1)) {
116
+ for (let i = 0; i < match.length / spaceValue.length; i++) {
117
+ tags[tagKey].push(...spacePropsTags[tagKey].map((rangeIdx) => index + (rangeIdx + i * spaceValue.length)));
118
+ }
119
+ } else {
120
+ tags[tagKey].push(index, index + match.length - 1);
121
+ }
122
+ }
123
+ }
124
+
125
+ return tags;
126
+ }
127
+
128
+ function applyCanaryTagRanges(result, metadata, tags) {
129
+ metadata.sourceEvents = [];
130
+ // the diff doesn't include the " that opens the regex.
131
+ let canaryReplacementDiff = 0;
132
+ // for each marker in the stringify's result, remove the marker and
133
+ // create a TagRange for the value.
134
+ return replace(result, metadata.regex, (m, id, offset) => {
135
+ // adjust offset by total characters removed so far
136
+ offset = offset - canaryReplacementDiff + 1;
137
+ // we don't replace the opening " in the regex - that just makes sure
138
+ // we only find our marker at the start of a string value.
139
+ canaryReplacementDiff += m.length - 1;
140
+ for (const tagKey of Object.keys(metadata.strInfos[id].tags)) {
141
+ if (!tags[tagKey]) {
142
+ tags[tagKey] = [];
143
+ }
144
+
145
+ for (const tagIdx of metadata.strInfos[id].tags[tagKey]) {
146
+ tags[tagKey].push(tagIdx + offset);
147
+ }
148
+ }
149
+
150
+ metadata.history.add(metadata[id]);
151
+ // replace the canary with the starting quote
152
+ return '"';
153
+ });
154
+ }
155
+
156
+ return core.assess.dataflow.propagation.jsonInstrumentation.stringify = {
157
+ install() {
158
+ patcher.patch(JSON, 'stringify', {
159
+ name: 'JSON.prototype.stringify',
160
+ patchType,
161
+ pre(data) {
162
+ if (!sources.getStore()?.assess || instrumentation.isLocked()) return;
163
+
164
+ const [input, , space] = data.args;
165
+ let [, replacer] = data.args;
166
+ replacer = patchReplacer(replacer);
167
+
168
+ // context used by the post hook.
169
+ data.metadata = {
170
+ history: new Set(),
171
+ origArgs: data.args.slice(),
172
+ strInfos: {},
173
+ propagate: false,
174
+ regex,
175
+ spaceProps: undefined,
176
+ target: undefined,
177
+ };
178
+
179
+
180
+ // if the space can't be trusted then remember space's tracking info so it
181
+ // can be applied to the entire JSON.stringify result string.
182
+ const spaceProps = getUntrustedSpaceProps(space);
183
+ if (spaceProps) {
184
+ data.metadata.spaceProps = spaceProps;
185
+ data.metadata.history.add(spaceProps);
186
+ data.metadata.propagate = true;
187
+ }
188
+
189
+ // each canary tag gets a separate id to make matching easier.
190
+ let id = 0;
191
+
192
+ /**
193
+ * wraps the replacer method and updates propagate boolean if value of replacer
194
+ * is tracked
195
+ *
196
+ * @param {string} key
197
+ * @param {string} value
198
+ */
199
+ function contrastReplacer(key, val) {
200
+ const valProperties = tracker.getData(val);
201
+ if (valProperties && Object.keys(valProperties.tags).length) {
202
+ data.metadata.propagate = true;
203
+ }
204
+
205
+ let value = replacer.call(this, key, val);
206
+
207
+ // keys aren't propagated, so check only the value
208
+ if (isString(value) && valProperties) {
209
+ data.metadata.strInfos[id] = valProperties;
210
+ value = `${canary}${id}~${value}`;
211
+ id++;
212
+ }
213
+ return value;
214
+ }
215
+
216
+ data.args = [input, contrastReplacer, space];
217
+ },
218
+ post(data) {
219
+ if (!sources.getStore()?.assess || instrumentation.isLocked()) return;
220
+ let tags = {};
221
+ const vulnerableSources = [];
222
+ if (!data.metadata?.propagate) {
223
+ return data.result;
224
+ }
225
+
226
+ const { metadata } = data;
227
+ const ret = applyCanaryTagRanges(data.result, metadata, tags);
228
+
229
+ if (Object.keys(tags).length) {
230
+ vulnerableSources.push('P0');
231
+ }
232
+
233
+ if (metadata.spaceProps) {
234
+ tags = createMergedTags(tags, createSpaceTagRanges(ret, metadata));
235
+ vulnerableSources.push('P2');
236
+ }
237
+
238
+ data.result = ret;
239
+
240
+ const method = 'JSON.stringify';
241
+ const event = createPropagationEvent({
242
+ context: method,
243
+ name: method,
244
+ history: Array.from(metadata.history),
245
+ object: {
246
+ value: inspect(data.obj),
247
+ tracked: false
248
+ },
249
+ args: [
250
+ {
251
+ value: inspect(metadata.origArgs[0]),
252
+ tracked: false
253
+ },
254
+ (metadata.origArgs[1] && {
255
+ value: inspect(metadata.origArgs[1]),
256
+ tracked: false
257
+ }),
258
+ (metadata.origArgs[2] && {
259
+ value: inspect(metadata.origArgs[2]),
260
+ tracked: !!metadata.spaceProps
261
+ })
262
+ ].filter(Boolean),
263
+ result: {
264
+ value: ret,
265
+ tracked: true
266
+ },
267
+ tags,
268
+ stacktraceOpts: {
269
+ constructorOpt: data.hooked,
270
+ prependFrames: [data.orig]
271
+ },
272
+ source: vulnerableSources.length === 1 ? vulnerableSources[0] : 'P',
273
+ target: 'R',
274
+ });
275
+
276
+ if (!event) return;
277
+
278
+ const { extern } = tracker.track(ret, event);
279
+
280
+ if (extern) {
281
+ data.result = extern;
282
+ }
283
+ },
284
+ });
285
+ },
286
+ uninstall() {
287
+ JSON.stringify = patcher.unwrap(JSON.stringify);
288
+ },
289
+ };
290
+ };
@@ -0,0 +1,79 @@
1
+ /*
2
+ * Copyright: 2022 Contrast Security, Inc
3
+ * Contact: support@contrastsecurity.com
4
+ * License: Commercial
5
+
6
+ * NOTICE: This Software and the patented inventions embodied within may only be
7
+ * used as part of Contrast Security’s commercial offerings. Even though it is
8
+ * made available through public repositories, use of this Software is subject to
9
+ * the applicable End User Licensing Agreement found at
10
+ * https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
11
+ * between Contrast Security and the End User. The Software may not be reverse
12
+ * engineered, modified, repackaged, sold, redistributed or otherwise used in a
13
+ * way not consistent with the End User License Agreement.
14
+ */
15
+ 'use strict';
16
+
17
+ const { patchType } = require('../common');
18
+
19
+ module.exports = function(core) {
20
+ const {
21
+ assess: {
22
+ dataflow: {
23
+ eventFactory,
24
+ tracker
25
+ }
26
+ },
27
+ patcher,
28
+ } = core;
29
+
30
+ return core.assess.dataflow.propagation.bufferInstrumentation = {
31
+ install() {
32
+ const name = 'global.Buffer.prototype.toString';
33
+
34
+ patcher.patch(global.Buffer.prototype, 'toString', {
35
+ patchType,
36
+ name,
37
+ post(data) {
38
+ const { hooked, obj, orig, result } = data;
39
+
40
+ if (!result) return;
41
+
42
+ const bufferInfo = tracker.getData(obj);
43
+ if (!bufferInfo) {
44
+ return;
45
+ }
46
+
47
+ const event = eventFactory.createPropagationEvent({
48
+ args: data.args.map((a) => ({ tracked: false, value: a })),
49
+ context: 'buffer.toString()',
50
+ object: { tracked: true, value: 'Buffer' },
51
+ history: [bufferInfo],
52
+ name,
53
+ result: {
54
+ tracked: true,
55
+ value: result
56
+ },
57
+ source: 'O',
58
+ tags: bufferInfo.tags,
59
+ stacktraceOpts: {
60
+ constructorOpt: hooked,
61
+ prependFrames: [orig]
62
+ },
63
+ target: 'R',
64
+ });
65
+
66
+ if (event) {
67
+ const { extern } = tracker.track(result, event);
68
+ if (extern) {
69
+ data.result = extern;
70
+ }
71
+ }
72
+ }
73
+ });
74
+ },
75
+ uninstall() {
76
+ global.Buffer.prototype.toString = patcher.unwrap(global.Buffer.prototype.toString);
77
+ }
78
+ };
79
+ };
@@ -22,7 +22,9 @@ module.exports = function(core) {
22
22
  scopes: { sources, instrumentation },
23
23
  patcher,
24
24
  assess: {
25
- dataflow: { tracker }
25
+ dataflow: {
26
+ tracker
27
+ },
26
28
  }
27
29
  } = core;
28
30
 
@@ -36,6 +38,7 @@ module.exports = function(core) {
36
38
 
37
39
  const arg = data.args[0];
38
40
  let argInfo = tracker.getData(arg);
41
+ if (tracker.getData(data.result)) return;
39
42
 
40
43
  if (data.obj && !argInfo) {
41
44
  argInfo = tracker.getData(data.result.toString());
@@ -46,6 +49,7 @@ module.exports = function(core) {
46
49
  }
47
50
 
48
51
  const { extern } = tracker.track(data.result, argInfo);
52
+
49
53
  if (extern) {
50
54
  data.result = extern;
51
55
  }
@@ -15,6 +15,9 @@
15
15
 
16
16
  'use strict';
17
17
 
18
+ const {
19
+ DataflowTag: { URL_ENCODED }
20
+ } = require('@contrast/common');
18
21
  const {
19
22
  createFullLengthCopyTags
20
23
  } = require('../../tag-utils');
@@ -48,7 +51,7 @@ module.exports = function(core) {
48
51
  const history = [argInfo];
49
52
  const newTags = createFullLengthCopyTags(argInfo.tags, result.length);
50
53
 
51
- newTags['url-encoded'] = [0, result.length - 1];
54
+ newTags[URL_ENCODED] = [0, result.length - 1];
52
55
 
53
56
  const event = createPropagationEvent({
54
57
  name: 'global.encodeURIComponent',
@@ -63,7 +66,7 @@ module.exports = function(core) {
63
66
  args: [{ value: argInfo.value, tracked: true }],
64
67
  tags: newTags,
65
68
  history,
66
- addedTags: ['url-encoded'],
69
+ addedTags: [URL_ENCODED],
67
70
  stacktraceOpts: {
68
71
  constructorOpt: hooked,
69
72
  prependFrames: [orig]
@@ -15,6 +15,9 @@
15
15
 
16
16
  'use strict';
17
17
 
18
+ const {
19
+ DataflowTag: { WEAK_URL_ENCODED }
20
+ } = require('@contrast/common');
18
21
  const {
19
22
  createFullLengthCopyTags
20
23
  } = require('../../tag-utils');
@@ -48,7 +51,7 @@ module.exports = function(core) {
48
51
  const history = [argInfo];
49
52
  const newTags = createFullLengthCopyTags(argInfo.tags, result.length);
50
53
 
51
- newTags['weak-url-encoded'] = [0, result.length - 1];
54
+ newTags[WEAK_URL_ENCODED] = [0, result.length - 1];
52
55
 
53
56
  const event = createPropagationEvent({
54
57
  name: 'pug-runtime.escape',
@@ -62,7 +65,7 @@ module.exports = function(core) {
62
65
  },
63
66
  args: [{ value: argInfo.value, tracked: true }],
64
67
  tags: newTags,
65
- addedTags: ['weak-url-encoded'],
68
+ addedTags: [WEAK_URL_ENCODED],
66
69
  history,
67
70
  stacktraceOpts: {
68
71
  constructorOpt: hooked,