2* @description MeshCentral Intel(R) AMT Interceptor
3* @author Ylian Saint-Hilaire
4* @copyright Intel Corporation 2018-2022
10/*xjslint plusplus: true */
11/*xjslint maxlen: 256 */
13/*jshint strict: false */
14/*jshint esversion: 6 */
17const crypto = require('crypto');
18const common = require('./common.js');
20var HttpInterceptorAuthentications = {};
21//var RedirInterceptorAuthentications = {};
23// Construct a HTTP interceptor object
24module.exports.CreateHttpInterceptor = function (args) {
27 // Create a random hex string of a given length
28 obj.randomValueHex = function (len) { return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len); };
31 obj.amt = { acc: '', mode: 0, count: 0, error: false }; // mode: 0:Header, 1:LengthBody, 2:ChunkedBody, 3:UntilClose
32 obj.ws = { acc: '', mode: 0, count: 0, error: false, authCNonce: obj.randomValueHex(10), authCNonceCount: 1 };
33 obj.blockAmtStorage = false;
36 obj.Debug = function (msg) { console.log(msg); };
38 // Process data coming from Intel AMT
39 obj.processAmtData = function (data) {
40 obj.amt.acc += data.toString('binary'); // Add data to accumulator
43 do { datalen = data.length; data += obj.processAmtDataEx(); } while (datalen != data.length); // Process as much data as possible
44 return Buffer.from(data, 'binary');
47 // Process data coming from AMT in the accumulator
48 obj.processAmtDataEx = function () {
50 if (obj.amt.mode == 0) { // Header Mode
51 // Decode the HTTP header
52 headerend = obj.amt.acc.indexOf('\r\n\r\n');
53 if (headerend < 0) return '';
54 var headerlines = obj.amt.acc.substring(0, headerend).split('\r\n');
55 obj.amt.acc = obj.amt.acc.substring(headerend + 4);
56 obj.amt.directive = headerlines[0].split(' ');
57 var headers = headerlines.slice(1);
59 obj.amt.mode = 3; // UntilClose
61 var j = headers[i].indexOf(':');
63 var v1 = headers[i].substring(0, j).trim().toLowerCase();
64 var v2 = headers[i].substring(j + 1).trim();
65 obj.amt.headers[v1] = v2;
66 if (v1.toLowerCase() == 'www-authenticate') {
67 HttpInterceptorAuthentications[obj.args.host + ':' + obj.args.port] = v2;
68 } else if (v1.toLowerCase() == 'content-length') {
69 obj.amt.count = parseInt(v2);
70 if (obj.amt.count > 0) {
71 obj.amt.mode = 1; // LengthBody
73 obj.amt.mode = 0; // Header
75 } else if (v1.toLowerCase() == 'transfer-encoding' && v2.toLowerCase() == 'chunked') {
76 obj.amt.mode = 2; // ChunkedBody
81 // Reform the HTTP header
82 r = obj.amt.directive.join(' ') + '\r\n';
83 for (i in obj.amt.headers) { r += (i + ': ' + obj.amt.headers[i] + '\r\n'); }
86 } else if (obj.amt.mode == 1) { // Length Body Mode
87 // Send the body of content-length size
88 var rl = obj.amt.count;
89 if (rl < obj.amt.acc.length) rl = obj.amt.acc.length;
90 r = obj.amt.acc.substring(0, rl);
91 obj.amt.acc = obj.amt.acc.substring(rl);
93 if (obj.amt.count == 0) { obj.amt.mode = 0; }
95 } else if (obj.amt.mode == 2) { // Chunked Body Mode
96 // Send data one chunk at a time
97 headerend = obj.amt.acc.indexOf('\r\n');
98 if (headerend < 0) return '';
99 var chunksize = parseInt(obj.amt.acc.substring(0, headerend), 16);
100 if ((chunksize == 0) && (obj.amt.acc.length >= headerend + 4)) {
101 // Send the ending chunk (NOTE: We do not support trailing headers)
102 r = obj.amt.acc.substring(0, headerend + 4);
103 obj.amt.acc = obj.amt.acc.substring(headerend + 4);
106 } else if ((chunksize > 0) && (obj.amt.acc.length >= (headerend + 4 + chunksize))) {
108 r = obj.amt.acc.substring(0, headerend + chunksize + 4);
109 obj.amt.acc = obj.amt.acc.substring(headerend + chunksize + 4);
112 } else if (obj.amt.mode == 3) { // Until Close Mode
120 // Process data coming from the Browser
121 obj.processBrowserData = function (data) {
122 obj.ws.acc += data.toString('binary'); // Add data to accumulator
125 do { datalen = data.length; data += obj.processBrowserDataEx(); } while (datalen != data.length); // Process as much data as possible
126 return Buffer.from(data, 'binary');
129 // Process data coming from the Browser in the accumulator
130 obj.processBrowserDataEx = function () {
132 if (obj.ws.mode == 0) { // Header Mode
133 // Decode the HTTP header
134 headerend = obj.ws.acc.indexOf('\r\n\r\n');
135 if (headerend < 0) return '';
136 var headerlines = obj.ws.acc.substring(0, headerend).split('\r\n');
137 obj.ws.acc = obj.ws.acc.substring(headerend + 4);
138 obj.ws.directive = headerlines[0].split(' ');
139 // If required, block access to amt-storage. This is needed when web storage is not supported on CIRA.
140 if ((obj.blockAmtStorage == true) && (obj.ws.directive.length > 1) && (obj.ws.directive[1].indexOf('/amt-storage') == 0)) { obj.ws.directive[1] = obj.ws.directive[1].replace('/amt-storage', '/amt-dummy-storage'); }
141 var headers = headerlines.slice(1);
143 obj.ws.mode = 3; // UntilClose
145 var j = headers[i].indexOf(':');
147 var v1 = headers[i].substring(0, j).trim().toLowerCase();
148 var v2 = headers[i].substring(j + 1).trim();
149 obj.ws.headers[v1] = v2;
150 if (v1.toLowerCase() == 'www-authenticate') {
151 HttpInterceptorAuthentications[obj.args.host + ':' + obj.args.port] = v2;
152 } else if (v1.toLowerCase() == 'content-length') {
153 obj.ws.count = parseInt(v2);
154 if (obj.ws.count > 0) {
155 obj.ws.mode = 1; // LengthBody
157 obj.ws.mode = 0; // Header
159 } else if (v1.toLowerCase() == 'transfer-encoding' && v2.toLowerCase() == 'chunked') {
160 obj.ws.mode = 2; // ChunkedBody
165 // Insert authentication
166 if (obj.args.user && obj.args.pass && HttpInterceptorAuthentications[obj.args.host + ':' + obj.args.port]) {
167 // We have authentication data, lets use it.
168 var AuthArgs = obj.GetAuthArgs(HttpInterceptorAuthentications[obj.args.host + ':' + obj.args.port]);
170 // If different QOP options are proposed, always use 'auth' for now.
171 AuthArgs.qop = 'auth';
173 // In the future, we should support auth-int, but that will required the body of the request to be accumulated and hashed.
175 if (AuthArgs.qop != null) { // If Intel AMT supports auth-int, use it.
176 var qopList = AuthArgs.qop.split(',');
177 for (var i in qopList) { qopList[i] = qopList[i].trim(); }
178 if (qopList.indexOf('auth-int') >= 0) { AuthArgs.qop = 'auth-int'; } else { AuthArgs.qop = 'auth'; }
182 var hash = obj.ComputeDigesthash(obj.args.user, obj.args.pass, AuthArgs.realm, obj.ws.directive[0], obj.ws.directive[1], AuthArgs.qop, AuthArgs.nonce, obj.ws.authCNonceCount, obj.ws.authCNonce);
183 var authstr = 'Digest username="' + obj.args.user + '",realm="' + AuthArgs.realm + '",nonce="' + AuthArgs.nonce + '",uri="' + obj.ws.directive[1] + '",qop=' + AuthArgs.qop + ',nc=' + obj.ws.authCNonceCount + ',cnonce="' + obj.ws.authCNonce + '",response="' + hash + '"';
184 if (AuthArgs.opaque) { authstr += (',opaque="' + AuthArgs.opaque + '"'); }
185 obj.ws.headers.authorization = authstr;
186 obj.ws.authCNonceCount++;
188 // We don't have authentication, clear it out of the header if needed.
189 if (obj.ws.headers.authorization) { delete obj.ws.headers.authorization; }
192 // Reform the HTTP header
193 r = obj.ws.directive.join(' ') + '\r\n';
194 for (i in obj.ws.headers) { r += (i + ': ' + obj.ws.headers[i] + '\r\n'); }
197 } else if (obj.ws.mode == 1) { // Length Body Mode
198 // Send the body of content-length size
199 var rl = obj.ws.count;
200 if (rl < obj.ws.acc.length) rl = obj.ws.acc.length;
201 r = obj.ws.acc.substring(0, rl);
202 obj.ws.acc = obj.ws.acc.substring(rl);
204 if (obj.ws.count == 0) { obj.ws.mode = 0; }
206 } else if (obj.amt.mode == 2) { // Chunked Body Mode
207 // Send data one chunk at a time
208 headerend = obj.amt.acc.indexOf('\r\n');
209 if (headerend < 0) return '';
210 var chunksize = parseInt(obj.amt.acc.substring(0, headerend), 16);
211 if (isNaN(chunksize)) { // TODO: Check this path
212 // Chunk is not in this batch, move one
213 r = obj.amt.acc.substring(0, headerend + 2);
214 obj.amt.acc = obj.amt.acc.substring(headerend + 2);
215 // Peek if we next is the end of chunked transfer
216 headerend = obj.amt.acc.indexOf('\r\n');
218 chunksize = parseInt(obj.amt.acc.substring(0, headerend), 16);
219 if (chunksize == 0) { obj.amt.mode = 0; }
222 } else if (chunksize == 0 && obj.amt.acc.length >= headerend + 4) {
223 // Send the ending chunk (NOTE: We do not support trailing headers)
224 r = obj.amt.acc.substring(0, headerend + 4);
225 obj.amt.acc = obj.amt.acc.substring(headerend + 4);
228 } else if (chunksize > 0 && obj.amt.acc.length >= headerend + 4) {
230 r = obj.amt.acc.substring(0, headerend + chunksize + 4);
231 obj.amt.acc = obj.amt.acc.substring(headerend + chunksize + 4);
234 } else if (obj.ws.mode == 3) { // Until Close Mode
242 // Parse authentication values from the HTTP header
243 obj.GetAuthArgs = function (authheader) {
245 var authargsstr = authheader.substring(7).split(',');
246 for (var j in authargsstr) {
247 var argstr = authargsstr[j];
248 var i = argstr.indexOf('=');
249 var k = argstr.substring(0, i).trim().toLowerCase();
250 var v = argstr.substring(i + 1).trim();
251 if (v.substring(0, 1) == '\"') { v = v.substring(1, v.length - 1); }
252 if (i > 0) authargs[k] = v;
257 // Compute the MD5 digest hash for a set of values
258 obj.ComputeDigesthash = function (username, password, realm, method, path, qop, nonce, nc, cnonce) {
259 var ha1 = crypto.createHash('md5').update(username + ':' + realm + ':' + password).digest('hex');
260 var ha2 = crypto.createHash('md5').update(method + ':' + path).digest('hex');
261 return crypto.createHash('md5').update(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2).digest('hex');
268// Construct a redirection interceptor object
269module.exports.CreateRedirInterceptor = function (args) {
272 // Create a random hex string of a given length
273 obj.randomValueHex = function (len) { return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len); };
276 obj.amt = { acc: '', mode: 0, count: 0, error: false, direct: false };
277 obj.ws = { acc: '', mode: 0, count: 0, error: false, direct: false, authCNonce: obj.randomValueHex(10), authCNonceCount: 1 };
279 obj.RedirectCommands = { StartRedirectionSession: 0x10, StartRedirectionSessionReply: 0x11, EndRedirectionSession: 0x12, AuthenticateSession: 0x13, AuthenticateSessionReply: 0x14 };
280 obj.StartRedirectionSessionReplyStatus = { SUCCESS: 0, TYPE_UNKNOWN: 1, BUSY: 2, UNSUPPORTED: 3, ERROR: 0xFF };
281 obj.AuthenticationStatus = { SUCCESS: 0, FALIURE: 1, NOTSUPPORTED: 2 };
282 obj.AuthenticationType = { QUERY: 0, USERPASS: 1, KERBEROS: 2, BADDIGEST: 3, DIGEST: 4 };
285 obj.Debug = function (msg) { console.log(msg); };
287 // Process data coming from Intel AMT
288 obj.processAmtData = function (data) {
289 if ((obj.amt.direct == true) && (obj.amt.acc == '')) { return data; } // Interceptor fast path
290 obj.amt.acc += data.toString('binary'); // Add data to accumulator
293 do { datalen = data.length; data += obj.processAmtDataEx(); } while (datalen != data.length); // Process as much data as possible
294 return Buffer.from(data, 'binary');
297 // Process data coming from AMT in the accumulator
298 obj.processAmtDataEx = function () {
300 if (obj.amt.acc.length == 0) return '';
301 if (obj.amt.direct == true) {
302 var data = obj.amt.acc;
306 //console.log(obj.amt.acc.charCodeAt(0));
307 switch (obj.amt.acc.charCodeAt(0)) {
308 case obj.RedirectCommands.StartRedirectionSessionReply: {
309 if (obj.amt.acc.length < 4) return '';
310 if (obj.amt.acc.charCodeAt(1) == obj.StartRedirectionSessionReplyStatus.SUCCESS) {
311 if (obj.amt.acc.length < 13) return '';
312 var oemlen = obj.amt.acc.charCodeAt(12);
313 if (obj.amt.acc.length < 13 + oemlen) return '';
314 r = obj.amt.acc.substring(0, 13 + oemlen);
315 obj.amt.acc = obj.amt.acc.substring(13 + oemlen);
320 case obj.RedirectCommands.AuthenticateSessionReply: {
321 if (obj.amt.acc.length < 9) return '';
322 var l = common.ReadIntX(obj.amt.acc, 5);
323 if (obj.amt.acc.length < 9 + l) return '';
324 var authstatus = obj.amt.acc.charCodeAt(1);
325 var authType = obj.amt.acc.charCodeAt(4);
327 if ((authType == obj.AuthenticationType.DIGEST) && (authstatus == obj.AuthenticationStatus.FALIURE)) {
328 // Grab and keep all authentication parameters
329 var realmlen = obj.amt.acc.charCodeAt(9);
330 obj.amt.digestRealm = obj.amt.acc.substring(10, 10 + realmlen);
331 var noncelen = obj.amt.acc.charCodeAt(10 + realmlen);
332 obj.amt.digestNonce = obj.amt.acc.substring(11 + realmlen, 11 + realmlen + noncelen);
333 var qoplen = obj.amt.acc.charCodeAt(11 + realmlen + noncelen);
334 obj.amt.digestQOP = obj.amt.acc.substring(12 + realmlen + noncelen, 12 + realmlen + noncelen + qoplen);
336 else if (authType != obj.AuthenticationType.QUERY && authstatus == obj.AuthenticationStatus.SUCCESS) {
337 // Intel AMT relayed that authentication was successful, go to direct relay mode in both directions.
338 obj.ws.direct = true;
339 obj.amt.direct = true;
342 r = obj.amt.acc.substring(0, 9 + l);
343 obj.amt.acc = obj.amt.acc.substring(9 + l);
347 obj.amt.error = true;
355 // Process data coming from the Browser
356 obj.processBrowserData = function (data) {
357 if ((obj.ws.direct == true) && (obj.ws.acc == '')) { return data; } // Interceptor fast path
358 obj.ws.acc += data.toString('binary'); // Add data to accumulator
361 do { datalen = data.length; data += obj.processBrowserDataEx(); } while (datalen != data.length); // Process as much data as possible
362 return Buffer.from(data, 'binary');
365 // Process data coming from the Browser in the accumulator
366 obj.processBrowserDataEx = function () {
368 if (obj.ws.acc.length == 0) return '';
369 if (obj.ws.direct == true) {
370 var data = obj.ws.acc;
374 switch (obj.ws.acc.charCodeAt(0)) {
375 case obj.RedirectCommands.StartRedirectionSession: {
376 if (obj.ws.acc.length < 8) return '';
377 r = obj.ws.acc.substring(0, 8);
378 obj.ws.acc = obj.ws.acc.substring(8);
381 case obj.RedirectCommands.EndRedirectionSession: {
382 if (obj.ws.acc.length < 4) return '';
383 r = obj.ws.acc.substring(0, 4);
384 obj.ws.acc = obj.ws.acc.substring(4);
387 case obj.RedirectCommands.AuthenticateSession: {
388 if (obj.ws.acc.length < 9) return '';
389 var l = common.ReadIntX(obj.ws.acc, 5);
390 if (obj.ws.acc.length < 9 + l) return '';
392 var authType = obj.ws.acc.charCodeAt(4);
393 if (authType == obj.AuthenticationType.DIGEST && obj.args.user && obj.args.pass) {
394 var authurl = '/RedirectionService';
395 if (obj.amt.digestRealm) {
396 // Replace this authentication digest with a server created one
397 // We have everything we need to authenticate
398 var nc = '0'+ (10000000 + obj.ws.authCNonceCount).toString().substring(1);// set NC at least 8 bytes
399 obj.ws.authCNonceCount++;
400 var digest = obj.ComputeDigesthash(obj.args.user, obj.args.pass, obj.amt.digestRealm, 'POST', authurl, obj.amt.digestQOP, obj.amt.digestNonce, nc, obj.ws.authCNonce);
402 // Replace this authentication digest with a server created one
403 // We have everything we need to authenticate
404 r = String.fromCharCode(0x13, 0x00, 0x00, 0x00, 0x04);
405 r += common.IntToStrX(obj.args.user.length + obj.amt.digestRealm.length + obj.amt.digestNonce.length + authurl.length + obj.ws.authCNonce.length + nc.toString().length + digest.length + obj.amt.digestQOP.length + 8);
406 r += String.fromCharCode(obj.args.user.length); // Username Length
407 r += obj.args.user; // Username
408 r += String.fromCharCode(obj.amt.digestRealm.length); // Realm Length
409 r += obj.amt.digestRealm; // Realm
410 r += String.fromCharCode(obj.amt.digestNonce.length); // Nonce Length
411 r += obj.amt.digestNonce; // Nonce
412 r += String.fromCharCode(authurl.length); // Authentication URL "/RedirectionService" Length
413 r += authurl; // Authentication URL
414 r += String.fromCharCode(obj.ws.authCNonce.length); // CNonce Length
415 r += obj.ws.authCNonce; // CNonce
416 r += String.fromCharCode(nc.toString().length); // NonceCount Length
417 r += nc.toString(); // NonceCount
418 r += String.fromCharCode(digest.length); // Response Length
419 r += digest; // Response
420 r += String.fromCharCode(obj.amt.digestQOP.length); // QOP Length
421 r += obj.amt.digestQOP; // QOP
423 obj.ws.acc = obj.ws.acc.substring(9 + l); // Don't relay the original message
426 // Replace this authentication digest with a server created one
427 // Since we don't have authentication parameters, fill them in with blanks to get an error back what that info.
428 r = String.fromCharCode(0x13, 0x00, 0x00, 0x00, 0x04);
429 r += common.IntToStrX(obj.args.user.length + authurl.length + 8);
430 r += String.fromCharCode(obj.args.user.length);
432 r += String.fromCharCode(0x00, 0x00, authurl.length);
434 r += String.fromCharCode(0x00, 0x00, 0x00, 0x00);
435 obj.ws.acc = obj.ws.acc.substring(9 + l); // Don't relay the original message
440 r = obj.ws.acc.substring(0, 9 + l);
441 obj.ws.acc = obj.ws.acc.substring(9 + l);
452 // Compute the MD5 digest hash for a set of values
453 obj.ComputeDigesthash = function (username, password, realm, method, path, qop, nonce, nc, cnonce) {
454 var ha1 = crypto.createHash('md5').update(username + ':' + realm + ':' + password).digest('hex');
455 var ha2 = crypto.createHash('md5').update(method + ':' + path).digest('hex');
456 return crypto.createHash('md5').update(ha1 + ':' + nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2).digest('hex');