Skip to content

Instantly share code, notes, and snippets.

@kerus1024
Last active January 30, 2021 05:40
Show Gist options
  • Save kerus1024/7dfc8f1fba89c952e5e62350a849f5b6 to your computer and use it in GitHub Desktop.
Save kerus1024/7dfc8f1fba89c952e5e62350a849f5b6 to your computer and use it in GitHub Desktop.
Read SNI Hostname from ClientHello SNI Header
const snireader = (buffer) => {
let pos = 0;
if (buffer[pos] !== 0x16) {
// SNI: Handshake
return;
}
if (buffer[pos = pos + 5] !== 0x01) {
// SNI: ClientHello
return;
}
// Skip Length
pos += 3;
// Skip TLS Version
pos += 2;
// Skip Random 32 bytes
pos += 32;
// Session ID Length
const sessionIDLength = buffer[++pos];
pos += sessionIDLength;
// Cipher Suites Length
pos++;
const cipherLength = buffer[++pos];
pos += cipherLength;
// Compression Mode Length
const compressionModeLength = buffer[++pos];
pos += compressionModeLength;
// Extension Length
const extensionLength = buffer[++pos] * 0x1FF + buffer[++pos];
for (let i = pos; (i || pos) < Buffer.byteLength(buffer); i++) {
// Extension ServerName
// Server Name
if (buffer[pos + 1] === 0x00 && buffer[pos + 2] === 0x00) {
pos += 2;
// ServerName Extension Length
pos += 2;
// Server Name List Length
pos += 2;
if (buffer[++pos] !== 0x00) {
// SNI: Hostname
continue;
}
pos += 2;
const serverNameLength = buffer[pos];
const serverName = buffer.slice(++pos, pos + serverNameLength);
console.log('SNI:Server-Name:', serverName.toString());
return serverName.toString();
} else {
pos += 2;
// Skip Extension
const skipLength = buffer[++pos] * 0x1FF + buffer[++pos];
pos += skipLength;
}
}
// fail
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment