-
Notifications
You must be signed in to change notification settings - Fork 309
/
index.js
328 lines (256 loc) · 9.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
'use strict'
const log = require('../log')
const RuleManager = require('./rule_manager')
const remoteConfig = require('./remote_config')
const {
bodyParser,
cookieParser,
multerParser,
incomingHttpRequestStart,
incomingHttpRequestEnd,
passportVerify,
queryParser,
nextBodyParsed,
nextQueryParsed,
expressProcessParams,
responseBody,
responseWriteHead,
responseSetHeader,
routerParam
} = require('./channels')
const waf = require('./waf')
const addresses = require('./addresses')
const Reporter = require('./reporter')
const appsecTelemetry = require('./telemetry')
const apiSecuritySampler = require('./api_security_sampler')
const web = require('../plugins/util/web')
const { extractIp } = require('../plugins/util/ip_extractor')
const { HTTP_CLIENT_IP } = require('../../../../ext/tags')
const { isBlocked, block, setTemplates, getBlockingAction } = require('./blocking')
const UserTracking = require('./user_tracking')
const { storage } = require('../../../datadog-core')
const graphql = require('./graphql')
const rasp = require('./rasp')
const responseAnalyzedSet = new WeakSet()
let isEnabled = false
let config
function enable (_config) {
if (isEnabled) return
try {
appsecTelemetry.enable(_config.telemetry)
graphql.enable()
if (_config.appsec.rasp.enabled) {
rasp.enable(_config)
}
setTemplates(_config)
RuleManager.loadRules(_config.appsec)
remoteConfig.enableWafUpdate(_config.appsec)
Reporter.setRateLimit(_config.appsec.rateLimit)
apiSecuritySampler.configure(_config.appsec)
UserTracking.setCollectionMode(_config.appsec.eventTracking.mode, false)
bodyParser.subscribe(onRequestBodyParsed)
multerParser.subscribe(onRequestBodyParsed)
cookieParser.subscribe(onRequestCookieParser)
incomingHttpRequestStart.subscribe(incomingHttpStartTranslator)
incomingHttpRequestEnd.subscribe(incomingHttpEndTranslator)
passportVerify.subscribe(onPassportVerify) // possible optimization: only subscribe if collection mode is enabled
queryParser.subscribe(onRequestQueryParsed)
nextBodyParsed.subscribe(onRequestBodyParsed)
nextQueryParsed.subscribe(onRequestQueryParsed)
expressProcessParams.subscribe(onRequestProcessParams)
routerParam.subscribe(onRequestProcessParams)
responseBody.subscribe(onResponseBody)
responseWriteHead.subscribe(onResponseWriteHead)
responseSetHeader.subscribe(onResponseSetHeader)
isEnabled = true
config = _config
} catch (err) {
log.error('[ASM] Unable to start AppSec', err)
disable()
}
}
function onRequestBodyParsed ({ req, res, body, abortController }) {
if (body === undefined || body === null) return
if (!req) {
const store = storage.getStore()
req = store?.req
}
const rootSpan = web.root(req)
if (!rootSpan) return
const results = waf.run({
persistent: {
[addresses.HTTP_INCOMING_BODY]: body
}
}, req)
handleResults(results, req, res, rootSpan, abortController)
}
function onRequestCookieParser ({ req, res, abortController, cookies }) {
if (!cookies || typeof cookies !== 'object') return
const rootSpan = web.root(req)
if (!rootSpan) return
const results = waf.run({
persistent: {
[addresses.HTTP_INCOMING_COOKIES]: cookies
}
}, req)
handleResults(results, req, res, rootSpan, abortController)
}
function incomingHttpStartTranslator ({ req, res, abortController }) {
const rootSpan = web.root(req)
if (!rootSpan) return
const clientIp = extractIp(config, req)
rootSpan.addTags({
'_dd.appsec.enabled': 1,
'_dd.runtime_family': 'nodejs',
[HTTP_CLIENT_IP]: clientIp
})
const requestHeaders = Object.assign({}, req.headers)
delete requestHeaders.cookie
const persistent = {
[addresses.HTTP_INCOMING_URL]: req.url,
[addresses.HTTP_INCOMING_HEADERS]: requestHeaders,
[addresses.HTTP_INCOMING_METHOD]: req.method
}
if (clientIp) {
persistent[addresses.HTTP_CLIENT_IP] = clientIp
}
const actions = waf.run({ persistent }, req)
handleResults(actions, req, res, rootSpan, abortController)
}
function incomingHttpEndTranslator ({ req, res }) {
const persistent = {}
// we need to keep this to support other body parsers
// TODO: no need to analyze it if it was already done by the body-parser hook
if (req.body !== undefined && req.body !== null) {
persistent[addresses.HTTP_INCOMING_BODY] = req.body
}
// we need to keep this to support other cookie parsers
if (req.cookies !== null && typeof req.cookies === 'object') {
persistent[addresses.HTTP_INCOMING_COOKIES] = req.cookies
}
// we need to keep this to support nextjs
const query = req.query
if (query !== null && typeof query === 'object') {
persistent[addresses.HTTP_INCOMING_QUERY] = query
}
if (apiSecuritySampler.sampleRequest(req, res, true)) {
persistent[addresses.WAF_CONTEXT_PROCESSOR] = { 'extract-schema': true }
}
if (Object.keys(persistent).length) {
waf.run({ persistent }, req)
}
waf.disposeContext(req)
Reporter.finishRequest(req, res)
}
function onPassportVerify ({ framework, login, user, success, abortController }) {
const store = storage.getStore()
const rootSpan = store?.req && web.root(store.req)
if (!rootSpan) {
log.warn('[ASM] No rootSpan found in onPassportVerify')
return
}
const results = UserTracking.trackLogin(framework, login, user, success, rootSpan)
handleResults(results, store.req, store.req.res, rootSpan, abortController)
}
function onRequestQueryParsed ({ req, res, query, abortController }) {
if (!query || typeof query !== 'object') return
if (!req) {
const store = storage.getStore()
req = store?.req
}
const rootSpan = web.root(req)
if (!rootSpan) return
const results = waf.run({
persistent: {
[addresses.HTTP_INCOMING_QUERY]: query
}
}, req)
handleResults(results, req, res, rootSpan, abortController)
}
function onRequestProcessParams ({ req, res, abortController, params }) {
const rootSpan = web.root(req)
if (!rootSpan) return
if (!params || typeof params !== 'object' || !Object.keys(params).length) return
const results = waf.run({
persistent: {
[addresses.HTTP_INCOMING_PARAMS]: params
}
}, req)
handleResults(results, req, res, rootSpan, abortController)
}
function onResponseBody ({ req, res, body }) {
if (!body || typeof body !== 'object') return
if (!apiSecuritySampler.sampleRequest(req, res)) return
// we don't support blocking at this point, so no results needed
waf.run({
persistent: {
[addresses.HTTP_INCOMING_RESPONSE_BODY]: body
}
}, req)
}
function onResponseWriteHead ({ req, res, abortController, statusCode, responseHeaders }) {
// avoid "write after end" error
if (isBlocked(res)) {
abortController?.abort()
return
}
// avoid double waf call
if (responseAnalyzedSet.has(res)) {
return
}
const rootSpan = web.root(req)
if (!rootSpan) return
responseHeaders = Object.assign({}, responseHeaders)
delete responseHeaders['set-cookie']
const results = waf.run({
persistent: {
[addresses.HTTP_INCOMING_RESPONSE_CODE]: '' + statusCode,
[addresses.HTTP_INCOMING_RESPONSE_HEADERS]: responseHeaders
}
}, req)
responseAnalyzedSet.add(res)
handleResults(results, req, res, rootSpan, abortController)
}
function onResponseSetHeader ({ res, abortController }) {
if (isBlocked(res)) {
abortController?.abort()
}
}
function handleResults (actions, req, res, rootSpan, abortController) {
if (!actions || !req || !res || !rootSpan || !abortController) return
const blockingAction = getBlockingAction(actions)
if (blockingAction) {
block(req, res, rootSpan, abortController, blockingAction)
}
}
function disable () {
isEnabled = false
config = null
RuleManager.clearAllRules()
appsecTelemetry.disable()
graphql.disable()
rasp.disable()
remoteConfig.disableWafUpdate()
apiSecuritySampler.disable()
// Channel#unsubscribe() is undefined for non active channels
if (bodyParser.hasSubscribers) bodyParser.unsubscribe(onRequestBodyParsed)
if (multerParser.hasSubscribers) multerParser.unsubscribe(onRequestBodyParsed)
if (cookieParser.hasSubscribers) cookieParser.unsubscribe(onRequestCookieParser)
if (incomingHttpRequestStart.hasSubscribers) incomingHttpRequestStart.unsubscribe(incomingHttpStartTranslator)
if (incomingHttpRequestEnd.hasSubscribers) incomingHttpRequestEnd.unsubscribe(incomingHttpEndTranslator)
if (passportVerify.hasSubscribers) passportVerify.unsubscribe(onPassportVerify)
if (queryParser.hasSubscribers) queryParser.unsubscribe(onRequestQueryParsed)
if (nextBodyParsed.hasSubscribers) nextBodyParsed.unsubscribe(onRequestBodyParsed)
if (nextQueryParsed.hasSubscribers) nextQueryParsed.unsubscribe(onRequestQueryParsed)
if (expressProcessParams.hasSubscribers) expressProcessParams.unsubscribe(onRequestProcessParams)
if (routerParam.hasSubscribers) routerParam.unsubscribe(onRequestProcessParams)
if (responseBody.hasSubscribers) responseBody.unsubscribe(onResponseBody)
if (responseWriteHead.hasSubscribers) responseWriteHead.unsubscribe(onResponseWriteHead)
if (responseSetHeader.hasSubscribers) responseSetHeader.unsubscribe(onResponseSetHeader)
}
module.exports = {
enable,
disable,
incomingHttpStartTranslator,
incomingHttpEndTranslator
}