Created
June 4, 2019 03:40
-
-
Save AlecDusheck/2e933bbfb67532b363b649f66da02513 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const socks = require('socksv5'); | |
const Client = require('ssh2').Client; | |
const config = require('./config'); | |
let socksServer; | |
let sshConnection; | |
const connect = async () => { | |
unbind(); // Unbind previous connections | |
sshConnection = new Client(); | |
sshConnection.on("error", err => { | |
console.log("Got error in SSH connection:", err); | |
process.exit(1); | |
}); | |
sshConnection.connect({ | |
password: config.password, | |
username: config.username, | |
port: 22, | |
host: config.host, | |
keepAlive: true | |
}); | |
await new Promise(resolve => { | |
sshConnection.on("ready", () => { | |
return resolve(); | |
}) | |
}); | |
console.log("SSH connection prepped!"); | |
socksServer = socks.createServer(socksHandler); | |
socksServer.listen(config.localPort, 'localhost', () => { | |
console.log('Socks5 server started on ' + config.localPort); | |
}).useAuth(socks.auth.None()); | |
socksServer.on("error", err => { | |
console.log("Got error in socks5 connection:", err); | |
}); | |
}; | |
const socksHandler = async (info, accept, deny) => { | |
sshConnection.forwardOut(info.srcAddr, | |
info.srcPort, | |
info.dstAddr, | |
info.dstPort, | |
(err, stream) => { | |
if (err) { | |
sshConnection.end(); | |
return deny(); | |
} | |
let clientSocket; | |
if (clientSocket = accept(true)) { | |
stream.pipe(clientSocket).on("error", err => { | |
console.log("Failed piping socks socket:", err) | |
}).pipe(stream).on("error", err => { | |
console.log("Failed piping ssh socket:", err) | |
}) | |
} | |
}); | |
}; | |
const unbind = () => { | |
if (socksServer) { | |
socksServer.removeAllListeners(); | |
socksServer = undefined; | |
} | |
if (sshConnection) { | |
sshConnection.removeAllListeners(); | |
sshConnection = undefined; | |
} | |
}; | |
connect(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment