-
Notifications
You must be signed in to change notification settings - Fork 323
/
Copy pathlfi.js
114 lines (89 loc) · 2.64 KB
/
lfi.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
'use strict'
const { fsOperationStart, incomingHttpRequestStart } = require('../channels')
const { storage } = require('../../../../datadog-core')
const { enable: enableFsPlugin, disable: disableFsPlugin, RASP_MODULE } = require('./fs-plugin')
const { FS_OPERATION_PATH } = require('../addresses')
const waf = require('../waf')
const { RULE_TYPES, handleResult } = require('./utils')
const { isAbsolute } = require('path')
let config
let enabled
let analyzeSubscribed
function enable (_config) {
config = _config
if (enabled) return
enabled = true
incomingHttpRequestStart.subscribe(onFirstReceivedRequest)
}
function disable () {
if (fsOperationStart.hasSubscribers) fsOperationStart.unsubscribe(analyzeLfi)
if (incomingHttpRequestStart.hasSubscribers) incomingHttpRequestStart.unsubscribe(onFirstReceivedRequest)
disableFsPlugin(RASP_MODULE)
enabled = false
analyzeSubscribed = false
}
function onFirstReceivedRequest () {
// nodejs unsubscribe during publish bug: https://github.com/nodejs/node/pull/55116
process.nextTick(() => {
incomingHttpRequestStart.unsubscribe(onFirstReceivedRequest)
})
enableFsPlugin(RASP_MODULE)
if (!analyzeSubscribed) {
fsOperationStart.subscribe(analyzeLfi)
analyzeSubscribed = true
}
}
function analyzeLfi (ctx) {
const store = storage('legacy').getStore()
if (!store) return
const { req, fs, res } = store
if (!req || !fs) return
getPaths(ctx, fs).forEach(path => {
const ephemeral = {
[FS_OPERATION_PATH]: path
}
const raspRule = { type: RULE_TYPES.LFI }
const result = waf.run({ ephemeral }, req, raspRule)
handleResult(result, req, res, ctx.abortController, config)
})
}
function getPaths (ctx, fs) {
// these properties could have String, Buffer, URL, Integer or FileHandle types
const pathArguments = [
ctx.dest,
ctx.existingPath,
ctx.file,
ctx.newPath,
ctx.oldPath,
ctx.path,
ctx.prefix,
ctx.src,
ctx.target
]
return pathArguments
.map(path => pathToStr(path))
.filter(path => shouldAnalyze(path, fs))
}
function pathToStr (path) {
if (!path) return
if (typeof path === 'string' ||
path instanceof String ||
path instanceof Buffer ||
path instanceof URL) {
return path.toString()
}
}
function shouldAnalyze (path, fs) {
if (!path) return
const notExcludedRootOp = !fs.opExcluded && fs.root
return notExcludedRootOp && (isAbsolute(path) || path.includes('../') || shouldAnalyzeURLFile(path, fs))
}
function shouldAnalyzeURLFile (path, fs) {
if (path.startsWith('file://')) {
return shouldAnalyze(path.substring(7), fs)
}
}
module.exports = {
enable,
disable
}