@newrelic/security-agent 1.1.1 → 1.3.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 (26) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/THIRD_PARTY_NOTICES.md +211 -1
  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/sec-utils.js +99 -57
  7. package/lib/instrumentation-security/core/security-metadata.js +12 -2
  8. package/lib/instrumentation-security/hooks/express/nr-express.js +43 -3
  9. package/lib/instrumentation-security/hooks/fs/nr-fs.js +4 -4
  10. package/lib/instrumentation-security/hooks/grpc-js/nr-grpc.js +301 -0
  11. package/lib/instrumentation-security/hooks/http/nr-http.js +34 -23
  12. package/lib/instrumentation-security/index.js +32 -3
  13. package/lib/nr-security-agent/index.js +7 -1
  14. package/lib/nr-security-agent/lib/core/Policy.js +0 -1
  15. package/lib/nr-security-agent/lib/core/commonUtils.js +19 -4
  16. package/lib/nr-security-agent/lib/core/connections/grpcClient.js +112 -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/sec-agent-constants.js +2 -1
  22. package/lib/nr-security-agent/lib/core/sec-util.js +3 -1
  23. package/lib/nr-security-agent/lib/core/statusUtils.js +7 -6
  24. package/lib/nr-security-agent/lib/core/websocket-client.js +1 -1
  25. package/lib/nr-security-agent/lib/core/xss-utils.js +11 -5
  26. package/package.json +3 -2
package/CHANGELOG.md CHANGED
@@ -1,3 +1,27 @@
1
+ ### v1.3.0 (2024-05-31)
2
+ #### Features
3
+ * Added route field in security event for API endpoint mapping
4
+ #### Bug fixes
5
+ * Fix for control commands acknowledgement in security agent
6
+ * Added assert for typeof response data in Reflected XSS validation
7
+ * Updated @grpc/grpc-js instrumentation to instrument submodules
8
+ * Handling to convert header values into string
9
+ #### Miscellaneous chores
10
+ * Updated log level for critical messages
11
+ * Readme update
12
+ * (deps-dev): bump axios from 0.21.4 to 1.7.2
13
+
14
+ ### v1.2.0 (2024-04-12)
15
+ #### Features
16
+ * Added instrumentation for express framework's res.download() and res.sendFile()
17
+ #### Bug fixes
18
+ * Handling to decrypt fuzz header data for IAST scanning
19
+ * Logging and snapshot file fixes
20
+ #### Miscellaneous chores
21
+ * Prepend vulnerability case type with apiId
22
+ * Updated jsonVersion to v1.2.0
23
+ * Bumped undici from 5.28.3 to 5.28.4
24
+
1
25
  ### v1.1.1 (2024-03-21)
2
26
  #### Bug fixes
3
27
  * Reverted IAST support for gRPC.
package/README.md CHANGED
@@ -99,7 +99,7 @@ New Relic hosts and moderates an online forum where you can interact with New Re
99
99
 
100
100
  ## Contribute
101
101
 
102
- Any feedback provided to New Relic about the New Relic security agent, including feedback provided as source code, comments, or other copyrightable or patentable material, is provided to New Relic under the terms of the Apache Software License, version 2. If you do not provide attribution information or a copy of the license with your feedback, you waive the performance of those requirements of the Apache License with respect to New Relic. The license grant regarding any feedback is irrevocable and persists past the termination of the preview license.
102
+ Any feedback provided to New Relic about the New Relic security agent, including feedback provided as source code, comments, or other copyrightable or patentable material, is provided to New Relic under the terms of the New Relic Software License v1.0. If you do not provide attribution information or a copy of the license with your feedback, you waive the performance of those requirements of the New Relic Software License v1.0 with respect to New Relic. The license grant regarding any feedback is irrevocable.
103
103
  Keep in mind that when you submit a pull request or other feedback, you’ll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.
104
104
  If you have any questions drop us an email at opensource@newrelic.com.
105
105
 
