@newrelic/security-agent 1.2.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 (27) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +212 -211
  4. package/lib/instrumentation-security/core/constants.js +1 -0
  5. package/lib/instrumentation-security/core/grpc-utils.js +53 -0
  6. package/lib/instrumentation-security/core/security-metadata.js +12 -2
  7. package/lib/instrumentation-security/hooks/fs/nr-fs.js +4 -4
  8. package/lib/instrumentation-security/hooks/grpc-js/nr-grpc.js +342 -0
  9. package/lib/instrumentation-security/hooks/http/nr-http.js +46 -6
  10. package/lib/instrumentation-security/index.js +32 -3
  11. package/lib/nr-security-agent/index.js +7 -1
  12. package/lib/nr-security-agent/lib/core/ExceptionReporting.js +182 -0
  13. package/lib/nr-security-agent/lib/core/LogMessage.js +4 -1
  14. package/lib/nr-security-agent/lib/core/commonUtils.js +2 -2
  15. package/lib/nr-security-agent/lib/core/connections/grpcClient.js +112 -0
  16. package/lib/nr-security-agent/lib/core/connections/restclient.js +6 -0
  17. package/lib/nr-security-agent/lib/core/connections/websocket/response/IASTUtils.js +3 -0
  18. package/lib/nr-security-agent/lib/core/connections/websocket/response/fuzz-request-handler.js +32 -12
  19. package/lib/nr-security-agent/lib/core/connections/websocket/response/startup-handshake-handler.js +1 -1
  20. package/lib/nr-security-agent/lib/core/connections/websocket/websocket.js +9 -4
  21. package/lib/nr-security-agent/lib/core/event.js +1 -0
  22. package/lib/nr-security-agent/lib/core/health-check.js +0 -1
  23. package/lib/nr-security-agent/lib/core/sec-util.js +1 -0
  24. package/lib/nr-security-agent/lib/core/statusUtils.js +1 -1
  25. package/lib/nr-security-agent/lib/core/websocket-client.js +2 -1
  26. package/lib/nr-security-agent/lib/core/xss-utils.js +11 -5
  27. package/package.json +4 -3
