forked from mediamonks/node-spf-check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
422 lines (335 loc) · 14.8 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
'use strict';
const dns = require('dns');
const util = require('util');
const spfParse = require('spf-parse');
const ipaddr = require('ipaddr.js');
const tlsjs = require('tldjs');
const _ = require('lodash');
/** Result messages. */
const messages = {
None: 'Cannot assert whether or not the client host is authorized',
Neutral: 'Domain owner has explicitly stated that he cannot or does not want to assert whether or not the IP address is authorized',
Pass: 'Client is authorized to inject mail with the given identity',
Fail: 'Client is *not* authorized to use the domain in the given identity',
SoftFail: 'Domain believes the host is not authorized but is not willing to make that strong of a statement',
TempError: 'Encountered a transient error while performing the check',
PermError: 'Domain\'s published records could not be correctly interpreted',
};
/** Result values (ex. {None: 'None', Neutral: 'Neutral', ...}). */
const results = _.mapValues(messages, _.nthArg(1));
class SPFResult {
constructor(result, message) {
if (!_.has(results, result)) {
throw TypeError('Result "' + result + '" not found');
}
if (!_.isString(message) || _.isEmpty(message)) {
message = messages[result];
}
/** An string value of results constant. */
this.result = result;
/** Description text. */
this.message = message;
/** Last matched mechanism or "default" if none. Used in Received-SPF
* header field. */
this.mechanism = "default";
/** List of all matched mechanisms (order from last to first). */
this.matched = [];
}
}
class SPF {
constructor(domain, sender, options) {
if (_.isObject(domain) && _.isUndefined(sender) && _.isUndefined(options)) {
options = domain;
domain = undefined;
} else if (_.isObject(sender) && _.isUndefined(options)) {
options = sender;
sender = undefined;
}
this.domain = _.isString(domain) ? domain : _.result(options, 'domain', () => {
throw new Error('Undefined domain');
});
this.sender = _.isString(sender) ? sender : _.get(options, 'sender', 'postmaster@' + this.domain);
// If the sender has no localpart, substitute the string "postmaster"
// for the localpart.
if (!_.includes(this.sender, '@')) {
this.sender = 'postmaster@' + this.sender;
}
this.warnings = [];
this.queryDNSCount = 0;
this.options = {
/** Conforms to https://tools.ietf.org/html/rfc4408 */
version: 1,
/** Resolve all mechanisms before evaluating them. This will cause
* many DNS queries to be made and possible hit the 10 queries hard
* limit. Note that "redirect" mechanisms always resolves first no
* matter the value of this option.
*/
prefetch: false,
/** Hard limit on the number of DNS lookups, including any lookups
* caused by the use of the "include" mechanism or the "redirect"
* modifier. */
maxDNS: 10,
...options,
};
}
async resolveA(hostname, rrtype) {
return this.resolveDNS(hostname, rrtype).catch((error) => {
if(error.result === results.TempError) {
return [];
}
throw error;
});
}
async resolveMX(hostname, rrtype) {
// First performs an MX lookup.
// Ignore errors and return an empty array instead; this allows an MX mechianism to not resolve and still be valid.
// RFC is not precisely clear about this, but it can be interpreted that way.
const exchanges = await this.resolveDNS(hostname, 'MX').catch((error) => {
if(error.result === results.TempError) {
return [];
}
throw error;
});
// Check the number of exchanges to retrieve A records and limit before
// doing any DNS lookup.
if (exchanges.length >= this.options.maxDNS) {
throw new SPFResult(results.PermError, 'Limit of DNS lookups reached when processing MX mechanism');
}
// Then it performs an address lookup on each MX name returned.
let promises = exchanges
.map(exchange => this
.resolveDNS(exchange.exchange, rrtype, /*lookupLimit=*/false)
.catch(() => [])
);
await Promise
.all(promises)
.then((results) => results
.forEach((result, i) => exchanges[i].records = result)
);
return _.sortBy(exchanges, 'priority');
}
async resolveDNS(hostname, rrtype, lookupLimit) {
// Default behaviour is to throw PermError when limit is reached.
lookupLimit = _.isNil(lookupLimit) || lookupLimit === true;
if (lookupLimit && this.queryDNSCount >= this.options.maxDNS) {
throw new SPFResult(results.PermError, 'Limit of DNS lookups reached');
}
return new Promise((resolve, reject) => {
dns.resolve(hostname, rrtype, (err, records) => {
lookupLimit && this.queryDNSCount++;
if (err) {
// If the DNS lookup returns "domain does not exist",
// immediately returns the result "None".
if ((new RegExp('queryTxt (ENOTFOUND|ENODATA) ' + hostname)).test(err.message)) {
reject(new SPFResult(results.None, 'Domain does not exists'));
} else {
reject(new SPFResult(results.TempError, err.message));
}
} else {
if (rrtype === 'TXT') {
resolve(_.map(records, record => {
return _.join(record, '');
}));
} else {
resolve(records);
}
}
});
});
}
async resolveSPF(hostname, rrtype) {
// TODO resolve SPF record and use them instead of TXT if exists
const records = _.filter(await this.resolveDNS(hostname, 'TXT'), record => {
// Records that do not begin with a version section are discarded.
return _.startsWith(record, 'v=spf' + this.options.version + ' ');
});
if (records.length === 0) {
throw new SPFResult(results.None, 'Assume that the domain makes no SPF declarations');
}
if (records.length > 1) {
throw new SPFResult(results.PermError, 'There should be exactly one record remaining');
}
const record = records.pop();
if (/[^\x00-\x7f]/.test(record)) {
throw new SPFResult(results.PermError, 'Character content of the record should be encoded as US-ASCII');
}
const parsed = spfParse(record);
if (parsed.valid === false) {
throw new SPFResult(results.PermError, 'There shouldn\'t be any syntax errors');
}
if (_.has(parsed, 'messages')) {
const errors = _.filter(parsed.messages, ['type', 'error']);
if (errors.length > 0) {
// When multiple parse errors are found, return the first one so
// they can be fixed one at the time.
throw new SPFResult(results.PermError, errors.shift().message);
}
this.warnings = _.concat(this.warnings, _.map(_.filter(parsed.messages, ['type', 'warning']), 'message'));
}
// True when there is an "all" mechanism.
const catchAll = _.some(parsed.mechanisms, ['type', 'all']);
// List of parsed/resolved mechanisms to be returned.
let resolved = [];
for (let i = 0; i < parsed.mechanisms.length; i++) {
// Parsed mechanisms to be resolved recursively.
const mechanism = parsed.mechanisms[i];
if (mechanism.type === 'redirect') {
if (!catchAll) {
// Any "redirect" modifier has effect only when there is
// not an "all" mechanism.
resolved = _.concat(resolved, await this.resolveSPF(mechanism.value, rrtype));
}
continue;
}
if (mechanism.type === 'a') {
mechanism.resolve = async () => {
return { records: await this.resolveA(mechanism.value || hostname, rrtype) };
};
}
if (mechanism.type === 'mx') {
mechanism.resolve = async () => {
return { exchanges: await this.resolveMX(mechanism.value || hostname, rrtype) };
};
}
if (mechanism.type === 'ip4' || mechanism.type === 'ip6') {
// If ip4-cidr-length is omitted, it is taken to be "/32".
// If ip6-cidr-length is omitted, it is taken to be "/128".
if (mechanism.value.indexOf('/') === -1) {
mechanism.value += mechanism.type === 'ip4' ? '/32' : '/128';
}
try {
mechanism.address = ipaddr.parseCIDR(mechanism.value);
} catch (err) {
throw new SPFResult(results.PermError, 'Malformed "' + mechanism.type + '" address');
}
}
if (mechanism.type === 'include') {
mechanism.resolve = async () => {
return { includes: await this.resolveSPF(mechanism.value, rrtype) };
};
}
if (this.options.prefetch && mechanism.resolve) {
// Early fetch all DNS records before any evaluation. Will fail
// fast in some cases that will pass without.
_.assign(mechanism, await mechanism.resolve());
}
resolved.push(mechanism);
if (mechanism.type === 'all') {
break; // Mechanisms after "all" will never be resolved.
}
}
return resolved;
}
async check(ip) {
if (!ipaddr.isValid(ip)) {
return new SPFResult(results.None, 'Malformed IP for comparison');
}
if (!tlsjs.isValid(this.domain)) {
return new SPFResult(results.None, 'No SPF record can be found on malformed domain');
}
// List of parsed mechanisms done by `spf-parse` module. Each value is
// an object that contains type and value.
let mechanisms;
// Parsed IP address.
const addr = ipaddr.parse(ip);
try {
mechanisms = await this.resolveSPF(this.domain,
// When any mechanism fetches host addresses to compare with
// given IP, when it is an IPv4 address, A records are fetched,
// when it is an IPv6 address, AAAA records are fetched instead.
addr.kind() === 'ipv4' ? 'A' : 'AAAA'
);
} catch (err) {
if (err instanceof SPFResult) {
return err;
}
return new SPFResult(results.TempError, err.message);
}
if (mechanisms.length === 0) {
// This is a last minute check that may never get called because
// there should always be the version mechanism.
return new SPFResult(results.TempError);
}
try {
return await this.evaluate(mechanisms, addr);
} catch (err) {
if (err instanceof SPFResult) {
return err;
}
return new SPFResult(results.PermError, err.message);
}
}
async evaluate(mechanisms, addr) {
// TODO implement exp
for (let i = 0; i < mechanisms.length; i++) {
const mechanism = mechanisms[i];
if (!this.options.prefetch && mechanism.resolve) {
_.assign(mechanism, await mechanism.resolve());
}
if (mechanism.type === 'include') {
mechanism.evaluated = await this.evaluate(mechanism.includes, addr);
}
if (this.match(mechanism, addr)) {
const result = new SPFResult(mechanism.prefixdesc);
result.mechanism = mechanism.type;
result.matched = [mechanism.type];
if (mechanism.type === 'include') {
result.matched = _.merge(result.matched, mechanism.evaluated.matched);
}
return result;
}
}
// If none of the mechanisms match, then returns a result of "Neutral",
// just as if "?all" were specified as the last directive.
return new SPFResult(results.Neutral);
}
match(mechanism, addr) {
switch (mechanism.type) {
case 'version':
if (mechanism.value !== 'spf' + this.options.version) {
throw new SPFResult(results.PermError, 'Version "' + mechanism.value + '" not supported');
}
return false;
case 'a':
return _.includes(mechanism.records, addr.toString());
case 'mx':
for (let i = 0; i < mechanism.exchanges.length; i++) {
if (_.includes(mechanism.exchanges[i].records, addr.toString())) {
return true;
}
}
return false;
case 'ip4':
case 'ip6':
// The parsed CIDR is stored in `mechanism.address` as a tuple
// with the IPv4/IPv6 instance as first element and the bits as
// second.
if (addr.kind() !== mechanism.address[0].kind()) {
return false;
}
return addr.match(mechanism.address);
case 'include':
if (mechanism.evaluated.result === results.None) {
throw new SPFResult(results.PermError, 'Validation for "include:' + mechanism.value + '" missed');
}
return mechanism.evaluated.result === results.Pass;
// TODO implement ptr
// TODO implement exists
case 'ptr':
case 'exists':
// not implemented, assume false
return false;
case 'all':
return true;
}
throw new SPFResult(results.PermError, 'Mechanism "' + mechanism.type + '" not supported');
}
}
module.exports = async function (ip, domain, sender, options) {
let spf = new SPF(domain, sender, options);
let res = await spf.check(ip);
return res.result;
};
module.exports = _.merge(module.exports, results);
module.exports.SPFResult = SPFResult;
module.exports.SPF = SPF;