@newrelic/security-agent 1.1.1 → 1.2.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+
2
+ ### v1.2.0 (2024-04-12)
3
+ #### Features
4
+ * Added instrumentation for express framework's res.download() and res.sendFile()
5
+ #### Bug fixes
6
+ * Handling to decrypt fuzz header data for IAST scanning
7
+ * Logging and snapshot file fixes
8
+ #### Miscellaneous chores
9
+ * Prepend vulnerability case type with apiId
10
+ * Updated jsonVersion to v1.2.0
11
+ * Bumped undici from 5.28.3 to 5.28.4
12
+
1
13
  ### v1.1.1 (2024-03-21)
2
14
  #### Bug fixes
3
15
  * Reverted IAST support for gRPC.
@@ -14,6 +14,7 @@ code, the source code can be found at [https://github.com/newrelic/csec-node-age
14
14
 
15
15
  **[dependencies](#dependencies)**
16
16
 
17
+ * [@newrelic/newrelic-plugin-oss-third-party](#newrelicnewrelic-plugin-oss-third-party)
17
18
  * [axios](#axios)
18
19
  * [check-disk-space](#check-disk-space)
19
20
  * [content-type](#content-type)
@@ -74,6 +75,214 @@ code, the source code can be found at [https://github.com/newrelic/csec-node-age
74
75
 
75
76
  ## dependencies
76
77
 
78
+ ### @newrelic/newrelic-plugin-oss-third-party
79
+
80
+ This product includes source derived from [@newrelic/newrelic-plugin-oss-third-party](https://github.com/newrelic/newrelic-oss-cli) ([v0.1.2](https://github.com/newrelic/newrelic-oss-cli/tree/v0.1.2)), distributed under the [Apache-2.0 License](https://github.com/newrelic/newrelic-oss-cli/blob/v0.1.2/LICENSE):
81
+
82
+ ```
83
+ Apache License
84
+ Version 2.0, January 2004
85
+ http://www.apache.org/licenses/
86
+
87
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
88
+
89
+ 1. Definitions.
90
+
91
+ "License" shall mean the terms and conditions for use, reproduction,
92
+ and distribution as defined by Sections 1 through 9 of this document.
93
+
94
+ "Licensor" shall mean the copyright owner or entity authorized by
95
+ the copyright owner that is granting the License.
96
+
97
+ "Legal Entity" shall mean the union of the acting entity and all
98
+ other entities that control, are controlled by, or are under common
99
+ control with that entity. For the purposes of this definition,
100
+ "control" means (i) the power, direct or indirect, to cause the
101
+ direction or management of such entity, whether by contract or
102
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
103
+ outstanding shares, or (iii) beneficial ownership of such entity.
104
+
105
+ "You" (or "Your") shall mean an individual or Legal Entity
106
+ exercising permissions granted by this License.
107
+
108
+ "Source" form shall mean the preferred form for making modifications,
109
+ including but not limited to software source code, documentation
110
+ source, and configuration files.
111
+
112
+ "Object" form shall mean any form resulting from mechanical
113
+ transformation or translation of a Source form, including but
114
+ not limited to compiled object code, generated documentation,
115
+ and conversions to other media types.
116
+
117
+ "Work" shall mean the work of authorship, whether in Source or
118
+ Object form, made available under the License, as indicated by a
119
+ copyright notice that is included in or attached to the work
120
+ (an example is provided in the Appendix below).
121
+
122
+ "Derivative Works" shall mean any work, whether in Source or Object
123
+ form, that is based on (or derived from) the Work and for which the
124
+ editorial revisions, annotations, elaborations, or other modifications
125
+ represent, as a whole, an original work of authorship. For the purposes
126
+ of this License, Derivative Works shall not include works that remain
127
+ separable from, or merely link (or bind by name) to the interfaces of,
128
+ the Work and Derivative Works thereof.
129
+
130
+ "Contribution" shall mean any work of authorship, including
131
+ the original version of the Work and any modifications or additions
132
+ to that Work or Derivative Works thereof, that is intentionally
133
+ submitted to Licensor for inclusion in the Work by the copyright owner
134
+ or by an individual or Legal Entity authorized to submit on behalf of
135
+ the copyright owner. For the purposes of this definition, "submitted"
136
+ means any form of electronic, verbal, or written communication sent
137
+ to the Licensor or its representatives, including but not limited to
138
+ communication on electronic mailing lists, source code control systems,
139
+ and issue tracking systems that are managed by, or on behalf of, the
140
+ Licensor for the purpose of discussing and improving the Work, but
141
+ excluding communication that is conspicuously marked or otherwise
142
+ designated in writing by the copyright owner as "Not a Contribution."
143
+
144
+ "Contributor" shall mean Licensor and any individual or Legal Entity
145
+ on behalf of whom a Contribution has been received by Licensor and
146
+ subsequently incorporated within the Work.
147
+
148
+ 2. Grant of Copyright License. Subject to the terms and conditions of
149
+ this License, each Contributor hereby grants to You a perpetual,
150
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
151
+ copyright license to reproduce, prepare Derivative Works of,
152
+ publicly display, publicly perform, sublicense, and distribute the
153
+ Work and such Derivative Works in Source or Object form.
154
+
155
+ 3. Grant of Patent License. Subject to the terms and conditions of
156
+ this License, each Contributor hereby grants to You a perpetual,
157
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
158
+ (except as stated in this section) patent license to make, have made,
159
+ use, offer to sell, sell, import, and otherwise transfer the Work,
160
+ where such license applies only to those patent claims licensable
161
+ by such Contributor that are necessarily infringed by their
162
+ Contribution(s) alone or by combination of their Contribution(s)
163
+ with the Work to which such Contribution(s) was submitted. If You
164
+ institute patent litigation against any entity (including a
165
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
166
+ or a Contribution incorporated within the Work constitutes direct
167
+ or contributory patent infringement, then any patent licenses
168
+ granted to You under this License for that Work shall terminate
169
+ as of the date such litigation is filed.
170
+
171
+ 4. Redistribution. You may reproduce and distribute copies of the
172
+ Work or Derivative Works thereof in any medium, with or without
173
+ modifications, and in Source or Object form, provided that You
174
+ meet the following conditions:
175
+
176
+ (a) You must give any other recipients of the Work or
177
+ Derivative Works a copy of this License; and
178
+
179
+ (b) You must cause any modified files to carry prominent notices
180
+ stating that You changed the files; and
181
+
182
+ (c) You must retain, in the Source form of any Derivative Works
183
+ that You distribute, all copyright, patent, trademark, and
184
+ attribution notices from the Source form of the Work,
185
+ excluding those notices that do not pertain to any part of
186
+ the Derivative Works; and
187
+
188
+ (d) If the Work includes a "NOTICE" text file as part of its
189
+ distribution, then any Derivative Works that You distribute must
190
+ include a readable copy of the attribution notices contained
191
+ within such NOTICE file, excluding those notices that do not
192
+ pertain to any part of the Derivative Works, in at least one
193
+ of the following places: within a NOTICE text file distributed
194
+ as part of the Derivative Works; within the Source form or
195
+ documentation, if provided along with the Derivative Works; or,
196
+ within a display generated by the Derivative Works, if and
197
+ wherever such third-party notices normally appear. The contents
198
+ of the NOTICE file are for informational purposes only and
199
+ do not modify the License. You may add Your own attribution
200
+ notices within Derivative Works that You distribute, alongside
201
+ or as an addendum to the NOTICE text from the Work, provided
202
+ that such additional attribution notices cannot be construed
203
+ as modifying the License.
204
+
205
+ You may add Your own copyright statement to Your modifications and
206
+ may provide additional or different license terms and conditions
207
+ for use, reproduction, or distribution of Your modifications, or
208
+ for any such Derivative Works as a whole, provided Your use,
209
+ reproduction, and distribution of the Work otherwise complies with
210
+ the conditions stated in this License.
211
+
212
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
213
+ any Contribution intentionally submitted for inclusion in the Work
214
+ by You to the Licensor shall be under the terms and conditions of
215
+ this License, without any additional terms or conditions.
216
+ Notwithstanding the above, nothing herein shall supersede or modify
217
+ the terms of any separate license agreement you may have executed
218
+ with Licensor regarding such Contributions.
219
+
220
+ 6. Trademarks. This License does not grant permission to use the trade
221
+ names, trademarks, service marks, or product names of the Licensor,
222
+ except as required for reasonable and customary use in describing the
223
+ origin of the Work and reproducing the content of the NOTICE file.
224
+
225
+ 7. Disclaimer of Warranty. Unless required by applicable law or
226
+ agreed to in writing, Licensor provides the Work (and each
227
+ Contributor provides its Contributions) on an "AS IS" BASIS,
228
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
229
+ implied, including, without limitation, any warranties or conditions
230
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
231
+ PARTICULAR PURPOSE. You are solely responsible for determining the
232
+ appropriateness of using or redistributing the Work and assume any
233
+ risks associated with Your exercise of permissions under this License.
234
+
235
+ 8. Limitation of Liability. In no event and under no legal theory,
236
+ whether in tort (including negligence), contract, or otherwise,
237
+ unless required by applicable law (such as deliberate and grossly
238
+ negligent acts) or agreed to in writing, shall any Contributor be
239
+ liable to You for damages, including any direct, indirect, special,
240
+ incidental, or consequential damages of any character arising as a
241
+ result of this License or out of the use or inability to use the
242
+ Work (including but not limited to damages for loss of goodwill,
243
+ work stoppage, computer failure or malfunction, or any and all
244
+ other commercial damages or losses), even if such Contributor
245
+ has been advised of the possibility of such damages.
246
+
247
+ 9. Accepting Warranty or Additional Liability. While redistributing
248
+ the Work or Derivative Works thereof, You may choose to offer,
249
+ and charge a fee for, acceptance of support, warranty, indemnity,
250
+ or other liability obligations and/or rights consistent with this
251
+ License. However, in accepting such obligations, You may act only
252
+ on Your own behalf and on Your sole responsibility, not on behalf
253
+ of any other Contributor, and only if You agree to indemnify,
254
+ defend, and hold each Contributor harmless for any liability
255
+ incurred by, or claims asserted against, such Contributor by reason
256
+ of your accepting any such warranty or additional liability.
257
+
258
+ END OF TERMS AND CONDITIONS
259
+
260
+ APPENDIX: How to apply the Apache License to your work.
261
+
262
+ To apply the Apache License to your work, attach the following
263
+ boilerplate notice, with the fields enclosed by brackets "[]"
264
+ replaced with your own identifying information. (Don't include
265
+ the brackets!) The text should be enclosed in the appropriate
266
+ comment syntax for the file format. We also recommend that a
267
+ file or class name and description of purpose be included on the
268
+ same "printed page" as the copyright notice for easier
269
+ identification within third-party archives.
270
+
271
+ Copyright [yyyy] [name of copyright owner]
272
+
273
+ Licensed under the Apache License, Version 2.0 (the "License");
274
+ you may not use this file except in compliance with the License.
275
+ You may obtain a copy of the License at
276
+
277
+ http://www.apache.org/licenses/LICENSE-2.0
278
+
279
+ Unless required by applicable law or agreed to in writing, software
280
+ distributed under the License is distributed on an "AS IS" BASIS,
281
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
282
+ See the License for the specific language governing permissions and
283
+ limitations under the License.
284
+ ```
285
+
77
286
  ### axios
78
287
 
79
288
  This product includes source derived from [axios](https://github.com/axios/axios) ([v1.6.8](https://github.com/axios/axios/tree/v1.6.8)), distributed under the [MIT License](https://github.com/axios/axios/blob/v1.6.8/LICENSE):
@@ -2631,7 +2840,7 @@ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2631
2840
 
2632
2841
  ### undici
2633
2842
 
2634
- This product includes source derived from [undici](https://github.com/nodejs/undici) ([v5.28.3](https://github.com/nodejs/undici/tree/v5.28.3)), distributed under the [MIT License](https://github.com/nodejs/undici/blob/v5.28.3/LICENSE):
2843
+ This product includes source derived from [undici](https://github.com/nodejs/undici) ([v5.28.4](https://github.com/nodejs/undici/tree/v5.28.4)), distributed under the [MIT License](https://github.com/nodejs/undici/blob/v5.28.4/LICENSE):
2635
2844
 
2636
2845
  ```
2637
2846
  MIT License
@@ -54,6 +54,7 @@ module.exports = {
54
54
  DOUBLE_DOLLAR: '$$',
55
55
  LOADING_MODULE: 'Loading module ',
56
56
  EMPTY_STRING: '',
57
+ COMMA: ',',
57
58
  QUESTION_MARK: '?',
58
59
  DOUBLE_PIPE: '||',
59
60
  DOTDOTSLASH: '../',
@@ -9,10 +9,11 @@ const secTrace = require('./sec-trace');
9
9
  const requestManager = require('./request-manager');
10
10
  const routeManager = require('./route-manager');
11
11
  const async_hooks = require('async_hooks');
12
+ const crypto = require('crypto');
12
13
 
13
- let AGENT_DIR = path.join(__dirname, '../../');
14
+ let AGENT_DIR = path.join(__dirname, '../../');
14
15
 
15
- if(process.platform == 'win32'){
16
+ if (process.platform == 'win32') {
16
17
  AGENT_DIR = path.join(__dirname, "..\\..\\");
17
18
  }
18
19
  const NR_LIB = '/newrelic/lib';
@@ -36,10 +37,11 @@ const API = require("../../nr-security-api");
36
37
  const logger = API.getLogger();
37
38
 
38
39
  createSkipList();
39
- const fs = require('fs');
40
+ const fs = require('fs');
40
41
  const cp = require('child_process');
41
42
  const requestIp = require('request-ip');
42
- const URL = require('url')
43
+ const URL = require('url');
44
+ const { EMPTY_STR } = require('./constants');
43
45
 
44
46
  /**
45
47
  * Creates a list of loaded internal modules,
@@ -47,7 +49,7 @@ const URL = require('url')
47
49
  *
48
50
  * @returns {Array} loadList
49
51
  */
50
- function createSkipList () {
52
+ function createSkipList() {
51
53
  let loadList = [];
52
54
  process.moduleLoadList.forEach(function (loadString) {
53
55
  loadList.push(loadString.split(SPACE_CHARACTER).pop());
@@ -63,7 +65,7 @@ const URL = require('url')
63
65
  }
64
66
 
65
67
 
66
- function getTraceObject (shim) {
68
+ function getTraceObject(shim) {
67
69
  const trace = stackTraceModule.get();
68
70
  const traceLength = 10;
69
71
  const stkTrace = [];
@@ -81,18 +83,18 @@ function getTraceObject (shim) {
81
83
  const request = requestManager.getRequest(shim);
82
84
  const key = request.method + ATTHERATE + request.uri;
83
85
  const routeFile = routeManager.getRoute(key);
84
- if(routeFile){
86
+ if (routeFile) {
85
87
  stkTrace.push(routeFile);
86
88
  }
87
- const sourceDetails = secTrace.getSourceDetailsFromTrace(trace,__filename, stkTrace);
89
+ const sourceDetails = secTrace.getSourceDetailsFromTrace(trace, __filename, stkTrace);
88
90
  const traceObject = {
89
- sourceDetails:sourceDetails,
91
+ sourceDetails: sourceDetails,
90
92
  stacktrace: stkTrace
91
93
  }
92
94
  return traceObject;
93
95
  }
94
96
 
95
- function getTraceObjectFallback (request) {
97
+ function getTraceObjectFallback(request) {
96
98
  const trace = stackTraceModule.get();
97
99
  const traceLength = 10;
98
100
  const stkTrace = [];
@@ -109,19 +111,19 @@ function getTraceObjectFallback (request) {
109
111
  }
110
112
  const key = request.method + ATTHERATE + request.uri;
111
113
  const routeFile = routeManager.getRoute(key);
112
- if(routeFile){
114
+ if (routeFile) {
113
115
  stkTrace.push(routeFile);
114
116
  }
115
- const sourceDetails = secTrace.getSourceDetailsFromTrace(trace,__filename, stkTrace);
117
+ const sourceDetails = secTrace.getSourceDetailsFromTrace(trace, __filename, stkTrace);
116
118
  const traceObject = {
117
- sourceDetails:sourceDetails,
119
+ sourceDetails: sourceDetails,
118
120
  stacktrace: stkTrace
119
121
  }
120
122
  return traceObject;
121
123
  }
122
124
 
123
125
 
124
- function traceElementForRoute () {
126
+ function traceElementForRoute() {
125
127
  const stkTrace = [];
126
128
  const trace = stackTraceModule.get();
127
129
  let methodName = null;
@@ -130,7 +132,7 @@ function traceElementForRoute () {
130
132
  const funcName = trace[i].getFunctionName();
131
133
  const fileName = trace[i].getFileName();
132
134
  const lineNumber = trace[i].getLineNumber();
133
- if(i>0){
135
+ if (i > 0) {
134
136
  methodName = trace[i - 1].getMethodName();
135
137
  }
136
138
 
@@ -143,11 +145,11 @@ function traceElementForRoute () {
143
145
  return stkTrace;
144
146
  }
145
147
 
146
- function getExecutionId(){
148
+ function getExecutionId() {
147
149
  return async_hooks.executionAsyncId();
148
150
  }
149
151
 
150
- function createPathIfNotExist (dir) {
152
+ function createPathIfNotExist(dir) {
151
153
  try {
152
154
  if (!fs.existsSync(dir)) {
153
155
  fs.mkdirSync(dir, 770, { recursive: true });
@@ -169,49 +171,87 @@ function createPathIfNotExist (dir) {
169
171
  */
170
172
  function addRequestData(shim, request) {
171
173
  try {
172
- const data = Object.assign({});
173
- const segment = shim.getActiveSegment();
174
- if (segment && segment.transaction) {
175
- data.protocol = (request.connection && request.connection.encrypted) ? 'https' : 'http';
176
- data.body = null;
177
- data.headers = request.headers;
178
- data.url = request.url;
179
- data.method = request.method;
180
- data.httpVersion = request.httpVersion;
181
- data.serverPort = segment.transaction.port;
182
- data.contextPath = '/';
183
- const queryObject = URL.parse(request.url, true).query;
184
- data.parameterMap = {};
185
- if (queryObject) {
186
- Object.keys(queryObject).forEach(function (key) {
187
- if (queryObject[key]) {
188
- if (!data.parameterMap[key]) {
189
- data.parameterMap[key] = new Array(queryObject[key].toString());
190
- }
174
+ const data = Object.assign({});
175
+ const segment = shim.getActiveSegment();
176
+ if (segment && segment.transaction) {
177
+ data.protocol = (request.connection && request.connection.encrypted) ? 'https' : 'http';
178
+ data.body = null;
179
+ data.headers = request.headers;
180
+ data.url = request.url;
181
+ data.method = request.method;
182
+ data.httpVersion = request.httpVersion;
183
+ data.serverPort = segment.transaction.port;
184
+ data.contextPath = '/';
185
+ const queryObject = URL.parse(request.url, true).query;
186
+ data.parameterMap = {};
187
+ if (queryObject) {
188
+ Object.keys(queryObject).forEach(function (key) {
189
+ if (queryObject[key]) {
190
+ if (!data.parameterMap[key]) {
191
+ data.parameterMap[key] = new Array(queryObject[key].toString());
192
+ }
193
+ }
194
+ });
195
+ }
196
+ data.clientIP = requestIp.getClientIp(request);
197
+ const transactionId = segment.transaction.id;
198
+ const storedRequest = requestManager.getRequestFromId(transactionId);
199
+ if (storedRequest && storedRequest.uri) {
200
+ data.uri = storedRequest.uri;
201
+ data.parameterMap = storedRequest.parameterMap;
202
+ }
203
+ requestManager.setRequest(transactionId, data);
204
+ if (shim.agent.getLinkingMetadata()) {
205
+ let linkingMetadata = shim.agent.getLinkingMetadata();
206
+ if (linkingMetadata['trace.id']) {
207
+ let traceId = linkingMetadata['trace.id'];
208
+ requestManager.setRequest(traceId, data)
209
+ }
191
210
  }
192
- });
193
211
  }
194
- data.clientIP = requestIp.getClientIp(request);
195
- const transactionId = segment.transaction.id;
196
- const storedRequest = requestManager.getRequestFromId(transactionId);
197
- if (storedRequest && storedRequest.uri) {
198
- data.uri = storedRequest.uri;
199
- data.parameterMap = storedRequest.parameterMap;
212
+ } catch (error) {
213
+ logger.debug("Error while preparing incoming request:", error);
214
+ }
215
+ }
216
+
217
+ function decryptData(encryptedData) {
218
+ let decryptedData = EMPTY_STR;
219
+ try {
220
+
221
+ const linkingMetadata = API.newrelic.getLinkingMetadata();
222
+ let entityGuid = linkingMetadata['entity.guid'];
223
+ let password = entityGuid;
224
+ let salt = password.slice(0, 16);
225
+ //derive key
226
+ const key = crypto.pbkdf2Sync(password, salt, 1024, 32, 'sha1');
227
+ const decipher = crypto.createDecipheriv('aes-256-cbc', key, Buffer.alloc(16));
228
+ let decrypted = decipher.update(encryptedData, 'hex');
229
+ decrypted += decipher.final();
230
+ decryptedData = decrypted.slice(16, decrypted.length);
231
+ } catch (error) {
232
+ logger.debug("Error while decrypting the data:", error);
233
+ }
234
+ return decryptedData;
235
+
236
+ }
237
+
238
+ function hashVerifier(decryptedData, hashFromSE) {
239
+ let flag = false;
240
+ try {
241
+ const hash = crypto.createHash('sha256'); // Create a new hash object
242
+ hash.update(decryptedData); // Write data to the hash object
243
+ let calculatedSHA256Hash = hash.digest('hex');
244
+ if (calculatedSHA256Hash === hashFromSE) {
245
+ flag = true;
200
246
  }
201
- requestManager.setRequest(transactionId, data);
202
- if(shim.agent.getLinkingMetadata()){
203
- let linkingMetadata = shim.agent.getLinkingMetadata();
204
- if(linkingMetadata['trace.id']){
205
- let traceId = linkingMetadata['trace.id'];
206
- requestManager.setRequest(traceId, data)
207
- }
208
- }
209
- }
210
247
  } catch (error) {
211
- logger.debug("Error while preparing incoming request:", error);
212
- }
213
- }
214
-
248
+ logger.debug("Error while calculating SHA256 of decrypted data:", error);
249
+ }
250
+
251
+ return flag;
252
+
253
+ }
254
+
215
255
 
216
256
  module.exports = {
217
257
  getTraceObject,
@@ -219,5 +259,7 @@ module.exports = {
219
259
  getExecutionId,
220
260
  createPathIfNotExist,
221
261
  getTraceObjectFallback,
222
- addRequestData
262
+ addRequestData,
263
+ decryptData,
264
+ hashVerifier
223
265
  }
@@ -18,8 +18,11 @@ const lodash = require('lodash');
18
18
  const routeManager = require('../../core/route-manager');
19
19
  const API = require("../../../nr-security-api");
20
20
  const logger = API.getLogger();
21
+ const { EVENT_TYPE, EVENT_CATEGORY } = require('../../core/event-constants');
22
+ const { STRING } = require('../../core/constants');
23
+ const securityMetaData = require('../../core/security-metadata');
21
24
 
22
- module.exports = function initialize(shim, express, moduleName) {
25
+ module.exports = function initialize(shim, express) {
23
26
  logger.info("Instrumenting express")
24
27
  if (!express || !express.Router) {
25
28
  return false
@@ -28,7 +31,8 @@ module.exports = function initialize(shim, express, moduleName) {
28
31
  if (express.Router.use) {
29
32
  wrapExpress4(shim, express)
30
33
  }
31
-
34
+ expressFileHook(shim, express && express.response, 'download')
35
+ expressFileHook(shim, express && express.response, 'sendFile')
32
36
  }
33
37
 
34
38
  /**
@@ -106,4 +110,40 @@ function extractParams(shim, req) {
106
110
  requestManager.setRequest(segment.transaction.id, request);
107
111
  }
108
112
  }
109
- }
113
+ }
114
+
115
+ /**
116
+ * Wrapper for resp.download()
117
+ * @param {*} shim
118
+ * @param {*} mod
119
+ * @param {*} fun
120
+ */
121
+ function expressFileHook(shim, mod, fun){
122
+ shim.wrap(mod, fun, function makeFAWrapper(shim, fn) {
123
+ if (!shim.isFunction(fn)) {
124
+ return fn
125
+ }
126
+ logger.debug(`Instrumenting express.response.${fun}`)
127
+ return function FAWrapper() {
128
+ let parameters = Array.prototype.slice.apply(arguments);
129
+ const interceptedArgs = [arguments[0]];
130
+ shim.interceptedArgs = interceptedArgs;
131
+ const request = requestManager.getRequest(shim);
132
+ if (request && typeof arguments[0] === STRING && !lodash.isEmpty(arguments[0])) {
133
+ const traceObject = secUtils.getTraceObject(shim);
134
+ try {
135
+ parameters[0] = path.resolve(parameters[0]);
136
+ } catch (error) {
137
+
138
+ }
139
+ let absoluteParameters = [parameters[0]];
140
+ const secMetadata = securityMetaData.getSecurityMetaData(request, absoluteParameters, traceObject, secUtils.getExecutionId(), EVENT_TYPE.FILE_OPERATION, EVENT_CATEGORY.FILE)
141
+ this.secEvent = API.generateSecEvent(secMetadata);
142
+ API.sendEvent(this.secEvent);
143
+ }
144
+ return fn.apply(this, arguments);
145
+ };
146
+ });
147
+ }
148
+
149
+
@@ -5,7 +5,7 @@
5
5
 
6
6
  module.exports = initialize
7
7
  const requestManager = require('../../core/request-manager');
8
- const { NR_CSEC_FUZZ_REQUEST_ID, QUESTION_MARK, EMPTY_STRING, UTF8, CONTENT_TYPE, TEXT_HTML, APPLICATION_JSON, APPLICATION_XML, APPLICATION_XHTML, TEXT_PLAIN, APPLICATION_X_FORM_URLENCODED, MULTIPART_FORM_DATA } = require('../../core/constants');
8
+ const { NR_CSEC_FUZZ_REQUEST_ID, QUESTION_MARK, EMPTY_STRING, UTF8, CONTENT_TYPE, TEXT_HTML, APPLICATION_JSON, APPLICATION_XML, APPLICATION_XHTML, TEXT_PLAIN, APPLICATION_X_FORM_URLENCODED, MULTIPART_FORM_DATA, COMMA } = require('../../core/constants');
9
9
  const ARRAY_TYPE = 'Array';
10
10
  const STRING_TYPE = 'string';
11
11
  const BUFFER_TYPE = 'Buffer';
@@ -168,27 +168,38 @@ function parseFuzzheaders(requestData, transactionId) {
168
168
  try {
169
169
  const additionalData = fuzzheaders[NR_CSEC_FUZZ_REQUEST_ID].split(CSEC_SEP);
170
170
  logger.debug('AdditionalData:', additionalData);
171
- if (additionalData.length >= 7) {
172
- for (let i = 6; i < additionalData.length; i++) {
173
- let file = additionalData[i].trim();
174
- file = file.replace(CSEC_HOME_TMP_CONST, CSEC_HOME_TMP);
175
- file = path.resolve(file);
176
- const parentDir = path.dirname(file);
177
- if (!isInvalid(parentDir) && isPathInside(parentDir, CSEC_HOME_TMP)) {
178
- try {
179
- if (!fs.existsSync(parentDir)) {
180
- secUtils.createPathIfNotExist(parentDir);
181
- } else {
182
- logger.debug(parentDir + ' Already Exists');
171
+ if (additionalData.length >= 8) {
172
+ let encryptedData = additionalData[6];
173
+ let hashVerifier = additionalData[7];
174
+ let decryptedData = secUtils.decryptData(encryptedData);
175
+ let verifiedHash = secUtils.hashVerifier(decryptedData, hashVerifier);
176
+ logger.debug("verifiedHash:", verifiedHash);
177
+ let filesToCreate = decryptedData.split(COMMA);
178
+ if (verifiedHash) {
179
+ logger.debug("Encrypted Data:", encryptedData);
180
+ logger.debug("Decrypted Data:", decryptedData)
181
+ logger.debug("fliesTocreate:",filesToCreate);
182
+ for (let i = 0; i < filesToCreate.length; i++) {
183
+ let file = filesToCreate[i].trim();
184
+ file = file.replace(CSEC_HOME_TMP_CONST, CSEC_HOME_TMP);
185
+ file = path.resolve(file);
186
+ const parentDir = path.dirname(file);
187
+ if (!isInvalid(parentDir) && isPathInside(parentDir, CSEC_HOME_TMP)) {
188
+ try {
189
+ if (!fs.existsSync(parentDir)) {
190
+ secUtils.createPathIfNotExist(parentDir);
191
+ } else {
192
+ logger.debug(parentDir + ' Already Exists');
193
+ }
194
+ fs.closeSync(fs.openSync(file, 'w'));
195
+
196
+ requestData.tempFiles = [];
197
+ requestData.tempFiles.push(file);
198
+ requestManager.setRequest(transactionId, requestData);
199
+
200
+ } catch (error) {
201
+ logger.debug(error);
183
202
  }
184
- fs.closeSync(fs.openSync(file, 'w'));
185
-
186
- requestData.tempFiles = [];
187
- requestData.tempFiles.push(file);
188
- requestManager.setRequest(transactionId, requestData);
189
-
190
- } catch (error) {
191
- logger.debug(error);
192
203
  }
193
204
  }
194
205
  }
@@ -392,7 +403,7 @@ function responseHook(resp, req, shim) {
392
403
  const dynamicScanningFlag = policy.data ? (policy.data.vulnerabilityScan?.enabled && policy.data.vulnerabilityScan.iastScan.enabled) : false;
393
404
  const type = response.getHeader(CONTENT_TYPE);
394
405
  let isUnsupportedType = isUnsupportedContentType(type);
395
-
406
+
396
407
  if (request && (construct || dynamicScanningFlag) && !isUnsupportedType) {
397
408
  const args = [];
398
409
  args.push(construct);
@@ -400,7 +411,7 @@ function responseHook(resp, req, shim) {
400
411
  const traceObject = secUtils.getTraceObject(shim);
401
412
  const secMetadata = securityMetaData.getSecurityMetaData(request, args, traceObject, secUtils.getExecutionId(), EVENT_TYPE.REFLECTED_XSS, EVENT_CATEGORY.REFLECTED_XSS)
402
413
  const secEvent = API.generateSecEvent(secMetadata);
403
- secEvent.httpResponse = {};
414
+ secEvent.httpResponse = {};
404
415
  secEvent.httpResponse.contentType = response.getHeader(CONTENT_TYPE);
405
416
  API.sendEvent(secEvent);
406
417
  }
@@ -51,7 +51,6 @@ function setPolicyData(data) {
51
51
  policy.data = data;
52
52
  appInfoVersionUpdate(policy, data);
53
53
  initLogger.info("[STEP-7] => Received and applied policy/configuration", JSON.stringify(policy.data));
54
- logger.info('Applied policy is:', JSON.stringify(policy.data));
55
54
  if (NRAgent && NRAgent.config.security.detection) {
56
55
  logger.info('Security detection flags:', JSON.stringify(NRAgent.config.security.detection));
57
56
  }
@@ -12,7 +12,7 @@ const OS = require('os');
12
12
  const path = require('path');
13
13
  const checkDiskSpace = require('check-disk-space').default;
14
14
  const AgentStatus = require('../core/agent-status');
15
- const { CSEC_HOME, SLASH } = require('./sec-agent-constants');
15
+ const { CSEC_HOME, SLASH, EMPTY_STR } = require('./sec-agent-constants');
16
16
 
17
17
  const njsAgentConstants = require('./sec-agent-constants');
18
18
  const API = require('../../../nr-security-api');
@@ -445,6 +445,20 @@ function addLogEventtoBuffer(logMessage) {
445
445
  logger.debug(error);
446
446
  }
447
447
  }
448
+ /**
449
+ * Utility to get framework from APM
450
+ * @returns
451
+ */
452
+ function getFramework(){
453
+ let framework = EMPTY_STR;
454
+ try {
455
+ framework = NRAgent.environment.get('Framework')[0];
456
+ } catch (error) {
457
+ logger.debug("Unable to get framework");
458
+ }
459
+ return framework;
460
+ }
461
+
448
462
 
449
463
  module.exports = {
450
464
  getUUID,
@@ -469,5 +483,6 @@ module.exports = {
469
483
  getWSHealthStatus,
470
484
  setWSHealthStatus,
471
485
  addLogEventtoBuffer,
472
- getLogEvents
486
+ getLogEvents,
487
+ getFramework
473
488
  };
@@ -111,6 +111,7 @@ module.exports = {
111
111
  SEVERE: 'SEVERE',
112
112
  HIGH: 'HIGH',
113
113
  CRITICAL: 'CRITICAL',
114
+ HYPHEN: '-',
114
115
 
115
116
  LOG_MESSAGES: {
116
117
  LOADED_CSEC_ENVS_MSG: '[STEP-1][COMPLETE][env] Environment Information Gathering Done.',
@@ -165,7 +166,7 @@ module.exports = {
165
166
  ERROR_WHILE_SEND_EVENT: 'ERROR While Sending Event: {}',
166
167
  WS_CONNECTED: '[STEP-4][COMPLETE][WS] Connected To Prevent-web Service',
167
168
  SENDING_APPINFO: '[APP_INFO] Sending Application Info To Prevent-web Service: ',
168
- SENDING_APPINFO_COMPLETE: '[COMPLETE][APP_INFO] Application info sent to Prevent-Web service :',
169
+ SENDING_APPINFO_COMPLETE: '[STEP-3][COMPLETE][APP_INFO] Application info sent to Prevent-Web service :',
169
170
  APPLY_INSTRUMENTATION: '[STEP-6][BEGIN][instrumentation] Applying Instrumentation',
170
171
  AVAIL_DISK: 'Available Disk Space Is: ',
171
172
  AVAIL_DISK_ERROR: 'Insufficient Disk Space Available To The Location %s Is : %s',
@@ -9,7 +9,7 @@ const { SecEvent } = require('./event');
9
9
  const logs = require('./logging');
10
10
  const { Agent } = require('./agent');
11
11
  const shaUtil = require('./sha-size-util');
12
- const { LOG_MESSAGES, NR_CSEC_FUZZ_REQUEST_ID, COLON, VULNERABLE, EXITEVENT, EMPTY_STR, RASP, SEVERE } = require('./sec-agent-constants');
12
+ const { LOG_MESSAGES, NR_CSEC_FUZZ_REQUEST_ID, COLON, VULNERABLE, EXITEVENT, EMPTY_STR, RASP, SEVERE, HYPHEN } = require('./sec-agent-constants');
13
13
  const API = require('../../../nr-security-api');
14
14
  const NRAgent = API.getNRAgent();
15
15
  const HC = require('./health-check');
@@ -83,6 +83,7 @@ function generateSecEvent(securityMetadata) {
83
83
  }
84
84
 
85
85
  let apiId = shaUtil.getSHA256ForData(traceObject.stacktrace.join('|') + uri);
86
+ apiId = securityMetadata.eventType + HYPHEN + apiId;
86
87
  const agentModule = Agent.getAgent();
87
88
  const metaData = {};
88
89
  if (traceObject.sourceDetails && traceObject.sourceDetails.evalObj) {
@@ -23,10 +23,11 @@ const logs = require('./logging');
23
23
  const commonUtils = require('./commonUtils');
24
24
  const logger = logs.getLogger();
25
25
  const statusFile = njsAgentConstants.STATUS_LOG_FILE;
26
+ const sep = require('path').sep;
26
27
 
27
28
  const statusTemplate = 'Snapshot timestamp: : %s\n' +
28
29
  `CSEC Agent start timestamp: ${njsAgentConstants.AGENT_START_TIME} with application uuid:${commonUtils.getUUID()}\n` +
29
- `SEC_HOME: ${njsAgentConstants.CSEC_HOME}\n` +
30
+ `CSEC_HOME: ${njsAgentConstants.CSEC_HOME}${sep}nr-security-home${sep}\n` +
30
31
  `Agent location: ${AGENT_DIR}\n` +
31
32
  `Using CSEC Agent for Node.js, Node version:${process.version}, PID:${process.pid}\n` +
32
33
  `Process title: ${process.title}\n` +
@@ -35,10 +36,10 @@ const statusTemplate = 'Snapshot timestamp: : %s\n' +
35
36
  `Current working directory: ${process.cwd()}\n` +
36
37
  `Agent mode: ${commonUtils.getCSECmode()}\n` +
37
38
  'Application server: %s\n' +
38
- 'Application Framework: %s\n' +
39
+ `Application Framework: %s\n` +
39
40
  `Websocket connection to Prevent Web: ${commonUtils.getValidatorServiceEndpointURL()}, Status: %s\n` +
40
- 'Instrumentation successful:\n' +
41
- 'Tracking loaded modules in the application:\n' +
41
+ 'Instrumentation successful\n' +
42
+ 'Tracking loaded modules in the application\n' +
42
43
  'Policy applied successfully. Policy version is: %s\n' +
43
44
  'Started Health Check for Agent\n' +
44
45
  'Started Inbound and Outbound monitoring \n' +
@@ -83,7 +84,7 @@ function getFormattedData() {
83
84
  const appInfo = Agent.applicationInfo;
84
85
  const deployedApplications = appInfo && appInfo.serverInfo && appInfo.serverInfo.deployedApplications;
85
86
  const appLoc = deployedApplications[0].deployedPath;
86
- const formattedSnapshot = util.format(statusTemplate, new Date().toString(), appLoc, appInfo.serverInfo.name, njsAgentConstants.FRAMEWORK, commonUtils.getWSHealthStatus(), appInfo.policyVersion, getKeyValPairs(lastHC.stats), getKeyValPairs(lastHC.serviceStatus), JSON.stringify(getBufferedErrors()), JSON.stringify(getBufferedHC()));
87
+ const formattedSnapshot = util.format(statusTemplate, new Date().toString(), appLoc, appInfo.serverInfo.name, commonUtils.getFramework(), commonUtils.getWSHealthStatus(), appInfo.policyVersion, getKeyValPairs(lastHC.stats), getKeyValPairs(lastHC.serviceStatus), JSON.stringify(getBufferedErrors()), JSON.stringify(getBufferedHC()));
87
88
  return formattedSnapshot;
88
89
  }
89
90
 
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@newrelic/security-agent",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "New Relic Security Agent for Node.js",
5
5
  "main": "index.js",
6
- "jsonVersion": "1.1.1",
6
+ "jsonVersion": "1.2.0",
7
7
  "contributors": [
8
8
  {
9
9
  "name": "Sumit Suthar",