@contrast/protect 1.3.0 → 1.4.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 (43) hide show
  1. package/lib/error-handlers/install/express4.js +2 -3
  2. package/lib/error-handlers/install/fastify3.js +2 -4
  3. package/lib/error-handlers/install/koa2.js +1 -2
  4. package/lib/{cli-rewriter.js → get-source-context.js} +13 -15
  5. package/lib/hardening/constants.js +20 -0
  6. package/lib/hardening/handlers.js +65 -0
  7. package/lib/hardening/index.js +29 -0
  8. package/lib/hardening/install/node-serialize0.js +59 -0
  9. package/lib/index.d.ts +3 -21
  10. package/lib/index.js +4 -0
  11. package/lib/input-analysis/handlers.js +169 -7
  12. package/lib/input-analysis/index.js +4 -0
  13. package/lib/input-analysis/install/body-parser1.js +13 -21
  14. package/lib/input-analysis/install/cookie-parser1.js +13 -15
  15. package/lib/input-analysis/install/express4.js +8 -13
  16. package/lib/input-analysis/install/fastify3.js +4 -5
  17. package/lib/input-analysis/install/formidable1.js +4 -5
  18. package/lib/input-analysis/install/http.js +12 -3
  19. package/lib/input-analysis/install/koa-body5.js +5 -10
  20. package/lib/input-analysis/install/koa-bodyparser4.js +6 -10
  21. package/lib/input-analysis/install/koa2.js +13 -24
  22. package/lib/input-analysis/install/multer1.js +5 -6
  23. package/lib/input-analysis/install/qs6.js +7 -11
  24. package/lib/input-analysis/install/universal-cookie4.js +3 -7
  25. package/lib/input-analysis/ip-analysis.js +76 -0
  26. package/lib/input-analysis/virtual-patches.js +109 -0
  27. package/lib/input-tracing/handlers/index.js +86 -22
  28. package/lib/input-tracing/index.js +10 -4
  29. package/lib/input-tracing/install/child-process.js +13 -7
  30. package/lib/input-tracing/install/eval.js +60 -0
  31. package/lib/input-tracing/install/fs.js +4 -2
  32. package/lib/input-tracing/install/http.js +63 -0
  33. package/lib/input-tracing/install/mongodb.js +20 -20
  34. package/lib/input-tracing/install/mysql.js +3 -2
  35. package/lib/input-tracing/install/postgres.js +5 -4
  36. package/lib/input-tracing/install/sequelize.js +7 -5
  37. package/lib/input-tracing/install/sqlite3.js +6 -4
  38. package/lib/input-tracing/install/vm.js +132 -0
  39. package/lib/make-source-context.js +4 -1
  40. package/lib/semantic-analysis/handlers.js +160 -0
  41. package/lib/semantic-analysis/index.js +38 -0
  42. package/package.json +7 -9
  43. package/lib/utils.js +0 -84
