///|
/// The NTLM signature function — the one GSS-API calls `GSS_GetMIC` for NTLM
/// and the one SPNEGO needs when a server requires a `mechListMIC`.
///
/// This is not the message MIC of `compute_mic`. That value is an HMAC-MD5
/// over three NTLM messages and lives inside the authenticate message. This
/// one is MS-NLMP 3.4.5's `MAC`: a 16-byte structure keyed by a *signing* key
/// derived from the exported session key, and it is what signs an arbitrary
/// octet string — here the DER of the offered mechanism list.
///
/// Only the extended-session-security form is implemented, because that is the
/// only form this library negotiates: without ESS the MAC needs a stateful RC4
/// handle and a CRC32 checksum, and a server that omits ESS cannot be talked to
/// with the flags the client sends. The check aborts loudly instead of
/// producing a signature that looks valid and is not.

///|
/// MS-NLMP 3.4.5.3. The NUL is part of the constant.
const SIGN_MAGIC_INITIATOR : Bytes = b"session key to client-to-server signing key magic constant\x00"

///|
const SIGN_MAGIC_ACCEPTOR : Bytes = b"session key to server-to-client signing key magic constant\x00"

///|
const FLAG_EXTENDED_SESSIONSECURITY : UInt = 0x00080000U

///|
const FLAG_KEY_EXCHANGE : UInt = 0x40000000U

///|
fn u32le(value : UInt) -> Bytes {
  let out = FixedArray::make(4, b'\x00')
  for i = 0; i < 4; i = i + 1 {
    out[i] = ((value >> (i * 8)) & 0xFFU).to_byte()
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
/// Whether this library can produce a signature under these flags.
///
/// `mac` needs extended session security and refuses key exchange, because
/// the checksum would have to be RC4-encrypted with a key derived from the
/// encrypted random session key — a value this library does not negotiate.
/// Callers that read flags off the wire use this to reject instead of
/// tripping the assertion inside `mac`.
pub fn can_sign(flags : UInt) -> Bool {
  (flags & FLAG_EXTENDED_SESSIONSECURITY) != 0U &&
  (flags & FLAG_KEY_EXCHANGE) == 0U
}

///|
/// The signing key for one direction, MS-NLMP 3.4.5.3:
/// `MD5(ExportedSessionKey || magic)`.
///
/// `initiator` selects client-to-server when true and server-to-client when
/// false, so a client and a server derive different keys from the same session.
pub fn signing_key(
  session_base_key : Bytes,
  flags : UInt,
  initiator : Bool,
) -> Bytes {
  if (flags & FLAG_EXTENDED_SESSIONSECURITY) == 0U {
    abort("signing_key: extended session security was not negotiated")
  }
  let magic = if initiator { SIGN_MAGIC_INITIATOR } else { SIGN_MAGIC_ACCEPTOR }
  @crypto.md5(@crypto.concat(session_base_key, magic))
}

///|
/// MS-NLMP 3.4.5.2 `MAC` with extended session security:
///
/// ```
/// Version   = 0x00000001
/// Checksum  = HMAC_MD5(SigningKey, SeqNum || Message)[0..8]
/// SeqNum    = SeqNum
/// ```
///
/// Sixteen bytes: version, checksum, sequence number. When key exchange is
/// negotiated the checksum would be RC4-encrypted first; this library never
/// sets `NEGOTIATE_KEY_EXCH`, so asking for it here is a programming error
/// rather than a value that would fail later in a confusing place.
pub fn mac(
  signing_key : Bytes,
  flags : UInt,
  seq_num : UInt,
  message : Bytes,
) -> Bytes {
  if (flags & FLAG_EXTENDED_SESSIONSECURITY) == 0U {
    abort("mac: extended session security was not negotiated")
  }
  if (flags & FLAG_KEY_EXCHANGE) != 0U {
    abort("mac: NEGOTIATE_KEY_EXCH is not implemented")
  }
  let seq = u32le(seq_num)
  let digest = @crypto.hmac_md5(signing_key, @crypto.concat(seq, message))
  let out = FixedArray::make(16, b'\x00')
  out[0] = b'\x01'
  for i = 0; i < 8; i = i + 1 {
    out[4 + i] = digest[i]
  }
  for i = 0; i < 4; i = i + 1 {
    out[12 + i] = seq[i]
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
/// Compare a signature in constant time.
pub fn verify_mac(
  signing_key : Bytes,
  flags : UInt,
  seq_num : UInt,
  message : Bytes,
  signature : Bytes,
) -> Bool {
  if signature.length() != 16 {
    return false
  }
  let expected = mac(signing_key, flags, seq_num, message)
  let mut diff = 0
  for i = 0; i < 16; i = i + 1 {
    diff = diff | (expected[i].to_int() ^ signature[i].to_int())
  }
  diff == 0
}

///|
/// The `mechListMIC` an initiator puts in its last `NegTokenTarg`: the MAC over
/// the DER of the mechanism list it offered, keyed with the client-to-server
/// signing key and sequence number zero (the first signature of the context).
pub fn mech_list_mic(
  session_base_key : Bytes,
  flags : UInt,
  mech_list_der : Bytes,
) -> Bytes {
  mac(signing_key(session_base_key, flags, true), flags, 0U, mech_list_der)
}

///|
/// The acceptor's check of that value. Same list, same sequence number, the
/// other direction's key.
pub fn verify_mech_list_mic(
  session_base_key : Bytes,
  flags : UInt,
  mech_list_der : Bytes,
  mic : Bytes,
) -> Bool {
  verify_mac(
    signing_key(session_base_key, flags, true),
    flags,
    0U,
    mech_list_der,
    mic,
  )
}

///|
/// The `mechListMIC` an acceptor sends back, keyed with the server-to-client
/// signing key.
pub fn acceptor_mech_list_mic(
  session_base_key : Bytes,
  flags : UInt,
  mech_list_der : Bytes,
) -> Bytes {
  mac(signing_key(session_base_key, flags, false), flags, 0U, mech_list_der)
}

///|
/// The initiator's check of the acceptor's `mechListMIC`.
pub fn verify_acceptor_mech_list_mic(
  session_base_key : Bytes,
  flags : UInt,
  mech_list_der : Bytes,
  mic : Bytes,
) -> Bool {
  verify_mac(
    signing_key(session_base_key, flags, false),
    flags,
    0U,
    mech_list_der,
    mic,
  )
}