feat: add SMB networking support
This commit is contained in:
1 parent
6665750528
commit
2af2e90606
55 files changed
+7456
-158
No files matched your search
@@ -0,0 +1,71 @@
|
||||
# Makefile for the SMB2/SMB3 client library on MontaukOS
|
||||
# Copyright (c) 2026 Daniel Hammer
|
||||
|
||||
MAKEFLAGS += -rR
|
||||
.SUFFIXES:
|
||||
|
||||
# ---- Toolchain ----
|
||||
|
||||
include ../../mk/arch.mk
|
||||
ifneq ($(wildcard $(TOOLCHAIN_PREFIX)gcc),)
|
||||
CXX := $(TOOLCHAIN_PREFIX)g++
|
||||
AR := $(TOOLCHAIN_PREFIX)ar
|
||||
else
|
||||
CXX := g++
|
||||
AR := ar
|
||||
endif
|
||||
|
||||
# ---- Paths ----
|
||||
|
||||
BEARSSL := ../bearssl
|
||||
LIBC_INC := ../../include/libc
|
||||
PROG_INC := ../../include
|
||||
OBJDIR := obj$(ARCH_SUFFIX)
|
||||
|
||||
# ---- Compiler flags ----
|
||||
|
||||
CXXFLAGS := \
|
||||
-std=gnu++20 \
|
||||
-g -O2 -pipe \
|
||||
-Wall \
|
||||
-Wextra \
|
||||
-Wno-unused-parameter \
|
||||
-nostdinc \
|
||||
-ffreestanding \
|
||||
-fno-stack-protector \
|
||||
-fno-stack-check \
|
||||
-fno-PIC \
|
||||
-fno-rtti \
|
||||
-fno-exceptions \
|
||||
-ffunction-sections \
|
||||
-fdata-sections \
|
||||
$(ARCH_CFLAGS) \
|
||||
$(ARCH_NOFP_FLAGS) \
|
||||
-I $(PROG_INC) \
|
||||
-isystem $(LIBC_INC) \
|
||||
-I $(BEARSSL)/inc \
|
||||
-isystem ../../../kernel/freestnd-c-hdrs/$(ARCH)/include \
|
||||
-isystem ../../../kernel/freestnd-cxx-hdrs/$(ARCH)/include
|
||||
|
||||
# ---- Target ----
|
||||
|
||||
TARGET := $(ARCH_OUT)libsmb.a
|
||||
SRCS := smb.cpp ntlm.cpp crypto.cpp montauk_io.cpp
|
||||
OBJS := $(SRCS:%.cpp=$(OBJDIR)/%.o)
|
||||
HDRS := internal.hpp $(PROG_INC)/smb/smb.hpp $(PROG_INC)/smb/montauk.hpp
|
||||
|
||||
.PHONY: all clean
|
||||
|
||||
all: $(TARGET)
|
||||
|
||||
$(TARGET): $(OBJS)
|
||||
@mkdir -p $(dir $@)
|
||||
rm -f $@
|
||||
$(AR) rcs $@ $^
|
||||
|
||||
$(OBJDIR)/%.o: %.cpp $(HDRS) Makefile
|
||||
@mkdir -p $(OBJDIR)
|
||||
$(CXX) $(CXXFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -rf $(OBJDIR) $(TARGET)
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* crypto.cpp
|
||||
* Hashes and MACs used by SMB signing and NTLMv2
|
||||
* Copyright (c) 2026 Daniel Hammer
|
||||
*/
|
||||
|
||||
#include "internal.hpp"
|
||||
|
||||
extern "C" {
|
||||
#include <bearssl_hash.h>
|
||||
#include <bearssl_hmac.h>
|
||||
#include <bearssl_block.h>
|
||||
}
|
||||
|
||||
namespace smb::detail {
|
||||
|
||||
// ==========================================================================
|
||||
// MD4 (RFC 1320). BearSSL does not ship it; NTLM's password hash needs it.
|
||||
// ==========================================================================
|
||||
|
||||
static inline uint32_t rol(uint32_t v, int s) { return (v << s) | (v >> (32 - s)); }
|
||||
|
||||
static void md4_block(uint32_t st[4], const uint8_t* blk) {
|
||||
uint32_t x[16];
|
||||
for (int i = 0; i < 16; i++) x[i] = get32(blk + i * 4);
|
||||
uint32_t a = st[0], b = st[1], c = st[2], d = st[3];
|
||||
|
||||
#define MD4_F(x, y, z) (((x) & (y)) | (~(x) & (z)))
|
||||
#define MD4_G(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
|
||||
#define MD4_H(x, y, z) ((x) ^ (y) ^ (z))
|
||||
#define R1(a, b, c, d, k, s) a = rol(a + MD4_F(b, c, d) + x[k], s)
|
||||
#define R2(a, b, c, d, k, s) a = rol(a + MD4_G(b, c, d) + x[k] + 0x5A827999u, s)
|
||||
#define R3(a, b, c, d, k, s) a = rol(a + MD4_H(b, c, d) + x[k] + 0x6ED9EBA1u, s)
|
||||
|
||||
for (int i = 0; i < 16; i += 4) {
|
||||
R1(a, b, c, d, i, 3); R1(d, a, b, c, i + 1, 7);
|
||||
R1(c, d, a, b, i + 2, 11); R1(b, c, d, a, i + 3, 19);
|
||||
}
|
||||
for (int i = 0; i < 4; i++) {
|
||||
R2(a, b, c, d, i, 3); R2(d, a, b, c, i + 4, 5);
|
||||
R2(c, d, a, b, i + 8, 9); R2(b, c, d, a, i + 12, 13);
|
||||
}
|
||||
static const int order[4] = {0, 2, 1, 3};
|
||||
for (int j = 0; j < 4; j++) {
|
||||
int i = order[j];
|
||||
R3(a, b, c, d, i, 3); R3(d, a, b, c, i + 8, 9);
|
||||
R3(c, d, a, b, i + 4, 11); R3(b, c, d, a, i + 12, 15);
|
||||
}
|
||||
|
||||
#undef MD4_F
|
||||
#undef MD4_G
|
||||
#undef MD4_H
|
||||
#undef R1
|
||||
#undef R2
|
||||
#undef R3
|
||||
|
||||
st[0] += a; st[1] += b; st[2] += c; st[3] += d;
|
||||
}
|
||||
|
||||
void md4(const uint8_t* data, size_t len, uint8_t out[16]) {
|
||||
uint32_t st[4] = {0x67452301u, 0xEFCDAB89u, 0x98BADCFEu, 0x10325476u};
|
||||
size_t off = 0;
|
||||
for (; off + 64 <= len; off += 64) md4_block(st, data + off);
|
||||
|
||||
uint8_t tail[128];
|
||||
size_t rem = len - off;
|
||||
memset(tail, 0, sizeof(tail));
|
||||
if (rem > 0) memcpy(tail, data + off, rem);
|
||||
tail[rem] = 0x80;
|
||||
size_t total = (rem < 56) ? 64 : 128;
|
||||
put64(tail + total - 8, (uint64_t)len * 8);
|
||||
md4_block(st, tail);
|
||||
if (total == 128) md4_block(st, tail + 64);
|
||||
|
||||
for (int i = 0; i < 4; i++) put32(out + i * 4, st[i]);
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// HMAC
|
||||
// ==========================================================================
|
||||
|
||||
static void hmac(const br_hash_class* cls, const uint8_t* key, size_t keyLen,
|
||||
const uint8_t* a, size_t aLen, const uint8_t* b, size_t bLen, uint8_t* out) {
|
||||
br_hmac_key_context kc;
|
||||
br_hmac_context ctx;
|
||||
br_hmac_key_init(&kc, cls, key, keyLen);
|
||||
br_hmac_init(&ctx, &kc, 0);
|
||||
if (aLen > 0) br_hmac_update(&ctx, a, aLen);
|
||||
if (bLen > 0) br_hmac_update(&ctx, b, bLen);
|
||||
br_hmac_out(&ctx, out);
|
||||
}
|
||||
|
||||
void hmac_md5(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen,
|
||||
const uint8_t* b, size_t bLen, uint8_t out[16]) {
|
||||
hmac(&br_md5_vtable, key, keyLen, a, aLen, b, bLen, out);
|
||||
}
|
||||
|
||||
void hmac_sha256(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen,
|
||||
const uint8_t* b, size_t bLen, uint8_t out[32]) {
|
||||
hmac(&br_sha256_vtable, key, keyLen, a, aLen, b, bLen, out);
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// AES-128-CMAC (RFC 4493), the SMB 3.0 signing algorithm
|
||||
// ==========================================================================
|
||||
|
||||
// Double a 128-bit value in GF(2^128) (the CMAC subkey step).
|
||||
static void cmac_double(const uint8_t in[16], uint8_t out[16]) {
|
||||
uint8_t carry = 0;
|
||||
for (int i = 15; i >= 0; i--) {
|
||||
uint8_t next = (uint8_t)(in[i] >> 7);
|
||||
out[i] = (uint8_t)((in[i] << 1) | carry);
|
||||
carry = next;
|
||||
}
|
||||
if (carry) out[15] ^= 0x87;
|
||||
}
|
||||
|
||||
void aes_cmac(const uint8_t key[16], const uint8_t* data, size_t len, uint8_t out[16]) {
|
||||
br_aes_ct_cbcenc_keys keys;
|
||||
br_aes_ct_cbcenc_init(&keys, key, 16);
|
||||
|
||||
// CBC-MAC is CBC encryption that keeps only the chaining value, which
|
||||
// br_aes_ct_cbcenc_run leaves in `iv`.
|
||||
uint8_t iv[16];
|
||||
uint8_t block[16];
|
||||
|
||||
uint8_t l[16], k1[16], k2[16];
|
||||
memset(iv, 0, 16);
|
||||
memset(l, 0, 16);
|
||||
br_aes_ct_cbcenc_run(&keys, iv, l, 16);
|
||||
cmac_double(l, k1);
|
||||
cmac_double(k1, k2);
|
||||
|
||||
size_t blocks = (len + 15) / 16;
|
||||
bool lastComplete = len > 0 && (len % 16) == 0;
|
||||
if (blocks == 0) blocks = 1;
|
||||
|
||||
memset(iv, 0, 16);
|
||||
for (size_t i = 0; i + 1 < blocks; i++) {
|
||||
memcpy(block, data + i * 16, 16);
|
||||
br_aes_ct_cbcenc_run(&keys, iv, block, 16);
|
||||
}
|
||||
|
||||
const uint8_t* last = data + (blocks - 1) * 16;
|
||||
if (lastComplete) {
|
||||
for (int i = 0; i < 16; i++) block[i] = last[i] ^ k1[i];
|
||||
} else {
|
||||
size_t rem = len - (blocks - 1) * 16;
|
||||
memset(block, 0, 16);
|
||||
if (rem > 0) memcpy(block, last, rem);
|
||||
block[rem] = 0x80;
|
||||
for (int i = 0; i < 16; i++) block[i] ^= k2[i];
|
||||
}
|
||||
br_aes_ct_cbcenc_run(&keys, iv, block, 16);
|
||||
memcpy(out, block, 16);
|
||||
}
|
||||
|
||||
void smb3_kdf(const uint8_t key[16], const char* label, size_t labelLen,
|
||||
const char* context, size_t contextLen, uint8_t out[16]) {
|
||||
// K(1) = HMAC-SHA256(key, [i=1]_32be | label | 0x00 | context | [L=128]_32be)
|
||||
uint8_t msg[160];
|
||||
size_t n = 0;
|
||||
if (labelLen + contextLen + 9 > sizeof(msg)) { memset(out, 0, 16); return; }
|
||||
msg[n++] = 0; msg[n++] = 0; msg[n++] = 0; msg[n++] = 1;
|
||||
memcpy(msg + n, label, labelLen); n += labelLen;
|
||||
msg[n++] = 0;
|
||||
memcpy(msg + n, context, contextLen); n += contextLen;
|
||||
msg[n++] = 0; msg[n++] = 0; msg[n++] = 0; msg[n++] = 128;
|
||||
uint8_t full[32];
|
||||
hmac_sha256(key, 16, msg, n, nullptr, 0, full);
|
||||
memcpy(out, full, 16);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* internal.hpp
|
||||
* SMB client library internals: byte order, crypto, NTLM, SPNEGO
|
||||
* Copyright (c) 2026 Daniel Hammer
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
#include <smb/smb.hpp>
|
||||
#include <string.h>
|
||||
|
||||
namespace smb::detail {
|
||||
|
||||
// ---- Little-endian accessors (the SMB wire format) ----
|
||||
|
||||
inline void put16(uint8_t* p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
|
||||
inline void put32(uint8_t* p, uint32_t v) {
|
||||
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
|
||||
}
|
||||
inline void put64(uint8_t* p, uint64_t v) { put32(p, (uint32_t)v); put32(p + 4, (uint32_t)(v >> 32)); }
|
||||
inline uint16_t get16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); }
|
||||
inline uint32_t get32(const uint8_t* p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
inline uint64_t get64(const uint8_t* p) { return (uint64_t)get32(p) | ((uint64_t)get32(p + 4) << 32); }
|
||||
|
||||
// ---- Time ----
|
||||
|
||||
// Windows FILETIME: 100 ns ticks since 1601-01-01 UTC.
|
||||
static constexpr uint64_t FILETIME_UNIX_EPOCH = 116444736000000000ULL;
|
||||
inline int64_t filetime_to_unix(uint64_t ft) {
|
||||
if (ft == 0) return 0;
|
||||
if (ft < FILETIME_UNIX_EPOCH) return 0;
|
||||
return (int64_t)((ft - FILETIME_UNIX_EPOCH) / 10000000ULL);
|
||||
}
|
||||
inline uint64_t unix_to_filetime(int64_t t) {
|
||||
if (t <= 0) return 0;
|
||||
return (uint64_t)t * 10000000ULL + FILETIME_UNIX_EPOCH;
|
||||
}
|
||||
|
||||
// ---- Text ----
|
||||
|
||||
// UTF-8 -> UTF-16LE. Returns the number of bytes written (no terminator),
|
||||
// or -1 if `cap` is too small. With `path` set, '/' becomes '\' and
|
||||
// leading / trailing / doubled separators are dropped.
|
||||
int utf8_to_utf16(const char* in, uint8_t* out, uint32_t cap, bool path = false);
|
||||
// UTF-16LE (`len` bytes) -> NUL-terminated UTF-8, truncated to fit `cap`.
|
||||
void utf16_to_utf8(const uint8_t* in, uint32_t len, char* out, uint32_t cap);
|
||||
|
||||
// ---- Crypto (crypto.cpp) ----
|
||||
|
||||
void md4(const uint8_t* data, size_t len, uint8_t out[16]);
|
||||
// HMAC over the concatenation of two segments (either may be empty).
|
||||
void hmac_md5(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen,
|
||||
const uint8_t* b, size_t bLen, uint8_t out[16]);
|
||||
void hmac_sha256(const uint8_t* key, size_t keyLen, const uint8_t* a, size_t aLen,
|
||||
const uint8_t* b, size_t bLen, uint8_t out[32]);
|
||||
void aes_cmac(const uint8_t key[16], const uint8_t* data, size_t len, uint8_t out[16]);
|
||||
// SMB 3.0 key derivation (SP800-108 counter mode, HMAC-SHA256, 128 bits).
|
||||
// label and context include their terminating NUL.
|
||||
void smb3_kdf(const uint8_t key[16], const char* label, size_t labelLen,
|
||||
const char* context, size_t contextLen, uint8_t out[16]);
|
||||
|
||||
// ---- NTLMSSP + SPNEGO (ntlm.cpp) ----
|
||||
|
||||
static constexpr size_t NTLM_NEGOTIATE_LEN = 32;
|
||||
void ntlm_negotiate(uint8_t out[NTLM_NEGOTIATE_LEN]);
|
||||
|
||||
struct NtlmAuthParams {
|
||||
const char* user; // "" with anonymous set
|
||||
const char* password;
|
||||
const char* domain;
|
||||
bool anonymous;
|
||||
uint8_t clientChallenge[8];
|
||||
uint64_t fallbackTime; // FILETIME used if the server sent no timestamp
|
||||
};
|
||||
// Build the AUTHENTICATE message for a server CHALLENGE. Returns its
|
||||
// length or a negative Status. sessionKey receives the 16-byte session
|
||||
// base key (all zero for an anonymous logon).
|
||||
int ntlm_authenticate(const uint8_t* challenge, size_t challengeLen, const NtlmAuthParams& p,
|
||||
uint8_t* out, size_t outCap, uint8_t sessionKey[16]);
|
||||
|
||||
// Wrap an NTLM token in a SPNEGO NegTokenInit (first leg) or NegTokenResp
|
||||
// (later legs). Returns the blob length or -1 if it does not fit.
|
||||
int spnego_wrap(const uint8_t* token, size_t tokenLen, bool first, uint8_t* out, size_t outCap);
|
||||
// Find the NTLM token inside a server security blob (SPNEGO or raw).
|
||||
bool spnego_unwrap(const uint8_t* blob, size_t len, const uint8_t** token, size_t* tokenLen);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* montauk_io.cpp
|
||||
* MontaukOS transport for the SMB client library
|
||||
* Copyright (c) 2026 Daniel Hammer
|
||||
*/
|
||||
|
||||
#include <smb/montauk.hpp>
|
||||
#include <montauk/syscall.h>
|
||||
|
||||
namespace smb {
|
||||
|
||||
static constexpr uint64_t kSendStallMs = 15000;
|
||||
|
||||
static bool parse_ipv4(const char* s, uint32_t* out) {
|
||||
uint32_t parts[4] = {0, 0, 0, 0};
|
||||
int part = 0;
|
||||
while (*s) {
|
||||
if (part >= 4 || *s < '0' || *s > '9') return false;
|
||||
uint32_t value = 0;
|
||||
while (*s >= '0' && *s <= '9') {
|
||||
value = value * 10u + (uint32_t)(*s - '0');
|
||||
if (value > 255u) return false;
|
||||
s++;
|
||||
}
|
||||
parts[part++] = value;
|
||||
if (*s == '.') { s++; continue; }
|
||||
if (*s != '\0') return false;
|
||||
}
|
||||
if (part != 4) return false;
|
||||
*out = parts[0] | (parts[1] << 8) | (parts[2] << 16) | (parts[3] << 24);
|
||||
return true;
|
||||
}
|
||||
|
||||
int link_open(MontaukLink* link, const char* host, int port) {
|
||||
link->fd = -1;
|
||||
uint32_t ip = 0;
|
||||
if (!parse_ipv4(host, &ip)) ip = montauk::resolve(host);
|
||||
if (ip == 0) return ERR_NOT_FOUND;
|
||||
|
||||
int fd = montauk::socket(montauk::abi::SOCK_TCP);
|
||||
if (fd < 0) return ERR_IO;
|
||||
if (montauk::connect(fd, ip, (uint16_t)(port > 0 ? port : 445)) < 0) {
|
||||
montauk::closesocket(fd);
|
||||
return ERR_IO;
|
||||
}
|
||||
link->fd = fd;
|
||||
return OK;
|
||||
}
|
||||
|
||||
void link_close(MontaukLink* link) {
|
||||
if (link->fd >= 0) montauk::closesocket(link->fd);
|
||||
link->fd = -1;
|
||||
}
|
||||
|
||||
static int io_send(void* ctx, const void* data, uint32_t len) {
|
||||
int fd = ((MontaukLink*)ctx)->fd;
|
||||
if (fd < 0) return -1;
|
||||
const uint8_t* p = (const uint8_t*)data;
|
||||
uint32_t sent = 0;
|
||||
uint64_t deadline = montauk::get_milliseconds() + kSendStallMs;
|
||||
while (sent < len) {
|
||||
int r = montauk::send(fd, p + sent, len - sent);
|
||||
if (r > 0) {
|
||||
sent += (uint32_t)r;
|
||||
deadline = montauk::get_milliseconds() + kSendStallMs;
|
||||
continue;
|
||||
}
|
||||
if (r < 0) return -1;
|
||||
uint64_t now = montauk::get_milliseconds();
|
||||
if (now >= deadline) return -1;
|
||||
uint32_t signals = montauk::wait_handle(
|
||||
fd, montauk::abi::IPC_SIGNAL_WRITABLE | montauk::abi::IPC_SIGNAL_PEER_CLOSED,
|
||||
deadline - now);
|
||||
if (signals == (uint32_t)-1 || (signals & montauk::abi::IPC_SIGNAL_PEER_CLOSED)) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int io_recv(void* ctx, void* buf, uint32_t len, uint32_t timeoutMs) {
|
||||
int fd = ((MontaukLink*)ctx)->fd;
|
||||
if (fd < 0) return -1;
|
||||
uint64_t deadline = montauk::get_milliseconds() + timeoutMs;
|
||||
for (;;) {
|
||||
int r = montauk::recv(fd, buf, len);
|
||||
if (r > 0) return r;
|
||||
if (r < 0) return -1;
|
||||
uint64_t now = montauk::get_milliseconds();
|
||||
if (now >= deadline) return 0;
|
||||
uint32_t signals = montauk::wait_handle(
|
||||
fd, montauk::abi::IPC_SIGNAL_READABLE | montauk::abi::IPC_SIGNAL_PEER_CLOSED,
|
||||
deadline - now);
|
||||
if (signals == (uint32_t)-1) return -1;
|
||||
if ((signals & montauk::abi::IPC_SIGNAL_PEER_CLOSED) &&
|
||||
!(signals & montauk::abi::IPC_SIGNAL_READABLE)) return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static void io_random(void* ctx, void* buf, uint32_t len) {
|
||||
montauk::getrandom(buf, len);
|
||||
}
|
||||
|
||||
Io link_io(MontaukLink* link) {
|
||||
Io io;
|
||||
io.ctx = link;
|
||||
io.send = io_send;
|
||||
io.recv = io_recv;
|
||||
io.random = io_random;
|
||||
return io;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
* ntlm.cpp
|
||||
* NTLMv2 authentication messages and their SPNEGO wrapping
|
||||
* Copyright (c) 2026 Daniel Hammer
|
||||
*/
|
||||
|
||||
#include "internal.hpp"
|
||||
|
||||
namespace smb::detail {
|
||||
|
||||
static const uint8_t kSignature[8] = {'N', 'T', 'L', 'M', 'S', 'S', 'P', 0};
|
||||
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_UNICODE = 0x00000001;
|
||||
static constexpr uint32_t NTLMSSP_REQUEST_TARGET = 0x00000004;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_SIGN = 0x00000010;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_NTLM = 0x00000200;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_ANONYMOUS = 0x00000800;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_ALWAYS_SIGN = 0x00008000;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_EXTENDED = 0x00080000;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_TARGET_INFO = 0x00800000;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_128 = 0x20000000;
|
||||
static constexpr uint32_t NTLMSSP_NEGOTIATE_56 = 0x80000000;
|
||||
|
||||
// No KEY_EXCH: the session key is then the session base key itself, with
|
||||
// no RC4-wrapped random key to exchange.
|
||||
static constexpr uint32_t kClientFlags =
|
||||
NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_SIGN |
|
||||
NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_ALWAYS_SIGN | NTLMSSP_NEGOTIATE_EXTENDED |
|
||||
NTLMSSP_NEGOTIATE_TARGET_INFO | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_56;
|
||||
|
||||
static constexpr uint16_t MsvAvEOL = 0;
|
||||
static constexpr uint16_t MsvAvTimestamp = 7;
|
||||
|
||||
void ntlm_negotiate(uint8_t out[NTLM_NEGOTIATE_LEN]) {
|
||||
memset(out, 0, NTLM_NEGOTIATE_LEN);
|
||||
memcpy(out, kSignature, 8);
|
||||
put32(out + 8, 1);
|
||||
put32(out + 12, kClientFlags);
|
||||
// Empty domain and workstation fields, both pointing past the header.
|
||||
put32(out + 20, NTLM_NEGOTIATE_LEN);
|
||||
put32(out + 28, NTLM_NEGOTIATE_LEN);
|
||||
}
|
||||
|
||||
// Uppercase a UTF-16LE string in place. NTLM uppercases the user name;
|
||||
// ASCII and Latin-1 cover the names this client can be given sensibly.
|
||||
static void utf16_upper(uint8_t* s, int len) {
|
||||
for (int i = 0; i + 1 < len; i += 2) {
|
||||
uint16_t ch = get16(s + i);
|
||||
if (ch >= 'a' && ch <= 'z') ch = (uint16_t)(ch - 32);
|
||||
else if (ch >= 0xE0 && ch <= 0xFE && ch != 0xF7) ch = (uint16_t)(ch - 32);
|
||||
put16(s + i, ch);
|
||||
}
|
||||
}
|
||||
|
||||
static void put_field(uint8_t* p, uint16_t len, uint32_t offset) {
|
||||
put16(p, len);
|
||||
put16(p + 2, len);
|
||||
put32(p + 4, offset);
|
||||
}
|
||||
|
||||
int ntlm_authenticate(const uint8_t* challenge, size_t challengeLen, const NtlmAuthParams& p,
|
||||
uint8_t* out, size_t outCap, uint8_t sessionKey[16]) {
|
||||
static constexpr size_t kHeader = 64;
|
||||
memset(sessionKey, 0, 16);
|
||||
|
||||
if (challengeLen < 48 || memcmp(challenge, kSignature, 8) != 0 || get32(challenge + 8) != 2)
|
||||
return ERR_PROTOCOL;
|
||||
const uint8_t* serverChallenge = challenge + 24;
|
||||
|
||||
// Target info: the AV pair list this response must echo.
|
||||
uint16_t tiLen = get16(challenge + 40);
|
||||
uint32_t tiOff = get32(challenge + 44);
|
||||
const uint8_t* targetInfo = nullptr;
|
||||
if (tiLen > 0) {
|
||||
if ((size_t)tiOff + tiLen > challengeLen) return ERR_PROTOCOL;
|
||||
targetInfo = challenge + tiOff;
|
||||
}
|
||||
bool haveTimestamp = false;
|
||||
uint64_t timestamp = p.fallbackTime;
|
||||
for (size_t pos = 0; pos + 4 <= tiLen;) {
|
||||
uint16_t id = get16(targetInfo + pos);
|
||||
uint16_t len = get16(targetInfo + pos + 2);
|
||||
if (id == MsvAvEOL) break;
|
||||
if (pos + 4 + len > tiLen) return ERR_PROTOCOL;
|
||||
if (id == MsvAvTimestamp && len == 8) {
|
||||
timestamp = get64(targetInfo + pos + 4);
|
||||
haveTimestamp = true;
|
||||
}
|
||||
pos += 4 + (size_t)len;
|
||||
}
|
||||
|
||||
if (outCap < kHeader) return ERR_NOMEM;
|
||||
memset(out, 0, kHeader);
|
||||
memcpy(out, kSignature, 8);
|
||||
put32(out + 8, 3);
|
||||
|
||||
if (p.anonymous) {
|
||||
// Null session: no user, no responses, no session key.
|
||||
put_field(out + 12, 0, kHeader);
|
||||
put_field(out + 20, 0, kHeader);
|
||||
put_field(out + 28, 0, kHeader);
|
||||
put_field(out + 36, 0, kHeader);
|
||||
put_field(out + 44, 0, kHeader);
|
||||
put_field(out + 52, 0, kHeader);
|
||||
put32(out + 60, kClientFlags | NTLMSSP_NEGOTIATE_ANONYMOUS);
|
||||
return (int)kHeader;
|
||||
}
|
||||
|
||||
uint8_t user16[512], domain16[512], pass16[1024];
|
||||
int userLen = utf8_to_utf16(p.user ? p.user : "", user16, sizeof(user16));
|
||||
int domainLen = utf8_to_utf16(p.domain ? p.domain : "", domain16, sizeof(domain16));
|
||||
int passLen = utf8_to_utf16(p.password ? p.password : "", pass16, sizeof(pass16));
|
||||
if (userLen < 0 || domainLen < 0 || passLen < 0) return ERR_INVALID;
|
||||
|
||||
// NTOWFv2 = HMAC-MD5(MD4(password), UPPER(user) | domain)
|
||||
uint8_t ntHash[16], ntowf[16];
|
||||
md4(pass16, (size_t)passLen, ntHash);
|
||||
uint8_t upper[512];
|
||||
memcpy(upper, user16, (size_t)userLen);
|
||||
utf16_upper(upper, userLen);
|
||||
hmac_md5(ntHash, 16, upper, (size_t)userLen, domain16, (size_t)domainLen, ntowf);
|
||||
memset(pass16, 0, sizeof(pass16));
|
||||
memset(ntHash, 0, sizeof(ntHash));
|
||||
|
||||
// The NTLMv2 blob ("temp"): version, timestamp, client challenge and
|
||||
// the server's target info.
|
||||
size_t tempLen = 28 + (size_t)tiLen + 4;
|
||||
size_t ntRespLen = 16 + tempLen;
|
||||
size_t total = kHeader + 24 + ntRespLen + (size_t)domainLen + (size_t)userLen;
|
||||
if (total > outCap) return ERR_NOMEM;
|
||||
|
||||
uint8_t* lm = out + kHeader;
|
||||
uint8_t* nt = lm + 24;
|
||||
uint8_t* temp = nt + 16;
|
||||
memset(temp, 0, tempLen);
|
||||
temp[0] = 1;
|
||||
temp[1] = 1;
|
||||
put64(temp + 8, timestamp);
|
||||
memcpy(temp + 16, p.clientChallenge, 8);
|
||||
if (tiLen > 0) memcpy(temp + 28, targetInfo, tiLen);
|
||||
|
||||
// NTProofStr = HMAC-MD5(NTOWFv2, serverChallenge | temp)
|
||||
hmac_md5(ntowf, 16, serverChallenge, 8, temp, tempLen, nt);
|
||||
// SessionBaseKey = HMAC-MD5(NTOWFv2, NTProofStr)
|
||||
hmac_md5(ntowf, 16, nt, 16, nullptr, 0, sessionKey);
|
||||
|
||||
// LMv2 response; all zero when the server supplied a timestamp.
|
||||
memset(lm, 0, 24);
|
||||
if (!haveTimestamp) {
|
||||
hmac_md5(ntowf, 16, serverChallenge, 8, p.clientChallenge, 8, lm);
|
||||
memcpy(lm + 16, p.clientChallenge, 8);
|
||||
}
|
||||
memset(ntowf, 0, sizeof(ntowf));
|
||||
|
||||
uint32_t off = (uint32_t)kHeader;
|
||||
put_field(out + 12, 24, off); off += 24;
|
||||
put_field(out + 20, (uint16_t)ntRespLen, off); off += (uint32_t)ntRespLen;
|
||||
put_field(out + 28, (uint16_t)domainLen, off);
|
||||
memcpy(out + off, domain16, (size_t)domainLen); off += (uint32_t)domainLen;
|
||||
put_field(out + 36, (uint16_t)userLen, off);
|
||||
memcpy(out + off, user16, (size_t)userLen); off += (uint32_t)userLen;
|
||||
put_field(out + 44, 0, off); // workstation
|
||||
put_field(out + 52, 0, off); // encrypted session key
|
||||
put32(out + 60, kClientFlags);
|
||||
return (int)off;
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// SPNEGO (RFC 4178), just enough DER to carry one NTLM token
|
||||
// ==========================================================================
|
||||
|
||||
static size_t der_len_size(size_t len) { return len < 0x80 ? 1 : (len < 0x100 ? 2 : 3); }
|
||||
|
||||
static size_t der_put_len(uint8_t* p, size_t len) {
|
||||
if (len < 0x80) { p[0] = (uint8_t)len; return 1; }
|
||||
if (len < 0x100) { p[0] = 0x81; p[1] = (uint8_t)len; return 2; }
|
||||
p[0] = 0x82; p[1] = (uint8_t)(len >> 8); p[2] = (uint8_t)len;
|
||||
return 3;
|
||||
}
|
||||
|
||||
static size_t der_tlv_size(size_t contentLen) { return 1 + der_len_size(contentLen) + contentLen; }
|
||||
|
||||
static const uint8_t kSpnegoOid[] = {0x06, 0x06, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x02};
|
||||
// mechTypes [0] { SEQUENCE { OID 1.3.6.1.4.1.311.2.2.10 (NTLMSSP) } }
|
||||
static const uint8_t kMechTypes[] = {0xA0, 0x0E, 0x30, 0x0C, 0x06, 0x0A, 0x2B, 0x06, 0x01,
|
||||
0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0A};
|
||||
|
||||
int spnego_wrap(const uint8_t* token, size_t tokenLen, bool first, uint8_t* out, size_t outCap) {
|
||||
if (tokenLen > 0xFF00) return -1;
|
||||
size_t octet = der_tlv_size(tokenLen); // OCTET STRING { token }
|
||||
size_t tagged = der_tlv_size(octet); // [2] { ... }
|
||||
size_t seqContent = tagged + (first ? sizeof(kMechTypes) : 0);
|
||||
size_t seq = der_tlv_size(seqContent); // SEQUENCE { ... }
|
||||
size_t choice = der_tlv_size(seq); // [0] NegTokenInit / [1] NegTokenResp
|
||||
size_t total = first ? der_tlv_size(sizeof(kSpnegoOid) + choice) : choice;
|
||||
if (total > outCap) return -1;
|
||||
|
||||
uint8_t* p = out;
|
||||
if (first) {
|
||||
*p++ = 0x60; // APPLICATION 0
|
||||
p += der_put_len(p, sizeof(kSpnegoOid) + choice);
|
||||
memcpy(p, kSpnegoOid, sizeof(kSpnegoOid));
|
||||
p += sizeof(kSpnegoOid);
|
||||
}
|
||||
*p++ = first ? 0xA0 : 0xA1;
|
||||
p += der_put_len(p, seq);
|
||||
*p++ = 0x30;
|
||||
p += der_put_len(p, seqContent);
|
||||
if (first) {
|
||||
memcpy(p, kMechTypes, sizeof(kMechTypes));
|
||||
p += sizeof(kMechTypes);
|
||||
}
|
||||
*p++ = 0xA2; // mechToken / responseToken
|
||||
p += der_put_len(p, octet);
|
||||
*p++ = 0x04;
|
||||
p += der_put_len(p, tokenLen);
|
||||
memcpy(p, token, tokenLen);
|
||||
p += tokenLen;
|
||||
return (int)(p - out);
|
||||
}
|
||||
|
||||
// Read one DER header at *pos. Returns false if it runs past `len`.
|
||||
static bool der_read(const uint8_t* d, size_t len, size_t* pos, uint8_t* tag, size_t* contentLen) {
|
||||
size_t p = *pos;
|
||||
if (p + 2 > len) return false;
|
||||
*tag = d[p++];
|
||||
size_t l = d[p++];
|
||||
if (l & 0x80) {
|
||||
size_t n = l & 0x7F;
|
||||
if (n == 0 || n > 3 || p + n > len) return false;
|
||||
l = 0;
|
||||
for (size_t i = 0; i < n; i++) l = (l << 8) | d[p++];
|
||||
}
|
||||
if (l > len - p) return false;
|
||||
*contentLen = l;
|
||||
*pos = p;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool spnego_unwrap(const uint8_t* blob, size_t len, const uint8_t** token, size_t* tokenLen) {
|
||||
if (len >= 8 && memcmp(blob, kSignature, 8) == 0) { // raw NTLMSSP
|
||||
*token = blob;
|
||||
*tokenLen = len;
|
||||
return true;
|
||||
}
|
||||
|
||||
// NegTokenResp: [1] { SEQUENCE { [0] negState, [1] mech, [2] { OCTET STRING } ... } }
|
||||
size_t pos = 0;
|
||||
uint8_t tag;
|
||||
size_t clen;
|
||||
if (der_read(blob, len, &pos, &tag, &clen) && tag == 0xA1) {
|
||||
size_t end = pos + clen;
|
||||
if (der_read(blob, end, &pos, &tag, &clen) && tag == 0x30) {
|
||||
end = pos + clen;
|
||||
while (pos < end && der_read(blob, end, &pos, &tag, &clen)) {
|
||||
if (tag == 0xA2) {
|
||||
size_t inner = pos;
|
||||
uint8_t t2;
|
||||
size_t l2;
|
||||
if (der_read(blob, pos + clen, &inner, &t2, &l2) && t2 == 0x04 &&
|
||||
l2 >= 8 && memcmp(blob + inner, kSignature, 8) == 0) {
|
||||
*token = blob + inner;
|
||||
*tokenLen = l2;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
pos += clen;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Unusual framing: fall back to locating the NTLMSSP signature.
|
||||
for (size_t i = 0; i + 8 <= len; i++) {
|
||||
if (memcmp(blob + i, kSignature, 8) == 0) {
|
||||
*token = blob + i;
|
||||
*tokenLen = len - i;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user