@@ -20,10 +20,11 @@ function logMessageException(exception) {
20
20
  try {
21
21
  exceptionObject.message = exception.message ? exception.message : '';
22
22
  exceptionObject.cause = null;
23
+ exceptionObject.type = exception.name;
23
24
  if (exception.stack) {
24
25
  let stacktraceInList = exception.stack.split('\n');
25
26
  stacktraceInList = stacktraceInList.slice(1);
26
- exceptionObject.stacktrace = stacktraceInList;
27
+ exceptionObject.stackTrace = stacktraceInList;
27
28
  }
28
29
 
29
30
  } catch (error) {
@@ -51,6 +52,8 @@ function logMessage(level, message, caller, exception) {
51
52
  this.applicationUUID = applicationInfo.applicationUUID;
52
53
  this.groupName = applicationInfo.groupName;
53
54
  this.policyVersion = applicationInfo.policyVersion;
55
+ this.collectorVersion = applicationInfo.collectorVersion ? applicationInfo.collectorVersion : null;
56
+ this.buildNumber = applicationInfo.buildNumber ? applicationInfo.buildNumber : null;
54
57
  this.timestamp = Date.now();
55
58
  this.level = level ? level : 'SEVERE';
56
59
  this.message = message;
@@ -107,7 +107,7 @@ function createPathIfNotExist(dir) {
107
107
  } catch (error) {
108
108
  logger.debug(dir + ' Not Created', error);
109
109
  const LogMessage = require('./LogMessage');
110
- const logMessage = new LogMessage.logMessage("SEVERE", 'Error in creating directory', __filename, error);
110
+ const logMessage = new LogMessage.logMessage("DEBUG", 'Error in creating directory', __filename, error);
111
111
  addLogEventtoBuffer(logMessage);
112
112
  }
113
113
  }
@@ -288,7 +288,7 @@ function removeOlderSnapshots() {
288
288
  } catch (error) {
289
289
  logger.debug(error);
290
290
  const LogMessage = require('./LogMessage');
291
- const logMessage = new LogMessage.logMessage("SEVERE", 'Error in processing snapshot files', __filename, error);
291
+ const logMessage = new LogMessage.logMessage("DEBUG", 'Error in processing snapshot files', __filename, error);
292
292
  addLogEventtoBuffer(logMessage);
293
293
  }
294
294
  }
@@ -0,0 +1,112 @@
1
+ /*
2
+ * Copyright 2023 New Relic Corporation. All rights reserved.
3
+ * SPDX-License-Identifier: New Relic Pre-Release
4
+ */
5
+ const logger = require('../logging').getLogger();
6
+ const grpcutils = require('../../../../instrumentation-security/core/grpc-utils');
7
+ const clientMap = new Map();
8
+ let grpc;
9
+ const { NR_CSEC_FUZZ_REQUEST_ID } = require('../../core/sec-agent-constants');
10
+
11
+ /**
12
+ * Utility to get client object
13
+ * @param {*} config
14
+ * @returns
15
+ */
16
+ function getGPRCClient(config) {
17
+ let grpc = require("@grpc/grpc-js");
18
+ try {
19
+ const serviceName = grpcutils.getMethod(config.method).serviceName;
20
+
21
+ if (clientMap.has(serviceName)) {
22
+ return clientMap.get(serviceName);
23
+ }
24
+ const serviceObject = grpcutils.getService(serviceName);
25
+ const definition = grpc.loadPackageDefinition(serviceObject);
26
+ let service = getNestedValue(definition, serviceName)
27
+ if (service) {
28
+ logger.info("GRPC client service extracted successfully");
29
+ }
30
+ const client = new service(
31
+ "localhost:" + config.serverPort,
32
+ grpc.credentials.createInsecure()
33
+ );
34
+ if (!clientMap.has(serviceName)) {
35
+ clientMap.set(serviceName, client);
36
+ }
37
+ if(client){
38
+ logger.info("GRPC IAST client created successfully");
39
+ }
40
+ return client;
41
+ } catch (error) {
42
+ logger.error("error while creating client:", error);
43
+ }
44
+
45
+ }
46
+
47
+ /**
48
+ * Utility to fire unary requests
49
+ * @param {*} client
50
+ * @param {*} config
51
+ */
52
+ function fireUnaryRequest(client, config) {
53
+ try {
54
+ const methodObj = grpcutils.getMethod(config.requestURI);
55
+ if (methodObj && methodObj.originalName) {
56
+ let method = methodObj.originalName;
57
+ let metadata = new grpc.Metadata();
58
+ let bufferObj = Buffer.from(config.headers[NR_CSEC_FUZZ_REQUEST_ID], "utf8");
59
+ let base64String = bufferObj.toString("base64");
60
+ metadata.add(NR_CSEC_FUZZ_REQUEST_ID, base64String);
61
+ client[method](JSON.parse(config.data), metadata, (err, res) => {
62
+ if (err) {
63
+ logger.debug("Error occured:", err);
64
+ return
65
+ }
66
+
67
+ logger.info("Fuzz success: ", JSON.stringify(config));
68
+ return res;
69
+ })
70
+ }
71
+ else {
72
+ logger.debug("Not Found:", config.url);
73
+ }
74
+ } catch (error) {
75
+ logger.debug("Error while firing Unary request:", error);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * fire gRPC request based on provided config
81
+ * @param {*} config
82
+ * @returns
83
+ */
84
+ function fireRequest(config) {
85
+ try {
86
+ grpc = require("@grpc/grpc-js");
87
+ } catch (error) {
88
+ logger.debug("Unable to import grpc module", error);
89
+ }
90
+ let client = getGPRCClient(config);
91
+ fireUnaryRequest(client, config)
92
+ }
93
+
94
+
95
+ function getNestedValue(obj, targetKey) {
96
+ for (const key in obj) {
97
+ if (key === targetKey) {
98
+ return obj[key];
99
+ } else if (typeof obj[key] === 'object' && obj[key] !== null) {
100
+ const result = getNestedValue(obj[key], targetKey);
101
+ if (result !== undefined) {
102
+ return result;
103
+ }
104
+ }
105
+ }
106
+ return undefined; // Key not found
107
+ }
108
+
109
+
110
+ module.exports = {
111
+ fireRequest
112
+ };
@@ -12,6 +12,12 @@ const axios = require('axios').default;
12
12
  */
13
13
  function fireRequest (config) {
14
14
  axios.defaults.timeout = 5000;
15
+ axios.defaults.headers.common['user-agent'] = null;
16
+ axios.defaults.headers.common['accept-encoding'] = null;
17
+ axios.defaults.headers.common['connection'] = null;
18
+ axios.defaults.headers.common['sec-ch-ua-platform'] = null;
19
+ axios.defaults.headers.common['accept'] = null;
20
+ axios.defaults.headers.common['content-type'] = null;
15
21
  return axios(config);
16
22
  }
17
23
 
@@ -31,6 +31,9 @@ function completedRequestsMapInit(id) {
31
31
 
32
32
  function addCompletedRequests(id, eventId) {
33
33
  let data = completedRequestsMap.get(id);
34
+ if(!data){
35
+ return;
36
+ }
34
37
  data.push(eventId);
35
38
  completedRequestsMap.set(id, data);
36
39
  }
@@ -7,6 +7,7 @@
7
7
  const stringify = require('fast-safe-stringify');
8
8
 
9
9
  const restClient = require('../../restclient');
10
+ const grpcClient = require('../../grpcClient');
10
11
  const { Agent } = require('../../../agent');
11
12
  const { FuzzFailEvent } = require('../../../FuzzFailEvent');
12
13
  const { CSEC_HOME_TMP, COLON, NR_CSEC_FUZZ_REQUEST_ID, SLASH, CSEC_SEP, SEVERE } = require('../../../sec-agent-constants');
@@ -20,9 +21,6 @@ const LogMessage = require('../../../LogMessage');
20
21
  require('dns').setDefaultResultOrder('ipv4first')
21
22
  const PolicyManager = require('../../../Policy');
22
23
 
23
- const {
24
- IS_LAMBDA_ENV,
25
- AWS_LAMBDA_FUNCTION_VERSION_ENV_IDENTIFIER } = require('../../../sec-agent-constants');
26
24
  const statusUtils = require('../../../statusUtils');
27
25
 
28
26
  const find = `${SLASH}{{NR_CSEC_VALIDATOR_HOME_TMP}}`;
@@ -53,7 +51,7 @@ function startIASTSchedular() {
53
51
  if (isNaN(probingInterval)) {
54
52
  probingInterval = 5;
55
53
  }
56
-
54
+
57
55
  iastIntervalConst = setInterval(() => {
58
56
  let data = IASTUtil.generateIASTDataRequest();
59
57
  let currentTime = Date.now();
@@ -125,13 +123,16 @@ function handler(json) {
125
123
  function handleFuzzRequest(fuzzDetails) {
126
124
  const { fuzzRequest } = fuzzDetails;
127
125
  try {
128
- if (IS_LAMBDA_ENV) {
129
- const qualifiedARN = Agent.getAgent().applicationInfo.applicationUUID;
130
- const splitArn = String.prototype.split.call(qualifiedARN, ':');
131
- const arn = splitArn.slice(0, splitArn.length - 1).join(':');
132
- const ver = process.env[AWS_LAMBDA_FUNCTION_VERSION_ENV_IDENTIFIER];
133
- logger.info('Invoking Lambda:: ARN: ' + arn);
134
- logger.info('Invoking Lambda:: Version: ' + ver);
126
+ if (fuzzRequest.protocol == 'grpc') {
127
+ const config = parseGRPCRequestToFuzz(fuzzRequest);
128
+ config.headers['nr-csec-parent-id'] = fuzzRequest.id;
129
+ IASTUtil.completedRequestsMapInit(fuzzRequest.id);
130
+ grpcClient.fireRequest(config);
131
+ if (fuzzRequest.headers && fuzzRequest.headers[NR_CSEC_FUZZ_REQUEST_ID]) {
132
+ logScannedApiId(fuzzRequest.headers[NR_CSEC_FUZZ_REQUEST_ID], fuzzRequest.requestURI)
133
+ }
134
+
135
+ IASTUtil.removePendingRequestId(fuzzRequest.id);
135
136
 
136
137
  } else {
137
138
  const config = parseAxiosHttpRequestToFuzz(fuzzRequest);
@@ -153,7 +154,6 @@ function handleFuzzRequest(fuzzDetails) {
153
154
 
154
155
 
155
156
  logger.info('Firing http request:: URL: ' + config.url);
156
-
157
157
  const response = restClient.fireRequest(config);
158
158
  handleFuzzResponse(response, fuzzDetails);
159
159
  }
@@ -210,6 +210,26 @@ function parseAxiosHttpRequestToFuzz(requestObject) {
210
210
  };
211
211
  }
212
212
 
213
+ /**
214
+ * Parses the passed fuzz request object to
215
+ * Axios config.
216
+ *
217
+ * @param {JSON} requestObject
218
+ */
219
+ function parseGRPCRequestToFuzz(requestObject) {
220
+ let serverName = requestObject.serverName ? requestObject.serverName : LOCALHOST;
221
+ let host = serverName + COLON + requestObject.serverPort
222
+ return {
223
+ url: requestObject.protocol + COLON_SLASH_SLASH + host + requestObject.url,
224
+ requestURI: requestObject.requestURI,
225
+ protocol: requestObject.protocol,
226
+ serverPort: requestObject.serverPort,
227
+ method: requestObject.method,
228
+ data: requestObject.body,
229
+ headers: requestObject.headers,
230
+ timeout: 5000,
231
+ };
232
+ }
213
233
 
214
234
 
215
235
  /**
@@ -18,7 +18,7 @@ module.exports.handler = function handler(json) {
18
18
 
19
19
  initLogger.info(LOG_MESSAGES.AGENT_INIT_WITH_PROP, JSON.stringify(startupConfig.config));
20
20
  initLogger.info('Security Agent is now ACTIVE for', applicationInfoModule.getInstance().applicationUUID);
21
- const logMessage = new LogMessage.logMessage("SEVERE", `Security Agent is ACTIVE for ${ applicationInfoModule.getInstance().applicationUUID}`, __filename, null);
21
+ const logMessage = new LogMessage.logMessage("INFO", `Security Agent is ACTIVE for ${ applicationInfoModule.getInstance().applicationUUID}`, __filename, null);
22
22
  require('../../../commonUtils').addLogEventtoBuffer(logMessage);
23
23
 
24
24
  } catch (error) {
@@ -104,6 +104,7 @@ SecWebSocket.prototype.init = function init() {
104
104
  const validatorService = commonUtils.getValidatorServiceEndpointURL();
105
105
  const authHeaders = require('../../Auth-headers').getInstance();
106
106
  initLogger.info(`Connecting to Validator at ${validatorService}`);
107
+ IASTUtil.IASTCleanup();
107
108
  let cert = ''
108
109
  try {
109
110
  const certPath = commonUtils.getPathOfCACert();
@@ -138,6 +139,7 @@ SecWebSocket.prototype.init = function init() {
138
139
  })
139
140
  webSocket.on('close', () => {
140
141
  logger.warn("WS connection closed");
142
+ this.obeyReconnect();
141
143
  })
142
144
  this.instance = webSocket;
143
145
  };
@@ -172,7 +174,7 @@ SecWebSocket.prototype.obeyReconnect = function obeyReconnect() {
172
174
  }
173
175
 
174
176
  initTimeOut = setTimeout(() => {
175
- IASTUtil.IASTCleanup();
177
+
176
178
  logger.debug("Terminating ws instance and reconnecting");
177
179
  try {
178
180
  instance.terminate();
@@ -189,18 +191,21 @@ SecWebSocket.prototype.pingWS = async function pingWS() {
189
191
  let currentTime = Date.now();
190
192
 
191
193
  let timeDiffInPing = (currentTime - lastPongtime) / 1000;
192
- if (timeDiffInPing > 40 && lastPongtime != 0) {
194
+ logger.debug("Websocket ready state is:",self.instance.readyState)
195
+
196
+ if (timeDiffInPing > 40 && lastPongtime != 0 && self.instance.readyState > 1) {
193
197
  self.obeyReconnect();
194
198
  lastPongtime = 0;
195
199
  return;
196
200
  }
201
+
197
202
  try {
198
203
  await promisify(self.instance, self.instance.ping)(ACK, true, function (err) {
199
204
  if (err) {
200
205
  logger.debug("Error while pinging:", err);
201
206
  commonUtils.setWSHealthStatus('Error');
202
207
  statusUtils.addErrortoBuffer(err);
203
- self.obeyReconnect();
208
+
204
209
  }
205
210
  });
206
211
  } catch (err) {
@@ -258,7 +263,7 @@ SecWebSocket.prototype.dispatch = async function dispatch(event) {
258
263
  hc.getInstance().exitEventStats.sent++;
259
264
  }
260
265
 
261
- });
266
+ })
262
267
  } catch (error) {
263
268
  logger.debug(LOG_MESSAGES.ERROR_WHILE_SEND_EVENT, eventStr, error);
264
269
  statusUtils.addErrortoBuffer(error);
@@ -34,6 +34,7 @@ function BasicInfo() {
34
34
  this.policyVersion = (!lodash.isEmpty(policyManager.getInstance().data)) ? policyManager.getInstance().data.version : 'DEFAULT';
35
35
 
36
36
  if (NRAgent && NRAgent.config) {
37
+ this.accountId = NRAgent.config.account_id;
37
38
  this.entityGuid = NRAgent.config.entity_guid;
38
39
  this.linkingMetadata = LinkingMetaData.getLinkingMetadata();
39
40
  this.linkingMetadata.agentRunId = NRAgent.config.run_id;
@@ -43,7 +43,6 @@ module.exports.getInstance = function () {
43
43
  function HC(info) {
44
44
  BasicInfo.call(this);
45
45
 
46
-
47
46
  this.applicationUUID = info.applicationUUID;
48
47
  this.eventType = 'sec_health_check_lc';
49
48
  if (NRAgent && NRAgent.config) {
@@ -101,6 +101,7 @@ function generateSecEvent(securityMetadata) {
101
101
  const isAPIBlocked = false;
102
102
  const event = new SecEvent(traceObject.sourceDetails.fileName, traceObject.sourceDetails.funcName, traceObject.sourceDetails.lineNumber, securityMetadata.interceptedArgs, securityMetadata.executionId, agentModule.applicationInfo, securityMetadata.request, securityMetadata.eventType, traceObject.sourceDetails.source, securityMetadata.eventCategory, metaData, stakTrace, apiId, isAPIBlocked);
103
103
  event.metaData.isClientDetectedFromXFF = isClientDetectedFromXFF;
104
+ event.httpRequest.route = uri;
104
105
  return event;
105
106
  } catch (e) {
106
107
  statusUtils.addErrortoBuffer(e);
@@ -98,7 +98,7 @@ function writeSnapshot() {
98
98
  if (err) {
99
99
  logger.debug(err.message);
100
100
  const LogMessage = require('./LogMessage');
101
- const logMessage = new LogMessage.logMessage("SEVERE", 'Error in creating snapshot file', __filename, err);
101
+ const logMessage = new LogMessage.logMessage("DEBUG", 'Error in creating snapshot file', __filename, err);
102
102
  commonUtils.addLogEventtoBuffer(logMessage);
103
103
  } else {
104
104
  logger.info('Snapshot updated to file: %s', statusFile);
@@ -75,6 +75,7 @@ const initialize = function () {
75
75
  let data = require('./apiEndpoints').APIEndPoint(apiEndpoints);
76
76
  logger.debug("All API end points of the application is:",JSON.stringify(data));
77
77
  getDispatcherAndSendEvent(data);
78
+ require('../core/ExceptionReporting').startExceptionSendingSchedular();
78
79
  } catch (error) {
79
80
  logger.debug("Error while processing API endpoints",error);
80
81
  }
@@ -82,7 +83,7 @@ const initialize = function () {
82
83
  try {
83
84
  const framework = NRAgent.environment.get('Framework')[0];
84
85
  const dispatcher = NRAgent.environment.get('Dispatcher')[0];
85
- const logMessage = new LogMessage.logMessage("SEVERE", `Detected framework: ${framework} and dispatcher: ${dispatcher}`, __filename, null);
86
+ const logMessage = new LogMessage.logMessage("INFO", `Detected framework: ${framework} and dispatcher: ${dispatcher}`, __filename, null);
86
87
  commonUtils.addLogEventtoBuffer(logMessage);
87
88
  } catch (error) {
88
89
  logger.debug("Error while extracting data from APM environment",error);
@@ -10,6 +10,7 @@ const querystring = require('querystring');
10
10
  const { Agent } = require('./agent');
11
11
 
12
12
  const htmlEntities = require('html-entities');
13
+ const { STRING } = require('./sec-agent-constants');
13
14
 
14
15
  const tagNameRegex = /<([a-zA-Z_-]+[0-9]*|!--)/gmi;
15
16
  const attribRegex = /([^(/\s<'">)]+?)(?:\s*)=\s*(('|")([\s\S]*?)(?:(?=(\\?))\5.)*?\3|.+?(?=\/>|>|\?>|\s|<\/|$))/gmi;
@@ -136,10 +137,15 @@ function decodeResponseData (responseBody, responseHeaders) {
136
137
 
137
138
  function isXSS (combinedData) {
138
139
  const attackConstructs = new Set();
139
- for (const data of combinedData) {
140
- const constructs = getXSSConstructs(data);
141
- constructs.forEach(attackConstructs.add, attackConstructs);
140
+ try {
141
+ for (const data of combinedData) {
142
+ const constructs = getXSSConstructs(data);
143
+ constructs.forEach(attackConstructs.add, attackConstructs);
144
+ }
145
+ } catch (error) {
146
+ logger.debug("Error while getting rxss constucts:", error);
142
147
  }
148
+
143
149
  return attackConstructs;
144
150
  }
145
151
 
@@ -152,7 +158,7 @@ function getXSSConstructs (data) {
152
158
  let tmpStartPos = 0;
153
159
  let matcher;
154
160
  let attribMatcher;
155
- while (currPos < data.length) {
161
+ while (currPos < data.length && typeof data == STRING ) {
156
162
  let tagName;
157
163
 
158
164
  matcher = tagNameRegex.exec(data);
@@ -233,7 +239,7 @@ function getXSSConstructs (data) {
233
239
  currPos = tmpCurrPos;
234
240
  }
235
241
 
236
- if (data.charAt(currPos) !== ANGLE_END_CHAR) {
242
+ if (typeof data == STRING && data.charAt(currPos) !== ANGLE_END_CHAR) {
237
243
  const tmp = data.indexOf(ANGLE_END, currPos);
238
244
  if (tmp !== -1) {
239
245
  currPos = tmp;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@newrelic/security-agent",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "New Relic Security Agent for Node.js",
5
5
  "main": "index.js",
6
- "jsonVersion": "1.2.0",
6
+ "jsonVersion": "1.2.3",
7
7
  "contributors": [
8
8
  {
9
9
  "name": "Sumit Suthar",
@@ -55,9 +55,10 @@
55
55
  "unescape": "^1.0.1",
56
56
  "unescape-js": "^1.1.4",
57
57
  "uuid": "^9.0.1",
58
- "ws": "^8.14.2"
58
+ "ws": "^8.17.1"
59
59
  },
60
60
  "devDependencies": {
61
+ "@grpc/proto-loader": "^0.7.10",
61
62
  "@hapi/hapi": "^21.3.0",
62
63
  "@koa/router": "^12.0.0",
63
64
  "@newrelic/newrelic-oss-cli": "^0.1.2",