-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.logV2.js
258 lines (181 loc) · 9.89 KB
/
server.logV2.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
/* eslint no-console: 0 */
'use strict';
// mms.js
const {SMTPServer} = require('smtp-server');
const SMTPConnection = require('nodemailer/lib/smtp-connection');
const log4js = require('log4js');
const axios = require('axios');
const crypto = require('crypto');
const constants = require('./constants');
log4js.configure({
appenders: {
everything: { type: 'dateFile', filename: 'log/all-the-logs.log' }
},
categories: {
default: { appenders: [ 'everything' ], level: constants.LOGLEVEL }
}
});
const logger = log4js.getLogger();
logger.level = constants.LOGLEVEL;
let connCount = 0;
function computeHash(data) {
return crypto.createHash('sha256').update(data).digest('hex');
}
function checkHash(initial, current) {
return initial === current;
}
const server = new SMTPServer({
// disable STARTTLS to allow authentication in clear text mode
banner: 'Welcome to the KONTXT SMTP MTA Emulator',
disabledCommands: ['STARTTLS', 'AUTH'],
logger: true,
size: constants.MAXSIZE,
maxClients: constants.MAXCLIENTS,
onConnect ( session, callback ) {
connCount++;
logger.info( 'Number of concurrent connections: ' + connCount );
return callback();
},
onClose( session ) {
if( connCount >= 1 ) {
connCount--;
}
},
onData (stream, session, callback ) {
let chunks = [];
let smtpEntryHash = '';
stream.pipe(process.stdout); // print message to console
stream.on( 'data', (chunk) => {
chunks.push(chunk);
});
stream.on('end', () => {
// keep message AS IS in raw format
let rawSmtp = Buffer.concat(chunks)
logger.info( `Message ${computeHash(rawSmtp)} received` );
smtpEntryHash = computeHash(rawSmtp);
logger.debug( 'Payload features: ' + constants.KONTXTFEATURE );
logger.debug( 'Payload rawSmtp: ' + rawSmtp.toString() );
//establish connection to SVR remote MTA
let connection = new SMTPConnection( {
port: constants.DESTPORT,
host: constants.DESTIP,
secure: false,
ignoreTLS: true,
connectionTimeout: 5000,
debug: false,
name: 'mms.relay.kontxt.cloud'
});
// if this is set, we will simply relay, return, and not scan
if( constants.SKIPOBANSCAN ) {
connection.connect(() => {
logger.error('Scan skipped. CONNECTION ESTABLISHED TO REMOTE MTA ');
connection.send({
from: session.envelope.mailFrom,
to: session.envelope.rcptTo
}, rawSmtp, function (err, info) {
logger.error('Scan skipped. Caught ObanMicro API Error: relayed to remote MTA.' +
'; Message envelope from: ' + session.envelope.mailFrom.address +
'; Message envelope to: ' + session.envelope.rcptTo[0].address);
logger.info(`Scan skipped. Message ${computeHash(rawSmtp)} forwarded to MTA`);
connection.quit();
return callback(null, 'Message OK.');
});
});
} else {
axios.post(constants.KONTXTAPI, {
features: constants.KONTXTFEATURE,
// convert message to string assuming (default) utf8 encoding
// (a groundless assumption, but we need to satisfy kontxt API)
rawSmtp: rawSmtp.toString(),
maxContentLength: constants.MAXSIZE,
maxBodyLength: constants.MAXSIZE
})
.then((res) => {
let kontxtResult = '';
if (undefined !== res.data.data[0]) {
const inflightResults = res.data.data[0][constants.KONTXTFEATURE + '_results'];
kontxtResult = inflightResults.spam;
logger.debug('Raw block result from payload: ' + kontxtResult);
}
if (kontxtResult === true) {
logger.debug(`Message ${computeHash(rawSmtp)} blocked by Kontxt`);
logger.info(`Message ${computeHash(rawSmtp)} blocked by Inflight. Response: ` + kontxtResult +
'; envelopeFrom: ' + session.envelope.mailFrom.address +
' envelopeTo: ' + session.envelope.rcptTo[0].address);
let err = new Error('Message blocked. Inflight Response: ' + kontxtResult);
err.responseCode = constants.DROPCODE;
return callback(err);
}
logger.info(`Message ${computeHash(rawSmtp)} allowed by Kontxt`);
connection.on('error', function (err) {
logger.info(`Message ${computeHash(rawSmtp)} needs to be retried, MTA likely down`);
logger.error('Could not connect to SVR MTA: ' + err +
'; envelopeFrom: ' + session.envelope.mailFrom.address +
' envelopeTo: ' + session.envelope.rcptTo[0].address);
err = new Error('Message could not be sent, remote relay down. Inflight Response: ' + kontxtResult);
err.responseCode = constants.HASHCHECKCODE;
return callback(err);
});
connection.connect(() => {
logger.debug('CONNECTION ESTABLISHED TO REMOTE MTA');
if (checkHash(smtpEntryHash, computeHash(rawSmtp))) {
connection.send({
from: session.envelope.mailFrom,
to: session.envelope.rcptTo
}, rawSmtp, function (err, info) {
logger.info(`Message ${computeHash(rawSmtp)} relayed to remote MTA. Response: ` + kontxtResult +
'; envelopeFrom: ' + session.envelope.mailFrom.address +
' envelopeTo: ' + session.envelope.rcptTo[0].address);
logger.debug(`Message ${computeHash(rawSmtp)} forwarded to MTA`);
connection.quit();
return callback(null, "Message OK. Inflight Response: " + kontxtResult);
});
} else {
logger.error('Hash check failure. Message not relayed. Entry: ' + smtpEntryHash + ' Current: ' + computeHash(rawSmtp));
let err = new Error('Hash check failure. Message not relayed.');
err.responseCode = constants.RELAYDOWNCODE;
return callback(err);
}
});
})
.catch((error) => {
logger.error('ObanMicro API SMTP POST ERROR CAUGHT, sending message on to SVR MTA. Message: ' + error.message);
logger.info(`Message ${computeHash(rawSmtp)} allowed, Kontxt failed`);
// something is wrong with oban api, so let's send the message back to SVR MTA
connection.on('error', function (err) {
logger.info(`Message ${computeHash(rawSmtp)} discarded, MT likely down`);
logger.error('Caught ObanMicro API Error :: Could not connect to SVR MTA: ' + err +
'; Message envelope from: ' + session.envelope.mailFrom.address +
'; Message envelope to: ' + session.envelope.rcptTo[0].address);
return callback(null, "Message OK but SVR MTA is not available. Envelope logged.");
});
if (checkHash(smtpEntryHash, computeHash(rawSmtp))) {
connection.connect(() => {
logger.error('Caught ObanMicro API Error: CONNECTION ESTABLISHED TO REMOTE MTA ');
connection.send({
from: session.envelope.mailFrom,
to: session.envelope.rcptTo
}, rawSmtp, function (err, info) {
logger.error('Caught ObanMicro API Error: relayed to remote MTA.' +
'; envelopeFrom: ' + session.envelope.mailFrom.address +
'; envelopeTo: ' + session.envelope.rcptTo[0].address);
logger.info(`Message ${computeHash(rawSmtp)} forwarded to MTA`);
connection.quit();
return callback(null, 'Message OK.');
});
});
} else {
logger.error('Hash check failure. Message not relayed. Entry: ' + smtpEntryHash + ' Current: ' + computeHash(rawSmtp));
let err = new Error('Hash check failure. Message not relayed.');
err.responseCode = constants.HASHCHECKCODE;
return callback(err);
}
});
}
});
},
});
server.on('error', error => {
logger.error( 'ERROR CAUGHT. Message: ' + error.message );
});
server.listen( constants.LISTENPORT );