@@ -0,0 +1,132 @@
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 { isString, isNonEmptyObject } = require('@contrast/common');
19
+ const { patchType } = require('../constants');
20
+
21
+ module.exports = function(core) {
22
+ const {
23
+ scopes: { instrumentation },
24
+ patcher,
25
+ depHooks,
26
+ captureStacktrace,
27
+ protect,
28
+ protect: { inputTracing }
29
+ } = core;
30
+
31
+ function install() {
32
+ depHooks.resolve({ name: 'vm' }, (vm) => {
33
+ ['Script', 'createScript', 'runInContext', 'runInThisContext'].forEach(
34
+ (method) => {
35
+ const name = `vm.${method}`;
36
+
37
+ patcher.patch(vm, method, {
38
+ name,
39
+ patchType,
40
+ pre({ args, hooked, name, orig }) {
41
+ if (instrumentation.isLocked()) return;
42
+
43
+ const sourceContext = protect.getSourceContext(name);
44
+ if (!sourceContext) return;
45
+
46
+ const codeString = args[0];
47
+ if (!codeString || !isString(codeString)) return;
48
+
49
+ const sinkContext = captureStacktrace(
50
+ { name, value: codeString },
51
+ { constructorOpt: hooked, prependFrames: [orig] }
52
+ );
53
+ inputTracing.ssjsInjection(sourceContext, sinkContext);
54
+ }
55
+ });
56
+ }
57
+ );
58
+
59
+ patcher.patch(vm, 'runInNewContext', {
60
+ name: 'vm.runInNewContext',
61
+ patchType,
62
+ pre: ({ args, hooked, orig }) => {
63
+ if (instrumentation.isLocked()) return;
64
+
65
+ const sourceContext = protect.getSourceContext('vm.runInNewContext');
66
+ if (!sourceContext) return;
67
+
68
+ const codeString = args[0];
69
+ const envObj = args[1];
70
+
71
+ if ((!codeString || !isString(codeString)) && (!isNonEmptyObject(envObj))) return;
72
+
73
+ const codeStringSinkContext = (codeString && isString(codeString)) ? captureStacktrace(
74
+ { name: 'vm.runInNewContext', value: codeString },
75
+ { constructorOpt: hooked, prependFrames: [orig] }
76
+ ) : null;
77
+ const envObjSinkContext = isNonEmptyObject(envObj) ? captureStacktrace(
78
+ { name: 'vm.runInNewContext', value: envObj },
79
+ { constructorOpt: hooked, prependFrames: [orig] }
80
+ ) : null;
81
+
82
+ codeStringSinkContext && inputTracing.ssjsInjection(sourceContext, codeStringSinkContext);
83
+ envObjSinkContext && inputTracing.ssjsInjection(sourceContext, envObjSinkContext);
84
+ }
85
+ });
86
+
87
+ patcher.patch(vm, 'createContext', {
88
+ name: 'vm.createContext',
89
+ patchType,
90
+ pre: ({ args, hooked, orig }) => {
91
+ if (instrumentation.isLocked()) return;
92
+
93
+ const sourceContext = protect.getSourceContext('vm.createContext');
94
+ if (!sourceContext) return;
95
+
96
+ const envObj = args[0];
97
+ if (!isNonEmptyObject(envObj)) return;
98
+
99
+ const sinkContext = captureStacktrace(
100
+ { name: 'vm.createContext', value: envObj },
101
+ { constructorOpt: hooked, prependFrames: [orig] }
102
+ );
103
+ inputTracing.ssjsInjection(sourceContext, sinkContext);
104
+ }
105
+ });
106
+
107
+ patcher.patch(vm.Script.prototype, 'runInNewContext', {
108
+ name: 'vm.Script.prototype.runInNewContext',
109
+ patchType,
110
+ pre: ({ args, hooked, orig }) => {
111
+ if (instrumentation.isLocked()) return;
112
+
113
+ const sourceContext = protect.getSourceContext('vm.Script.prototype.runInNewContext');
114
+ if (!sourceContext) return;
115
+
116
+ const envObj = args[0];
117
+ if (!isNonEmptyObject(envObj)) return;
118
+
119
+ const sinkContext = captureStacktrace(
120
+ { name: 'vm.Script.prototype.runInNewContext', value: envObj },
121
+ { constructorOpt: hooked, prependFrames: [orig] }
122
+ );
123
+ inputTracing.ssjsInjection(sourceContext, sinkContext);
124
+ }
125
+ });
126
+ });
127
+ }
128
+
129
+ const vmInstrumentation = inputTracing.vmInstrumentation = { install };
130
+
131
+ return vmInstrumentation;
132
+ };
@@ -83,7 +83,7 @@ module.exports = function(core) {
83
83
  // particular request (if any route exclusions, etc.)
84
84
  rules: core.protect.rules,
85
85
  exclusions: [],
86
- virtualPatches: [],
86
+ virtualPatchesEvaluators: [],
87
87
 
88
88
  // maybe better as result, findings... but my bad naming choice is
89
89
  // past the point of return.
@@ -94,6 +94,9 @@ module.exports = function(core) {
94
94
  // successfully.
95
95
  bodyType: undefined,
96
96
  resultsMap: Object.create(null),
97
+ hardeningResultsMap: Object.create(null),
98
+ semanticResultsMap: Object.create(null),
99
+ serverFeaturesResultsMap: Object.create(null)
97
100
  },
98
101
 
99
102
  /*
@@ -0,0 +1,160 @@
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
+ BLOCKING_MODES,
20
+ InputType,
21
+ isString,
22
+ simpleTraverse
23
+ } = require('@contrast/common');
24
+
25
+ const SINK_EXPLOIT_PATTERN_START = /(?:^|\\|\/)(?:sh|bash|zsh|ksh|tcsh|csh|fish|cmd)/;
26
+ const stripWhiteSpace = (str) => str.replace(/\s/g, '');
27
+
28
+ // The sink instrumentation for this rule is in `protect/lib/input-tracing/install/child-process.js
29
+ module.exports = function(core) {
30
+ const { protect: { agentLib, semanticAnalysis, throwSecurityException } } = core;
31
+
32
+ function handleResult(sourceContext, sinkContext, ruleId, mode, finding) {
33
+ const sinkResults = sourceContext.findings.semanticResultsMap[ruleId];
34
+ const result = {
35
+ blocked: false,
36
+ findings: { command: sinkContext.value },
37
+ sinkContext,
38
+ ...finding
39
+ };
40
+
41
+ sourceContext.findings.semanticResultsMap[ruleId] = sinkResults ? [...sinkResults, result] : [result];
42
+
43
+ if (BLOCKING_MODES.includes(mode)) {
44
+ result.blocked = true;
45
+ const blockInfo = [mode, ruleId];
46
+ sourceContext.findings.securityException = blockInfo;
47
+ throwSecurityException(sourceContext);
48
+ }
49
+ }
50
+
51
+ semanticAnalysis.handleCmdInjectionSemanticDangerous = function(sourceContext, sinkContext) {
52
+ const ruleId = 'cmd-injection-semantic-dangerous-paths';
53
+ const { mode } = sourceContext.rules.agentRules[ruleId];
54
+
55
+ if (mode == 'off') return;
56
+
57
+ const result = agentLib.containsDangerousPath(sinkContext.value);
58
+
59
+ if (result) {
60
+ handleResult(sourceContext, sinkContext, ruleId, mode);
61
+ }
62
+ };
63
+
64
+ semanticAnalysis.handleCmdInjectionSemanticChainedCommands = function(sourceContext, sinkContext) {
65
+ const ruleId = 'cmd-injection-semantic-chained-commands';
66
+ const { mode } = sourceContext.rules.agentRules[ruleId];
67
+
68
+ if (mode == 'off') return;
69
+
70
+ const indexOfChaining = agentLib.indexOfChaining(sinkContext.value);
71
+
72
+ if (indexOfChaining != -1) {
73
+ handleResult(sourceContext, sinkContext, ruleId, mode);
74
+ }
75
+ };
76
+
77
+ semanticAnalysis.handleCommandInjectionCommandBackdoors = function(sourceContext, sinkContext) {
78
+ const ruleId = 'cmd-injection-command-backdoors';
79
+ const { mode } = sourceContext.rules.agentRules[ruleId];
80
+
81
+ if (mode == 'off') return;
82
+
83
+ const finding = findBackdoorInjection(sourceContext, sinkContext.value);
84
+
85
+ if (finding) {
86
+ handleResult(sourceContext, sinkContext, ruleId, mode, finding);
87
+ }
88
+ };
89
+
90
+ return semanticAnalysis;
91
+ };
92
+
93
+ /**
94
+ * Backdoor detection logic:
95
+ * - command is >= 2 chars
96
+ * - iterates over every piece of request and checks
97
+ * - the full value is the param to sink
98
+ * - the value matches a regex and ends the param to the sink
99
+ */
100
+ function findBackdoorInjection(sourceContext, command) {
101
+ if (command?.length < 2) {
102
+ return null;
103
+ }
104
+
105
+ const valuesOfInterest = {
106
+ [InputType.QUERYSTRING]: sourceContext.parsedQuery,
107
+ [InputType.PARAMETER_VALUE]: sourceContext.parsedParams,
108
+ [InputType.BODY]: sourceContext.parsedBody,
109
+ [InputType.COOKIE_VALUE]: sourceContext.parsedCookies,
110
+ [InputType.HEADER]: sourceContext.reqData.headers,
111
+ };
112
+
113
+ let found = false;
114
+ for (let inputType in valuesOfInterest) {
115
+ const values = valuesOfInterest[inputType];
116
+
117
+ if (values && Object.keys(values).length) {
118
+ simpleTraverse(values, (path, type, value, obj) => {
119
+ if (
120
+ !found &&
121
+ value &&
122
+ type === 'Value' &&
123
+ isString(value) &&
124
+ isBackdoorDetected(value, command)
125
+ ) {
126
+ let key;
127
+ key = inputType === InputType.HEADER ? obj.indexOf(command) - 1 : path[path.length - 1];
128
+ if (Number.isInteger(key) && obj[key]) {
129
+ key = obj[key];
130
+ }
131
+ path = path.length === 1 ? [] : Array.from(path).slice(0, path.length - 1);
132
+ inputType = path.length > 1 ? InputType.JSON_VALUE : inputType;
133
+
134
+ found = { key, inputType, path, value: command };
135
+ }
136
+ });
137
+ }
138
+ }
139
+
140
+ return found;
141
+ }
142
+
143
+ /**
144
+ * strips the whitespace of the request value and the command,
145
+ * checks if the command equals the request value
146
+ * or if the command looks like the start of a shell execution
147
+ * and ends with the request value passed to the sink
148
+ *
149
+ * @param {string} value from request key
150
+ */
151
+ function isBackdoorDetected(requestValue, command) {
152
+ const normalizedValue = stripWhiteSpace(requestValue);
153
+ const normalizedCommand = stripWhiteSpace(command);
154
+
155
+ return (
156
+ normalizedValue === normalizedCommand ||
157
+ (normalizedCommand.endsWith(normalizedValue) &&
158
+ SINK_EXPLOIT_PATTERN_START.test(normalizedCommand))
159
+ );
160
+ }
@@ -0,0 +1,38 @@
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
+ /**
19
+ * SEMANTIC ANALYSIS is a STAGE of Protect.
20
+ * The information about it can be found under some of the separate rules we support for this stage:
21
+ * https://protect-spec.prod.dotnet.contsec.com/rules/cmd-injection-semantic-dangerous-paths.html#semantic-analysis
22
+ * https://protect-spec.prod.dotnet.contsec.com/rules/cmd-injection-semantic-chained-commands.html#semantic-analysis
23
+ *
24
+ * To view other STAGES see https://protect-spec.prod.dotnet.contsec.com/guide/protect-types.html#protection-types
25
+ * @param {object} core composed dependencies
26
+ * @returns {object}
27
+ */
28
+ module.exports = function(core) {
29
+ const semanticAnalysis = core.protect.semanticAnalysis = {};
30
+
31
+ // load the interfaces that will be used by input tracing instrumentation
32
+ require('./handlers')(core);
33
+
34
+ // There is no `.install()` method as this STAGE does not introduce side effects on its own,
35
+ // it uses the instrumentation that's already in place for INPUT TRACING.
36
+
37
+ return semanticAnalysis;
38
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrast/protect",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Contrast service providing framework-agnostic Protect support",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Contrast Security <nodejs@contrastsecurity.com> (https://www.contrastsecurity.com)",
@@ -9,9 +9,6 @@
9
9
  ],
10
10
  "main": "lib/index.js",
11
11
  "types": "lib/index.d.ts",
12
- "bin": {
13
- "contrast-transpile": "lib/cli-rewriter.js"
14
- },
15
12
  "engines": {
16
13
  "npm": ">= 8.4.0",
17
14
  "node": ">= 14.15.0"
@@ -22,12 +19,13 @@
22
19
  "dependencies": {
23
20
  "@babel/template": "^7.16.7",
24
21
  "@babel/types": "^7.16.8",
25
- "@contrast/agent-lib": "^4.2.0",
26
- "@contrast/common": "1.0.3",
27
- "@contrast/core": "1.2.0",
28
- "@contrast/scopes": "1.1.0",
29
- "@contrast/esm-hooks": "1.1.3",
22
+ "@contrast/agent-lib": "^5.0.0",
23
+ "@contrast/common": "1.1.0",
24
+ "@contrast/core": "1.3.0",
25
+ "@contrast/esm-hooks": "1.1.4",
26
+ "@contrast/scopes": "1.1.1",
30
27
  "builtin-modules": "^3.2.0",
28
+ "ipaddr.js": "^2.0.1",
31
29
  "semver": "^7.3.7"
32
30
  }
33
31
  }
package/lib/utils.js DELETED
@@ -1,84 +0,0 @@
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
- /**
19
- * simpleTraverse() walks an object and calls a user function for each key
20
- * and string value. It is a "simple traverse" in that it
21
- * 1) doesn't make value callbacks unless the value is a non-empty string
22
- * 2) it only recognizes items that can be expressed in JSON, i.e., POJO
23
- * and arrays.
24
- * 3) it doesn't make callbacks for array indexes (though they appear in
25
- * the path). array indexes are always numeric and are not a threat.
26
- *
27
- * N.B. the path array that is passed to the callback is a dynamic path; new
28
- * keys are pushed and popped onto the path as simpleTraverse() walks the
29
- * object. in order to capture the path at the time of the callback, the
30
- * callback must copy the array, e.g., `path.slice()`, in order to "freeze"
31
- * it at the time of the callback. the reason for this is that most keys/values
32
- * are not going to be of interest, and there is no reason to create a new array
33
- * unless the key/value is of interest.
34
- *
35
- * @param {Object} obj the object to traverse
36
- * @param {Function} cb(path, type, value) is called for each non-array-index key
37
- * and string value. It is not called for non-string or empty-string Values.
38
- * path {[String]} the path prior to the 'Key' or 'Value'; includes array indexes.
39
- * type {String} 'Key' or 'Value'
40
- * value {String} the Key or Leaf string
41
- *
42
- */
43
- function simpleTraverse(obj, cb) {
44
- if (typeof obj !== 'object' || obj === null) {
45
- return;
46
- }
47
- const path = [];
48
- /* eslint-disable complexity */
49
- function traverse(obj) {
50
- const isArray = Array.isArray(obj);
51
- for (const k in obj) {
52
- if (isArray) {
53
- // if it is an array, store each index in path but don't call the
54
- // callback on the index itself as they are just numeric strings.
55
- path.push(k);
56
- if (typeof obj[k] === 'object' && obj[k] !== null) {
57
- traverse(obj[k]);
58
- } else if (typeof obj[k] === 'string' && obj[k]) {
59
- cb(path, 'Value', obj[k]);
60
- }
61
- path.pop();
62
- } else if (typeof obj[k] === 'object' && obj[k] !== null) {
63
- cb(path, 'Key', k);
64
- path.push(k);
65
- traverse(obj[k]);
66
- path.pop();
67
- } else {
68
- cb(path, 'Key', k);
69
- // only callback if the value is a non-empty string
70
- if (typeof obj[k] === 'string' && obj[k]) {
71
- path.push(k);
72
- cb(path, 'Value', obj[k]);
73
- path.pop();
74
- }
75
- }
76
- }
77
- }
78
-
79
- traverse(obj);
80
- }
81
-
82
- module.exports = {
83
- simpleTraverse,
84
- };