-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathinspectDNSLookupCalls.ts
More file actions
253 lines (220 loc) · 8.17 KB
/
inspectDNSLookupCalls.ts
File metadata and controls
253 lines (220 loc) · 8.17 KB
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
import { isIP, type LookupFunction } from "net";
import { LookupAddress } from "dns";
import { Agent } from "../../agent/Agent";
import { attackKindHumanName } from "../../agent/Attack";
import { getContext } from "../../agent/Context";
import { cleanupStackTrace } from "../../helpers/cleanupStackTrace";
import { escapeHTML } from "../../helpers/escapeHTML";
import { isPlainObject } from "../../helpers/isPlainObject";
import { getMetadataForSSRFAttack } from "./getMetadataForSSRFAttack";
import { isPrivateIP } from "./isPrivateIP";
import { isIMDSIPAddress, isTrustedHostname } from "./imds";
import { RequestContextStorage } from "../../sinks/undici/RequestContextStorage";
import { findHostnameInContext } from "./findHostnameInContext";
import { getRedirectOrigin } from "./getRedirectOrigin";
import { getPortFromURL } from "../../helpers/getPortFromURL";
import { getLibraryRoot } from "../../helpers/getLibraryRoot";
import { cleanError } from "../../helpers/cleanError";
export function inspectDNSLookupCalls(
lookup: Function,
agent: Agent,
module: string,
operation: string,
url?: URL,
stackTraceCallingLocation?: Error
): LookupFunction {
return function inspectDNSLookup(...args: unknown[]) {
const hostname =
args.length > 0 && typeof args[0] === "string" ? args[0] : undefined;
const callback = args.find((arg) => typeof arg === "function");
// If the hostname is an IP address, or if the callback is missing, we don't need to inspect the resolved IPs
if (!hostname || isIP(hostname) || !callback) {
return lookup(...args);
}
const options = args.find((arg) => isPlainObject(arg)) as
| Record<string, unknown>
| undefined;
const argsToApply = options
? [
hostname,
options,
wrapDNSLookupCallback(
callback as Function,
hostname,
module,
agent,
operation,
url,
stackTraceCallingLocation
),
]
: [
hostname,
wrapDNSLookupCallback(
callback as Function,
hostname,
module,
agent,
operation,
url,
stackTraceCallingLocation
),
];
lookup(...argsToApply);
};
}
// eslint-disable-next-line max-lines-per-function
function wrapDNSLookupCallback(
callback: Function,
hostname: string,
module: string,
agent: Agent,
operation: string,
urlArg?: URL,
callingLocationStackTrace?: Error
): Function {
// eslint-disable-next-line max-lines-per-function
return function wrappedDNSLookupCallback(
err: Error,
addresses: string | LookupAddress[],
family: number
) {
if (err) {
return callback(err);
}
const context = getContext();
if (context) {
const matches = agent.getConfig().getEndpoints(context);
if (matches.find((endpoint) => endpoint.forceProtectionOff)) {
// User disabled protection for this endpoint, we don't need to inspect the resolved IPs
// Just call the original callback to allow the DNS lookup
return callback(err, addresses, family);
}
}
const resolvedIPAddresses = getResolvedIPAddresses(addresses);
if (resolvesToIMDSIP(resolvedIPAddresses, hostname)) {
// Block stored SSRF attack that target IMDS IP addresses
// An attacker could have stored a hostname in a database that points to an IMDS IP address
// We don't check if the user input contains the hostname because there's no context
if (agent.shouldBlock()) {
return callback(
new Error(
`Zen has blocked ${attackKindHumanName("ssrf")}: ${operation}(...) originating from unknown source`
)
);
}
}
if (!context) {
// If there's no context, we can't check if the hostname is in the context
// Just call the original callback to allow the DNS lookup
return callback(err, addresses, family);
}
// This is set if this resolve is part of an outgoing request that we are inspecting
const requestContext = RequestContextStorage.getStore();
let port: number | undefined;
if (urlArg) {
port = getPortFromURL(urlArg);
} else if (requestContext) {
port = requestContext.port;
}
const privateIP = resolvedIPAddresses.find(isPrivateIP);
if (!privateIP) {
// If the hostname doesn't resolve to a private IP address, it's not an SSRF attack
// Just call the original callback to allow the DNS lookup
return callback(err, addresses, family);
}
let found = findHostnameInContext(hostname, context, port);
// The hostname is not found in the context, check if it's a redirect
if (!found && context.outgoingRequestRedirects) {
let url: URL | undefined;
// Url arg is passed when wrapping node:http(s), but not for undici / fetch because of the way they are wrapped
// For undici / fetch we need to get the url from the request context, which is an additional async context for outgoing requests,
// not to be confused with the "normal" context used in wide parts of this library
if (urlArg) {
url = urlArg;
} else if (requestContext) {
url = new URL(requestContext.url);
}
if (url) {
// Get the origin of the redirect chain (the first URL in the chain), if the URL is the result of a redirect
const redirectOrigin = getRedirectOrigin(
context.outgoingRequestRedirects,
url
);
// If the URL is the result of a redirect, get the origin of the redirect chain for reporting the attack source
if (redirectOrigin) {
found = findHostnameInContext(
redirectOrigin.hostname,
context,
getPortFromURL(redirectOrigin)
);
}
}
}
if (!found) {
// If we can't find the hostname in the context, it's not an SSRF attack
// Just call the original callback to allow the DNS lookup
return callback(err, addresses, family);
}
const isBypassedIP =
context &&
context.remoteAddress &&
agent.getConfig().isBypassedIP(context.remoteAddress);
if (isBypassedIP) {
// If the IP address is allowed, we don't need to block the request
// Just call the original callback to allow the DNS lookup
return callback(err, addresses, family);
}
// Used to get the stack trace of the calling location
// We don't throw the error, we just use it to get the stack trace
const stackTraceError = callingLocationStackTrace || new Error();
agent.onDetectedAttack({
module: module,
operation: operation,
kind: "ssrf",
source: found.source,
blocked: agent.shouldBlock(),
stack: cleanupStackTrace(stackTraceError.stack!, getLibraryRoot()),
paths: found.pathsToPayload,
metadata: getMetadataForSSRFAttack({ hostname, port }),
request: context,
payload: found.payload,
});
if (agent.shouldBlock()) {
return callback(
cleanError(
new Error(
`Zen has blocked ${attackKindHumanName("ssrf")}: ${operation}(...) originating from ${found.source}${escapeHTML((found.pathsToPayload || []).join())}`
)
)
);
}
// If the attack should not be blocked
// Just call the original callback to allow the DNS lookup
return callback(err, addresses, family);
};
}
function getResolvedIPAddresses(addresses: string | LookupAddress[]): string[] {
const resolvedIPAddresses: string[] = [];
for (const address of Array.isArray(addresses) ? addresses : [addresses]) {
if (typeof address === "string") {
resolvedIPAddresses.push(address);
continue;
}
if (isPlainObject(address) && address.address) {
resolvedIPAddresses.push(address.address);
}
}
return resolvedIPAddresses;
}
function resolvesToIMDSIP(
resolvedIPAddresses: string[],
hostname: string
): boolean {
// Allow access to Google Cloud metadata service as you need to set specific headers to access it
// We don't want to block legitimate requests
if (isTrustedHostname(hostname)) {
return false;
}
return resolvedIPAddresses.some((ip) => isIMDSIPAddress(ip));
}