-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdns.js
180 lines (140 loc) · 4.83 KB
/
dns.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
'use strict';
const crypto = require('crypto');
const d3 = require('d3');
const grok = require('node-grok');
const tz = require('timezone/loaded');
const esDateFormat = d3.timeFormat('%Y.%m.%d');
const fileDateFormat = d3.timeFormat('%Y-%m-%d');
const localHourFormat = d3.timeFormat('%H');
var _lookupCounter = 1;
var _recordFinderBuffer = Buffer.allocUnsafe(2);
function shortenBase64(str) {
var len = str.length;
while(len && str[len - 1] === '=')
len--;
while(len && str[len - 1] === 'A')
len--;
return str.substr(0, len);
}
function makeRecordFinder() {
if(++_lookupCounter >= 65535)
_lookupCounter = 1;
_recordFinderBuffer.writeUInt16LE(_lookupCounter, 0);
return shortenBase64(_recordFinderBuffer.toString('base64'));
}
const patterns = grok.loadDefaultSync();
patterns.createPattern('%{DATE_US} %{HOUR}:%{MINUTE}:%{SECOND} [AP]M', 'FULLDATE');
patterns.createPattern('[0-9A-Z]{16}', 'PACKETID');
patterns.createPattern('[ R]', 'RESPONSEFLAG');
patterns.createPattern('[ A][ T][ D][ R]', 'FLAGS');
const startPattern = patterns.createPattern('^%{FULLDATE:eventTime} %{WORD:thread} %{WORD:eventType}\\s+%{GREEDYDATA:message}$');
const packetPattern = patterns.createPattern('^%{PACKETID} %{WORD:protocol} %{WORD} %{IPV4:clientIp}\\s+%{WORD:xid} %{RESPONSEFLAG:responseFlag} %{WORD:opcode} \\[%{WORD:hexflags} %{FLAGS:flags}\\s+%{WORD:responseCode}\\] %{WORD:questionType} +%{GREEDYDATA:questionName}$');
const eventTimeParse = d3.timeParse('%-m/%-d/%Y %-I:%M:%S %p');
function preprocess(ctx, line) {
return line;
}
function process(ctx, line) {
if(line === '' ||
line.startsWith('\t') ||
line.startsWith('DNS Server log file creation at ') ||
line.startsWith('Log file wrap at ') ||
line.startsWith('Message logging key '))
return;
const startParsed = startPattern.parseSync(line);
if(!startParsed) {
console.log('!!! FAILED TO PARSE ' + line);
return;
}
if(startParsed.eventType === 'EVENT') {
console.log('EVENT: ' + startParsed.message);
return;
}
else if(startParsed.eventType !== 'PACKET') {
console.log(`!!! UNKNOWN EVENT TYPE ${startParsed.eventType}: ${startParsed.message}`);
return;
}
const parsed = packetPattern.parseSync(startParsed.message);
if(!parsed) {
console.log('!!! FAILED TO PARSE PACKET ' + line);
return;
}
let result;
if(parsed.responseFlag === 'R') {
//console.log(JSON.stringify(parsed));
let domainName = parseQName(parsed.questionName);
if(domainName === '') {
domainName = null;
}
else if(!domainName) {
console.log(`!!! FAILED TO PARSE QNAME ${JSON.stringify(parsed.questionName, null, 2)} (${JSON.stringify(domainName, null, 2)})`);
return;
}
domainName = domainName && domainName.toLowerCase();
const domainList = makeDomainList(domainName);
result = {
log: {
reportingIp: ctx.meta.remoteAddress,
receivingPort: ctx.meta.localPort,
receiveTime: ctx.meta.receiveTime,
eventTime: eventTimeParse(startParsed.eventTime),
source: {
ip: parsed.clientIp,
},
target: {
fqdn: domainName,
fqdnBreakdown: domainList,
},
protocol: (parsed.protocol === 'UDP') ? 17 : 6,
},
dns: {
packetId: parsed.packetId,
opcode: parsed.opcode,
responseCode: parsed.responseCode,
flags: {
authoritative: parsed.flags[0] === 'A',
truncated: parsed.flags[1] === 'T',
recursionDesired: parsed.flags[2] === 'D',
recursionAvailable: parsed.flags[3] === 'R',
},
questionType: parsed.questionType,
topDomain: domainList && domainList[0],
secondaryDomain: domainList && domainList[1],
}
};
if(!result.log.eventTime) {
console.log(`---- FAILED TO PARSE eventTime ${parsed.eventTime}`);
return;
}
//console.log(JSON.stringify(result, null, 2));
ctx.sendElasticsearch('dns-' + esDateFormat(ctx.meta.receiveTime), 'dns');
ctx.sendFile(`${ctx.meta.remoteAddress}/${fileDateFormat(ctx.meta.receiveTime)}/dns-${localHourFormat(ctx.meta.receiveTime)}.jsonlog`);
return result;
}
}
function parseQName(str) {
if(str[0] !== '(')
return null;
let start = 0;
const result = [];
for(;;) {
var end = str.indexOf(')', start);
const count = +str.substring(start + 1, end);
if(isNaN(count))
return null;
if(count === 0)
return result.join('.');
const wordStart = end + 1, wordEnd = wordStart + count;
result.push(str.substring(end + 1, end + 1 + count));
start = end + 1 + count;
}
}
function makeDomainList(domain) {
if(!domain)
return null;
const domains = [];
const domainList = domain.split('.');
for(let i = 1; i <= domainList.length; i++) {
domains.push(domainList.slice(-i).join('.'));
}
return domains;
}