///|
/// SPNEGO (RFC 4178) as it is used in HTTP authentication: the ASN.1 wrapper
/// that carries an NTLM token inside `Authorization: Negotiate`.
///
/// Two shapes matter in practice. The first client message is a full GSS-API
/// `InitialContextToken` — application tag 0, the SPNEGO OID, then a
/// `NegTokenInit` whose `mechToken [2]` is the NTLM type 1 message. Every
/// message after that is a bare `NegTokenTarg` — `[1]` — whose
/// `responseToken [2]` is the type 2 or type 3 message.
///
/// Some servers skip SPNEGO entirely and put the NTLM message straight in the
/// header. `unwrap` accepts both, because a client that cannot read what the
/// server actually sent is not much of a client.
const OID_SPNEGO : Bytes = b"\x2b\x06\x01\x05\x05\x02"
// 1.3.6.1.4.1.311.2.2.10
///|
const OID_NTLMSSP : Bytes = b"\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a"
///|
pub fn is_ntlmssp(token : Bytes) -> Bool {
if token.length() < 8 {
return false
}
let signature = b"NTLMSSP\x00"
let mut same = true
for i = 0; i < 8; i = i + 1 {
if token[i] != signature[i] {
same = false
}
}
same
}
///|
/// A SPNEGO token starts with either the GSS application tag (0x60) or one of
/// the NegotiationToken choice tags.
pub fn is_spnego(token : Bytes) -> Bool {
if token.length() < 2 || is_ntlmssp(token) {
return false
}
let first = token[0].to_int()
first == 0x60 || first == 0xA0 || first == 0xA1 || first == 0x30
}
///|
fn copy_range(data : Bytes, start : Int, length : Int) -> Bytes {
let out = FixedArray::make(length, b'\x00')
for i = 0; i < length; i = i + 1 {
out[i] = data[start + i]
}
FixedArray::unsafe_reinterpret_as_bytes(out)
}
///|
/// The DER of the `MechTypeList` this library offers: a SEQUENCE holding the
/// NTLMSSP OID. This is the byte string a `mechListMIC` is computed over, so
/// `wrap_init` and the MIC both go through here rather than each building its
/// own encoding — two encoders that agree today can disagree after an edit.
pub fn mech_list_der() -> Bytes {
sequence(oid(OID_NTLMSSP))
}
///|
/// The `MechTypeList` an incoming `NegTokenInit` carried, as the exact DER
/// bytes it arrived in.
///
/// A `mechListMIC` covers what the initiator sent, not what this library would
/// have encoded, so an acceptor has to check against these bytes rather than
/// against `mech_list_der()`. A peer that offers two mechanisms would otherwise
/// be rejected for a MIC it computed correctly.
pub fn offered_mech_list(token : Bytes) -> Bytes raise DerError {
if token.length() < 2 {
raise Truncated(token.length())
}
let mut start = 0
let mut node = read_tlv(token, 0)
if node.tag() == 0x60 {
let mech = read_tlv(token, node.content())
if mech.tag() != 0x06 {
raise BadTag(mech.tag(), 0x06)
}
start = mech.content() + mech.length()
node = read_tlv(token, start)
}
// Peel `[0]` wrappers until a SEQUENCE is reached. A NegTokenInit is one,
// and so is the MechTypeList inside it; which one it is becomes clear from
// what the sequence holds.
while node.tag() == 0xA0 || node.tag() == 0xA1 {
start = node.content()
node = read_tlv(token, start)
}
if node.tag() != 0x30 {
raise BadTag(node.tag(), 0x30)
}
if node.length() == 0 {
raise MissingToken
}
let first = read_tlv(token, node.content())
if first.tag() == 0x06 {
// This sequence is the MechTypeList itself.
return copy_range(token, start, node.content() - start + node.length())
}
// A NegTokenInit: find its `[0] mech_types` field and return that sequence
// together with its own header, which is what the MIC covers.
let end = node.content() + node.length()
let mut cursor = node.content()
while cursor < end {
let field = read_tlv(token, cursor)
if field.tag() == 0xA0 {
let inner_start = field.content()
let inner = read_tlv(token, inner_start)
if inner.tag() == 0x30 {
return copy_range(
token,
inner_start,
inner.content() - inner_start + inner.length(),
)
}
}
cursor = field.content() + field.length()
}
raise MissingToken
}
///|
/// The client's opening message: GSS-API wrapper around a NegTokenInit whose
/// only offered mechanism is NTLMSSP.
pub fn wrap_init(ntlm_token : Bytes) -> Bytes {
let mech_types = mech_list_der()
let neg_init = sequence(
@crypto.concat(context(0, mech_types), context(2, octet_string(ntlm_token))),
)
tlv(0x60, @crypto.concat(oid(OID_SPNEGO), context(0, neg_init)))
}
///|
/// A NegTokenTarg with no negState, which is what a client sends last.
pub fn wrap_response(ntlm_token : Bytes) -> Bytes {
tlv(0xA1, sequence(context(2, octet_string(ntlm_token))))
}
///|
/// A NegTokenTarg carrying `negState` — a server uses
/// 1 (accept-incomplete) with its challenge.
pub fn wrap_response_state(ntlm_token : Bytes, state : Int) -> Bytes {
tlv(
0xA1,
sequence(
@crypto.concat(
context(0, enumerated(state)),
context(2, octet_string(ntlm_token)),
),
),
)
}
///|
fn find_token(data : Bytes, tlv_value : Tlv) -> Bytes raise DerError {
// The content of [0]/[1] is a SEQUENCE; a bare 0x30 is that sequence already.
let (at, length) = if tlv_value.tag() == 0x30 {
(tlv_value.content(), tlv_value.length())
} else if tlv_value.tag() == 0xA0 || tlv_value.tag() == 0xA1 {
let inner = read_tlv(data, tlv_value.content())
if inner.tag() != 0x30 {
raise BadTag(inner.tag(), 0x30)
}
(inner.content(), inner.length())
} else {
raise BadTag(tlv_value.tag(), 0x30)
}
let end = at + length
let mut cursor = at
while cursor < end {
let field = read_tlv(data, cursor)
if field.tag() == 0xA2 {
let octets = read_tlv(data, field.content())
if octets.tag() != 0x04 {
raise BadTag(octets.tag(), 0x04)
}
return copy_range(data, octets.content(), octets.length())
}
cursor = field.content() + field.length()
}
raise MissingToken
}
///|
/// Pull the NTLM message out of whatever the peer sent: a bare NTLMSSP
/// message, a GSS-wrapped NegTokenInit, or a NegTokenTarg.
pub fn unwrap(token : Bytes) -> Bytes raise DerError {
if is_ntlmssp(token) {
return token
}
if token.length() < 2 {
raise Truncated(token.length())
}
let outer = read_tlv(token, 0)
if outer.tag() == 0x60 {
// App 0 { thisMech OID, innerContextToken NegotiationToken }
let mech = read_tlv(token, outer.content())
if mech.tag() != 0x06 {
raise BadTag(mech.tag(), 0x06)
}
let inner = read_tlv(token, mech.content() + mech.length())
if inner.tag() != 0xA0 && inner.tag() != 0xA1 && inner.tag() != 0x30 {
raise BadTag(inner.tag(), 0xA0)
}
return find_token(token, inner)
}
find_token(token, outer)
}
///|
/// A one-line description of a token, for the CLI and for error messages.
pub fn describe(token : Bytes) -> String {
if is_ntlmssp(token) {
return "ntlmssp message"
}
if token.length() < 2 {
return "empty"
}
let tag = token[0].to_int()
if tag == 0x60 {
"spnego initial context token"
} else if tag == 0xA1 {
"spnego negtokenresp"
} else if tag == 0xA0 {
"spnego negtokeninit"
} else if tag == 0x30 {
"der sequence"
} else {
"unknown"
}
}
///|
/// The four values `negState` can take (RFC 4178 section 4.2.2). A server
/// sends `accept-incomplete` while it still expects a token, `request-mic`
/// when it wants a `mechListMIC` before it will finish, and `accept-completed`
/// on the last message.
pub(all) enum NegState {
AcceptCompleted
AcceptIncomplete
Rejected
RequestMic
}
///|
pub fn NegState::to_int(self : NegState) -> Int {
match self {
AcceptCompleted => 0
AcceptIncomplete => 1
Rejected => 2
RequestMic => 3
}
}
///|
pub fn NegState::from_int(value : Int) -> NegState? {
match value {
0 => Some(AcceptCompleted)
1 => Some(AcceptIncomplete)
2 => Some(Rejected)
3 => Some(RequestMic)
_ => None
}
}
///|
/// The fields of a `NegTokenTarg` that matter over HTTP.
pub struct NegTarg {
state : NegState?
supported_mech : Bytes?
response_token : Bytes?
mech_list_mic : Bytes?
}
///|
pub fn NegTarg::state(self : NegTarg) -> NegState? {
self.state
}
///|
/// The mechanism the acceptor selected, as the raw OID content. RFC 4178 puts
/// it in the first `NegTokenTarg` an acceptor sends and forbids it afterwards.
pub fn NegTarg::supported_mech(self : NegTarg) -> Bytes? {
self.supported_mech
}
///|
pub fn NegTarg::response_token(self : NegTarg) -> Bytes? {
self.response_token
}
///|
pub fn NegTarg::mech_list_mic(self : NegTarg) -> Bytes? {
self.mech_list_mic
}
///|
/// Parse a `NegTokenTarg`, either with its `[1]` wrapper or as the bare
/// SEQUENCE some stacks emit. Unknown context tags are skipped rather than
/// rejected: a peer may add fields this code does not model.
pub fn parse_neg_targ(token : Bytes) -> NegTarg raise DerError {
if token.length() < 2 {
raise Truncated(token.length())
}
let outer = read_tlv(token, 0)
let (at, length) = if outer.tag() == 0xA1 {
let inner = read_tlv(token, outer.content())
if inner.tag() != 0x30 {
raise BadTag(inner.tag(), 0x30)
}
(inner.content(), inner.length())
} else if outer.tag() == 0x30 {
(outer.content(), outer.length())
} else {
raise BadTag(outer.tag(), 0xA1)
}
let end = at + length
let mut cursor = at
let mut state : NegState? = None
let mut supported : Bytes? = None
let mut response : Bytes? = None
let mut mic : Bytes? = None
while cursor < end {
let field = read_tlv(token, cursor)
match field.tag() {
0xA0 =>
if field.length() > 0 {
let value = read_tlv(token, field.content())
if value.tag() == 0x0A && value.length() > 0 {
state = NegState::from_int(token[value.content()].to_int())
}
}
0xA1 => {
let value = read_tlv(token, field.content())
if value.tag() == 0x06 {
supported = Some(copy_range(token, value.content(), value.length()))
}
}
0xA2 => {
let value = read_tlv(token, field.content())
if value.tag() == 0x04 {
response = Some(copy_range(token, value.content(), value.length()))
}
}
0xA3 => {
let value = read_tlv(token, field.content())
if value.tag() == 0x04 {
mic = Some(copy_range(token, value.content(), value.length()))
}
}
_ => ()
}
cursor = field.content() + field.length()
}
{
state,
supported_mech: supported,
response_token: response,
mech_list_mic: mic,
}
}
///|
/// A `NegTokenTarg` with a state, the selected mechanism and, when the server
/// asked for one, a `mechListMIC`.
///
/// RFC 4178 requires `supportedMech` in the first `NegTokenTarg` the acceptor
/// sends and forbids it in later ones; callers that are not the acceptor pass
/// `None`.
///
/// The MIC value is computed by `src/ntlm` — `mech_list_mic` over
/// `mech_list_der()` for the initiator, `acceptor_mech_list_mic` for the
/// acceptor — because RFC 4178 hands the value to the GSS mechanism, and the
/// mechanism here is NTLM. Passing a MIC this layer invented would be worse
/// than passing none.
pub fn wrap_targ_with_mech(
ntlm_token : Bytes,
state : NegState?,
supported_mech : Bytes?,
mech_list_mic : Bytes?,
) -> Bytes {
let mut content = b""
match state {
Some(s) => content = context(0, enumerated(s.to_int()))
None => ()
}
match supported_mech {
Some(mech) => content = @crypto.concat(content, context(1, oid(mech)))
None => ()
}
content = @crypto.concat(content, context(2, octet_string(ntlm_token)))
match mech_list_mic {
Some(m) => content = @crypto.concat(content, context(3, octet_string(m)))
None => ()
}
tlv(0xA1, sequence(content))
}
///|
/// A `NegTokenTarg` with only the fields HTTP needs: state, response token and
/// an optional `mechListMIC`.
pub fn wrap_targ(
ntlm_token : Bytes,
state : NegState?,
mech_list_mic : Bytes?,
) -> Bytes {
wrap_targ_with_mech(ntlm_token, state, None, mech_list_mic)
}
///|
/// The acceptor's last `NegTokenTarg`: `negState` and its own `mechListMIC`,
/// with no `responseToken` — the negotiation has no further NTLM message to
/// carry, and an empty `[2]` would be a field where RFC 4178 allows none.
pub fn wrap_final(state : NegState, mech_list_mic : Bytes) -> Bytes {
tlv(
0xA1,
sequence(
@crypto.concat(
context(0, enumerated(state.to_int())),
context(3, octet_string(mech_list_mic)),
),
),
)
}
///|
/// The acceptor's first `NegTokenTarg`: `negState`, the NTLMSSP mechanism, and
/// the challenge. This is the shape RFC 4178 asks for; a bare NegTokenTarg
/// without `supportedMech` is accepted by many clients but is not conformant.
pub fn wrap_challenge(ntlm_token : Bytes, state : NegState) -> Bytes {
wrap_targ_with_mech(ntlm_token, Some(state), Some(OID_NTLMSSP), None)
}