@@ -38,6 +38,7 @@ code, the source code can be found at [https://github.com/newrelic/csec-node-age
38
38
 
39
39
  **[devDependencies](#devDependencies)**
40
40
 
41
+ * [@grpc/proto-loader](#grpcproto-loader)
41
42
  * [@hapi/hapi](#hapihapi)
42
43
  * [@koa/router](#koarouter)
43
44
  * [@newrelic/newrelic-oss-cli](#newrelicnewrelic-oss-cli)
@@ -616,6 +617,215 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
616
617
 
617
618
  ## devDependencies
618
619
 
620
+ ### @grpc/proto-loader
621
+
622
+ This product includes source derived from [@grpc/proto-loader](https://github.com/grpc/grpc-node) ([v0.7.7](https://github.com/grpc/grpc-node/tree/v0.7.7)), distributed under the [Apache-2.0 License](https://github.com/grpc/grpc-node/blob/v0.7.7/LICENSE):
623
+
624
+ ```
625
+ Apache License
626
+ Version 2.0, January 2004
627
+ http://www.apache.org/licenses/
628
+
629
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
630
+
631
+ 1. Definitions.
632
+
633
+ "License" shall mean the terms and conditions for use, reproduction,
634
+ and distribution as defined by Sections 1 through 9 of this document.
635
+
636
+ "Licensor" shall mean the copyright owner or entity authorized by
637
+ the copyright owner that is granting the License.
638
+
639
+ "Legal Entity" shall mean the union of the acting entity and all
640
+ other entities that control, are controlled by, or are under common
641
+ control with that entity. For the purposes of this definition,
642
+ "control" means (i) the power, direct or indirect, to cause the
643
+ direction or management of such entity, whether by contract or
644
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
645
+ outstanding shares, or (iii) beneficial ownership of such entity.
646
+
647
+ "You" (or "Your") shall mean an individual or Legal Entity
648
+ exercising permissions granted by this License.
649
+
650
+ "Source" form shall mean the preferred form for making modifications,
651
+ including but not limited to software source code, documentation
652
+ source, and configuration files.
653
+
654
+ "Object" form shall mean any form resulting from mechanical
655
+ transformation or translation of a Source form, including but
656
+ not limited to compiled object code, generated documentation,
657
+ and conversions to other media types.
658
+
659
+ "Work" shall mean the work of authorship, whether in Source or
660
+ Object form, made available under the License, as indicated by a
661
+ copyright notice that is included in or attached to the work
662
+ (an example is provided in the Appendix below).
663
+
664
+ "Derivative Works" shall mean any work, whether in Source or Object
665
+ form, that is based on (or derived from) the Work and for which the
666
+ editorial revisions, annotations, elaborations, or other modifications
667
+ represent, as a whole, an original work of authorship. For the purposes
668
+ of this License, Derivative Works shall not include works that remain
669
+ separable from, or merely link (or bind by name) to the interfaces of,
670
+ the Work and Derivative Works thereof.
671
+
672
+ "Contribution" shall mean any work of authorship, including
673
+ the original version of the Work and any modifications or additions
674
+ to that Work or Derivative Works thereof, that is intentionally
675
+ submitted to Licensor for inclusion in the Work by the copyright owner
676
+ or by an individual or Legal Entity authorized to submit on behalf of
677
+ the copyright owner. For the purposes of this definition, "submitted"
678
+ means any form of electronic, verbal, or written communication sent
679
+ to the Licensor or its representatives, including but not limited to
680
+ communication on electronic mailing lists, source code control systems,
681
+ and issue tracking systems that are managed by, or on behalf of, the
682
+ Licensor for the purpose of discussing and improving the Work, but
683
+ excluding communication that is conspicuously marked or otherwise
684
+ designated in writing by the copyright owner as "Not a Contribution."
685
+
686
+ "Contributor" shall mean Licensor and any individual or Legal Entity
687
+ on behalf of whom a Contribution has been received by Licensor and
688
+ subsequently incorporated within the Work.
689
+
690
+ 2. Grant of Copyright License. Subject to the terms and conditions of
691
+ this License, each Contributor hereby grants to You a perpetual,
692
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
693
+ copyright license to reproduce, prepare Derivative Works of,
694
+ publicly display, publicly perform, sublicense, and distribute the
695
+ Work and such Derivative Works in Source or Object form.
696
+
697
+ 3. Grant of Patent License. Subject to the terms and conditions of
698
+ this License, each Contributor hereby grants to You a perpetual,
699
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
700
+ (except as stated in this section) patent license to make, have made,
701
+ use, offer to sell, sell, import, and otherwise transfer the Work,
702
+ where such license applies only to those patent claims licensable
703
+ by such Contributor that are necessarily infringed by their
704
+ Contribution(s) alone or by combination of their Contribution(s)
705
+ with the Work to which such Contribution(s) was submitted. If You
706
+ institute patent litigation against any entity (including a
707
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
708
+ or a Contribution incorporated within the Work constitutes direct
709
+ or contributory patent infringement, then any patent licenses
710
+ granted to You under this License for that Work shall terminate
711
+ as of the date such litigation is filed.
712
+
713
+ 4. Redistribution. You may reproduce and distribute copies of the
714
+ Work or Derivative Works thereof in any medium, with or without
715
+ modifications, and in Source or Object form, provided that You
716
+ meet the following conditions:
717
+
718
+ (a) You must give any other recipients of the Work or
719
+ Derivative Works a copy of this License; and
720
+
721
+ (b) You must cause any modified files to carry prominent notices
722
+ stating that You changed the files; and
723
+
724
+ (c) You must retain, in the Source form of any Derivative Works
725
+ that You distribute, all copyright, patent, trademark, and
726
+ attribution notices from the Source form of the Work,
727
+ excluding those notices that do not pertain to any part of
728
+ the Derivative Works; and
729
+
730
+ (d) If the Work includes a "NOTICE" text file as part of its
731
+ distribution, then any Derivative Works that You distribute must
732
+ include a readable copy of the attribution notices contained
733
+ within such NOTICE file, excluding those notices that do not
734
+ pertain to any part of the Derivative Works, in at least one
735
+ of the following places: within a NOTICE text file distributed
736
+ as part of the Derivative Works; within the Source form or
737
+ documentation, if provided along with the Derivative Works; or,
738
+ within a display generated by the Derivative Works, if and
739
+ wherever such third-party notices normally appear. The contents
740
+ of the NOTICE file are for informational purposes only and
741
+ do not modify the License. You may add Your own attribution
742
+ notices within Derivative Works that You distribute, alongside
743
+ or as an addendum to the NOTICE text from the Work, provided
744
+ that such additional attribution notices cannot be construed
745
+ as modifying the License.
746
+
747
+ You may add Your own copyright statement to Your modifications and
748
+ may provide additional or different license terms and conditions
749
+ for use, reproduction, or distribution of Your modifications, or
750
+ for any such Derivative Works as a whole, provided Your use,
751
+ reproduction, and distribution of the Work otherwise complies with
752
+ the conditions stated in this License.
753
+
754
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
755
+ any Contribution intentionally submitted for inclusion in the Work
756
+ by You to the Licensor shall be under the terms and conditions of
757
+ this License, without any additional terms or conditions.
758
+ Notwithstanding the above, nothing herein shall supersede or modify
759
+ the terms of any separate license agreement you may have executed
760
+ with Licensor regarding such Contributions.
761
+
762
+ 6. Trademarks. This License does not grant permission to use the trade
763
+ names, trademarks, service marks, or product names of the Licensor,
764
+ except as required for reasonable and customary use in describing the
765
+ origin of the Work and reproducing the content of the NOTICE file.
766
+
767
+ 7. Disclaimer of Warranty. Unless required by applicable law or
768
+ agreed to in writing, Licensor provides the Work (and each
769
+ Contributor provides its Contributions) on an "AS IS" BASIS,
770
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
771
+ implied, including, without limitation, any warranties or conditions
772
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
773
+ PARTICULAR PURPOSE. You are solely responsible for determining the
774
+ appropriateness of using or redistributing the Work and assume any
775
+ risks associated with Your exercise of permissions under this License.
776
+
777
+ 8. Limitation of Liability. In no event and under no legal theory,
778
+ whether in tort (including negligence), contract, or otherwise,
779
+ unless required by applicable law (such as deliberate and grossly
780
+ negligent acts) or agreed to in writing, shall any Contributor be
781
+ liable to You for damages, including any direct, indirect, special,
782
+ incidental, or consequential damages of any character arising as a
783
+ result of this License or out of the use or inability to use the
784
+ Work (including but not limited to damages for loss of goodwill,
785
+ work stoppage, computer failure or malfunction, or any and all
786
+ other commercial damages or losses), even if such Contributor
787
+ has been advised of the possibility of such damages.
788
+
789
+ 9. Accepting Warranty or Additional Liability. While redistributing
790
+ the Work or Derivative Works thereof, You may choose to offer,
791
+ and charge a fee for, acceptance of support, warranty, indemnity,
792
+ or other liability obligations and/or rights consistent with this
793
+ License. However, in accepting such obligations, You may act only
794
+ on Your own behalf and on Your sole responsibility, not on behalf
795
+ of any other Contributor, and only if You agree to indemnify,
796
+ defend, and hold each Contributor harmless for any liability
797
+ incurred by, or claims asserted against, such Contributor by reason
798
+ of your accepting any such warranty or additional liability.
799
+
800
+ END OF TERMS AND CONDITIONS
801
+
802
+ APPENDIX: How to apply the Apache License to your work.
803
+
804
+ To apply the Apache License to your work, attach the following
805
+ boilerplate notice, with the fields enclosed by brackets "{}"
806
+ replaced with your own identifying information. (Don't include
807
+ the brackets!) The text should be enclosed in the appropriate
808
+ comment syntax for the file format. We also recommend that a
809
+ file or class name and description of purpose be included on the
810
+ same "printed page" as the copyright notice for easier
811
+ identification within third-party archives.
812
+
813
+ Copyright {yyyy} {name of copyright owner}
814
+
815
+ Licensed under the Apache License, Version 2.0 (the "License");
816
+ you may not use this file except in compliance with the License.
817
+ You may obtain a copy of the License at
818
+
819
+ http://www.apache.org/licenses/LICENSE-2.0
820
+
821
+ Unless required by applicable law or agreed to in writing, software
822
+ distributed under the License is distributed on an "AS IS" BASIS,
823
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
824
+ See the License for the specific language governing permissions and
825
+ limitations under the License.
826
+
827
+ ```
828
+
619
829
  ### @hapi/hapi
620
830
 
621
831
  This product includes source derived from [@hapi/hapi](https://github.com/hapijs/hapi) ([v21.3.2](https://github.com/hapijs/hapi/tree/v21.3.2)), distributed under the [BSD-3-Clause License](https://github.com/hapijs/hapi/blob/v21.3.2/LICENSE.md):
@@ -2631,7 +2841,7 @@ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2631
2841
 
2632
2842
  ### undici
2633
2843
 
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):
2844
+ 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
2845
 
2636
2846
  ```
2637
2847
  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: '../',
@@ -0,0 +1,53 @@
1
+ /*
2
+ * Copyright 2023 New Relic Corporation. All rights reserved.
3
+ * SPDX-License-Identifier: New Relic Pre-Release
4
+ */
5
+
6
+
7
+ const grpcServiceMap = new Map();
8
+ const grpcMethodMap = new Map();
9
+ /**
10
+ * Utility to set service based on key value pair
11
+ * @param {*} key
12
+ * @param {*} value
13
+ */
14
+ function setService(key, value){
15
+ grpcServiceMap.set(key,value);
16
+ }
17
+
18
+ /**
19
+ * Utility to get service corresponding to key
20
+ * @param {*} key
21
+ * @returns
22
+ */
23
+ function getService(key){
24
+ return grpcServiceMap.get(key);
25
+ }
26
+
27
+ /**
28
+ * Utility to set method object
29
+ * @param {*} key
30
+ * @param {*} value
31
+ */
32
+ function setMethod(key, value){
33
+ grpcMethodMap.set(key,value);
34
+ }
35
+
36
+ /**
37
+ * Utility to get method object
38
+ * @param {*} key
39
+ * @returns
40
+ */
41
+ function getMethod(key){
42
+ return grpcMethodMap.get(key);
43
+ }
44
+
45
+ module.exports={
46
+ setService,
47
+ getService,
48
+ grpcServiceMap,
49
+ setMethod,
50
+ getMethod,
51
+ grpcMethodMap
52
+
53
+ }
@@ -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
  }
@@ -15,8 +15,18 @@
15
15
  */
16
16
  function getSecurityMetaData(request, interceptedArgs, traceObject, executionId, eventType, eventCategory) {
17
17
  const securityMetadata = {};
18
- const httpRequest = Object.assign({},request);
19
- if(httpRequest.tempFiles){
18
+ const rHeaders = request.headers;
19
+ try {
20
+ Object.keys(rHeaders).forEach(key => {
21
+ if (rHeaders[key]) {
22
+ rHeaders[key] = String(rHeaders[key]);
23
+ }
24
+ });
25
+ } catch (error) {
26
+ }
27
+ request.headers = rHeaders;
28
+ const httpRequest = Object.assign({}, request);
29
+ if (httpRequest.tempFiles) {
20
30
  delete httpRequest.tempFiles;
21
31
  }
22
32
  securityMetadata.request = httpRequest
@@ -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
+