Skip to content

Commit

Permalink
fix: Improved dnshack to catch all problematic dns.lookup requests
Browse files Browse the repository at this point in the history
  • Loading branch information
Hypfer committed Aug 12, 2020
1 parent 252c22d commit 8609612
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions lib/DnsHack.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ const Logger = require("./Logger");
Simply resolving any hostnames before connecting to them isn't an option though,
since then certificate validation will fail.
Therefore, the only way to mitigate this is to overwrite dns.lookup and redirect all calls that
look the same as the call of the mqtt library.
Therefore, the only way to mitigate this is to overwrite dns.lookup and redirect all calls of the MQTT client
by looking at the stacktrace of the call.
I'm sorry.
*/
Expand All @@ -28,25 +27,35 @@ dns.lookup = function lookupResolveHack(hostname, options, callback) {

if (
Object.getOwnPropertyNames(options).length === 2 &&
options.family === undefined && options.hints === 0
options.family === undefined
) {
Logger.trace("Intercepting dns.lookup call for", hostname);

dns.resolve4(hostname, (err, addresses) => {
if (err && err.code === "ENOTFOUND") {
dns.resolve6(hostname, (err, addresses) => {
if (err) {
callback(err);
} else {
callback(null, addresses[0], 6);
}
});
} else if (err) {
callback(err);
} else {
callback(null, addresses[0], 4);
}
});
//This sorta looks like something that might be a request from the MQTT client
//Time to take a look at the stacktrace to make sure
//Doing this after checking the previous condition saves us from creating a stacktrace
//on each udp send which would be horrible for the performance
const stack = new Error().stack;

if (stack.includes("lookupAndConnect")) { //nodejs internal function
Logger.trace("Intercepting dns.lookup call for", hostname);

dns.resolve4(hostname, (err, addresses) => {
if (err && err.code === "ENOTFOUND") {
dns.resolve6(hostname, (err, addresses) => {
if (err) {
callback(err);
} else {
callback(null, addresses[0], 6);
}
});
} else if (err) {
callback(err);
} else {
callback(null, addresses[0], 4);
}
});
} else {
return realLookup(hostname, options, callback);
}
} else {
return realLookup(hostname, options, callback);
}
Expand Down

0 comments on commit 8609612

Please sign in to comment.