forked from serverless-dns/serverless-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.js
305 lines (264 loc) · 9.12 KB
/
plugin.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
/*
* Copyright (c) 2021 RethinkDNS and its authors.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { services } from "./svc.js";
import * as bufutil from "../commons/bufutil.js";
import * as dnsutil from "../commons/dnsutil.js";
import * as envutil from "../commons/envutil.js";
import * as util from "../commons/util.js";
export default class RethinkPlugin {
/**
* @param {{request: Request}} event
*/
constructor(event) {
if (!services.ready) throw new Error("services not ready");
/**
* Parameters of RethinkPlugin which may be used by individual plugins.
*/
this.parameter = new Map();
const rxid = util.rxidFromHeader(event.request.headers) || util.xid();
this.registerParameter("rxid", "[rx." + rxid + "]");
// caution: event isn't an event on nodejs, but event.request is a request
this.registerParameter("request", event.request);
// TODO: a more generic way for plugins to queue events on all platforms
// dispatcher fn when called, fails with 'illegal invocation' if not
// bound explicitly to 'event' (since it then executes in the context
// of which-ever obj calls it): stackoverflow.com/a/9678166
this.registerParameter("dispatcher", event.waitUntil.bind(event));
this.log = log.withTags("RethinkPlugin");
this.plugin = [];
this.registerPlugin(
"userOp",
services.userOp,
["rxid", "request", "isDnsMsg"],
this.userOpCallback,
false
);
this.registerPlugin(
"cacheOnlyResolver",
services.dnsCacheHandler,
["rxid", "userBlocklistInfo", "requestDecodedDnsPacket", "isDnsMsg"],
this.dnsCacheCallBack,
false
);
this.registerPlugin(
"commandControl",
services.commandControl,
["rxid", "request", "isDnsMsg"],
this.commandControlCallBack,
false
);
this.registerPlugin(
"dnsResolver",
services.dnsResolver,
[
"rxid",
"dispatcher",
"request",
// resolver-url overriden by user-op
"userDnsResolverUrl",
"userBlocklistInfo",
"domainBlockstamp",
"requestDecodedDnsPacket",
"requestBodyBuffer",
],
this.dnsResolverCallBack,
false
);
}
registerParameter(k, v) {
this.parameter.set(k, v);
}
registerPlugin(
pluginName,
module,
parameter,
callBack,
continueOnStopProcess
) {
this.plugin.push({
name: pluginName,
module: module,
param: parameter,
callBack: callBack,
continueOnStopProcess: continueOnStopProcess,
});
}
async execute() {
const io = this.io;
const rxid = this.parameter.get("rxid");
const t = this.log.startTime("exec-plugin-" + rxid);
for (const p of this.plugin) {
if (io.stopProcessing && !p.continueOnStopProcess) {
continue;
}
this.log.lapTime(t, rxid, p.name, "send-io");
const res = await p.module.RethinkModule(
generateParam(this.parameter, p.param)
);
this.log.lapTime(t, rxid, p.name, "got-res");
if (typeof p.callBack === "function") {
await p.callBack.call(this, res, io);
}
this.log.lapTime(t, rxid, p.name, "post-callback");
}
this.log.endTime(t);
}
/**
* params
* @param {*} response
* @param {*} io
*/
async commandControlCallBack(response, io) {
const rxid = this.parameter.get("rxid");
const r = response.data;
this.log.d(rxid, "command-control response");
if (!util.emptyObj(r) && r.stopProcessing) {
this.log.d(rxid, "command-control reply", r);
io.hResponse(r.httpResponse);
}
}
/**
* Adds "userBlocklistInfo" and "dnsResolverUrl" to RethinkPlugin params
* @param {*} response - Contains `data` which is `userBlocklistInfo`
* @param {*} io
*/
async userOpCallback(response, io) {
const rxid = this.parameter.get("rxid");
const r = response.data;
this.log.d(rxid, "user-op response");
if (response.isException) {
this.log.w(rxid, "unexpected err userOp", r);
this.loadException(rxid, response, io);
} else if (!util.emptyObj(r)) {
// r.userBlocklistInfo and r.dnsResolverUrl may be "null"
const bi = r.userBlocklistInfo;
const rr = r.dnsResolverUrl;
this.log.d(rxid, "set user:blockInfo/resolver", bi, rr);
this.registerParameter("userBlocklistInfo", bi);
this.registerParameter("userDnsResolverUrl", rr);
} else {
this.log.i(rxid, "user-op is a no-op, possibly a command-control req");
}
}
dnsCacheCallBack(response, io) {
const rxid = this.parameter.get("rxid");
const r = response.data;
const deny = r.isBlocked;
const isAns = dnsutil.isAnswer(r.dnsPacket);
const noErr = dnsutil.rcodeNoError(r.dnsPacket);
this.log.d(rxid, "crr: block?", deny, "ans?", isAns, "noerr", noErr);
if (response.isException) {
this.loadException(rxid, response, io);
} else if (deny) {
// TODO: create block packets/buffers in dnsBlocker.js
io.dnsBlockResponse(r.flag);
} else if (isAns) {
this.registerParameter("responseBodyBuffer", r.dnsBuffer);
this.registerParameter("responseDecodedDnsPacket", r.dnsPacket);
io.dnsResponse(r.dnsBuffer, r.dnsPacket, r.flag);
} else {
this.registerParameter("domainBlockstamp", r.stamps);
this.log.d(rxid, "resolve query; no response from cache-handler");
}
}
/**
* Adds "responseBodyBuffer" (arrayBuffer of dns response from upstream
* resolver) to RethinkPlugin params
* @param {*} response
* @param {*} io
*/
dnsResolverCallBack(response, io) {
const rxid = this.parameter.get("rxid");
const r = response.data;
const deny = r.isBlocked;
// dns packets may have no answers, but still be a valid response
// for example, servfail do not contain any answers, whereas
// nxdomain has an authority-section (but no answers).
const isAns = dnsutil.isAnswer(r.dnsPacket);
const noErr = dnsutil.rcodeNoError(r.dnsPacket);
this.log.d(rxid, "rr: block?", deny, "ans?", isAns, "noerr?", noErr);
if (deny) {
// TODO: create block packets/buffers in dnsBlocker.js?
io.dnsBlockResponse(r.flag);
} else if (response.isException || !isAns) {
// if not blocked, but then, no-ans or is-exception, then:
this.loadException(rxid, response, io);
} else {
this.registerParameter("responseBodyBuffer", r.dnsBuffer);
this.registerParameter("responseDecodedDnsPacket", r.dnsPacket);
io.dnsResponse(r.dnsBuffer, r.dnsPacket, r.flag);
}
}
loadException(rxid, response, io) {
this.log.e(rxid, "exception", JSON.stringify(response));
io.dnsExceptionResponse(response);
}
async initIoState(io) {
this.io = io;
const request = this.parameter.get("request");
const rxid = this.parameter.get("rxid");
const isDnsMsg = util.isDnsMsg(request);
const isGwReq = util.isGatewayRequest(request);
let question = null;
io.id(rxid);
this.registerParameter("isDnsMsg", isDnsMsg);
// nothing to do if the current request isn't a dns question
if (!isDnsMsg) {
// throw away any request that is not a dns-msg since cc.js
// processes non-dns msgs only via GET, while rest of the
// plugins process only dns-msgs via GET and POST.
if (!util.isGetRequest(request)) {
this.log.i(rxid, "not a dns-msg, not a GET req either", request);
io.hResponse(util.respond405());
return;
}
}
// else: treat doh as if it was a dns-msg iff "dns" query-string is set
question = await extractDnsQuestion(request);
// not a dns request
if (bufutil.emptyBuf(question)) return;
if (isGwReq) io.gatewayAnswersOnly(envutil.gwip4(), envutil.gwip6());
try {
const questionPacket = dnsutil.decode(question);
this.registerParameter("isDnsMsg", true);
this.log.d(rxid, "cur-ques", JSON.stringify(questionPacket.questions));
io.decodedDnsPacket = questionPacket;
this.registerParameter("requestDecodedDnsPacket", questionPacket);
this.registerParameter("requestBodyBuffer", question);
} catch (e) {
// err if question is not a valid dns-packet
this.log.d(rxid, "cannot decode dns query; may be cc GET req?");
// TODO: io.hResponse(util.respond400()) instead?
// at this point: req is GET and has "dns" in its url-string
// but: is not a valid dns request
return;
}
}
}
/**
* Retrieves parameters of a plugin
* @param {String[]} list - Parameters of a plugin
* @returns - Object of plugin parameters
*/
function generateParam(parameter, list) {
const out = {};
for (const key of list) {
out[key] = parameter.get(key) || null;
}
return out;
}
async function extractDnsQuestion(request) {
if (util.isPostRequest(request)) {
return await request.arrayBuffer();
} else {
// TODO: okay to assume GET request?
const queryString = new URL(request.url).searchParams;
const dnsQuery = queryString.get("dns");
return bufutil.base64ToBytes(dnsQuery);
}
}