///|
/// The conversation: a client that answers a challenge and a server that
/// issues one and checks the answer. Both work on header values, so the HTTP
/// stack around them stays the caller's business.

///|
/// UNICODE | OEM | REQUEST_TARGET | SIGN | NTLM | ALWAYS_SIGN |
/// EXTENDED_SESSIONSECURITY | TARGET_INFO.
///
/// `TARGET_INFO` is what tells the server to populate the challenge's AV
/// pairs; without it a strict server may omit the timestamp and the SPN, and
/// the blob then loses the binding those pairs provide.
///
/// `SIGN` is what makes the NTLM signature function produce a real keyed MAC
/// instead of the all-zero placeholder SSPI uses when only `ALWAYS_SIGN` is
/// set. A `mechListMIC` computed under the placeholder would be accepted and
/// would protect nothing, so it is negotiated explicitly.
const CLIENT_FLAGS : UInt = 0x00888217U

///|
const SERVER_FLAGS : UInt = 0x20888211U

///|
fn le16(value : Int) -> Bytes {
  let out = FixedArray::make(2, b'\x00')
  out[0] = (value & 0xFF).to_byte()
  out[1] = ((value >> 8) & 0xFF).to_byte()
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
/// One AV pair: 2-byte id, 2-byte length, value.
fn av_pair(id : Int, value : Bytes) -> Bytes {
  @crypto.concat(@crypto.concat(le16(id), le16(value.length())), value)
}

///|
fn utf16(text : String) -> Bytes {
  @utf16.encode(text, endianness=Little)
}

///|
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)
}

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

///|
/// Target info as a Windows server sends it: the domain and the machine name,
/// then the end-of-list pair. A server that wants a MIC adds `MsvAvFlags` with
/// bit 1 set and a timestamp — a timestamp alone is enough to make most
/// clients sign, and Windows servers send it for the same reason.
fn target_info(
  domain : String,
  computer : String,
  mic_required : Bool,
  timestamp : UInt64,
) -> Bytes {
  let base = @crypto.concat(
    av_pair(2, utf16(domain)),
    av_pair(1, utf16(computer)),
  )
  let signed = if mic_required {
    @crypto.concat(
      @crypto.concat(base, av_pair(6, u32le(2U))),
      av_pair(7, u64le(timestamp)),
    )
  } else {
    base
  }
  @crypto.concat(signed, b"\x00\x00\x00\x00")
}

///|
fn first16(data : Bytes) -> Bytes {
  let out = FixedArray::make(16, b'\x00')
  for i = 0; i < 16; i = i + 1 {
    out[i] = data[i]
  }
  FixedArray::unsafe_reinterpret_as_bytes(out)
}

///|
pub struct Client {
  user : String
  domain : String
  password : String
  workstation : String
  spnego : Bool
  client_challenge : Bytes
  timestamp : UInt64
  flags : UInt
  /// Exported session key of the last answer. Kept so the client can check the
  /// acceptor's `mechListMIC`, which arrives after the answer was sent.
  mut last_session_key : Bytes
  /// Flags carried by the last authenticate message; the signing keys depend
  /// on them, so the acceptor's MIC must be checked with the same value.
  mut last_flags : UInt
  /// The `mechListMIC` this client sent, empty when it sent none.
  mut last_mech_list_mic : Bytes
}

///|
pub fn Client::new(user : String, domain : String, password : String) -> Client {
  {
    user,
    domain,
    password,
    workstation: "",
    spnego: true,
    client_challenge: b"\x00\x00\x00\x00\x00\x00\x00\x00",
    timestamp: 0UL,
    flags: CLIENT_FLAGS,
    last_session_key: b"",
    last_flags: 0U,
    last_mech_list_mic: b"",
  }
}

///|
/// A client with a fixed client challenge and timestamp, which is what tests
/// and reproducible runs need. Deterministic challenges are not for production.
pub fn Client::with_fixed_challenge(
  user : String,
  domain : String,
  password : String,
  client_challenge : Bytes,
  timestamp : UInt64,
) -> Client {
  {
    user,
    domain,
    password,
    workstation: "",
    spnego: true,
    client_challenge,
    timestamp,
    flags: CLIENT_FLAGS,
    last_session_key: b"",
    last_flags: 0U,
    last_mech_list_mic: b"",
  }
}

///|
pub fn Client::bare(self : Client) -> Client {
  {
    user: self.user,
    domain: self.domain,
    password: self.password,
    workstation: self.workstation,
    spnego: false,
    client_challenge: self.client_challenge,
    timestamp: self.timestamp,
    flags: self.flags,
    last_session_key: b"",
    last_flags: 0U,
    last_mech_list_mic: b"",
  }
}

///|
/// The raw NTLM negotiate message this client sends. Exposed because a MIC is
/// computed over exactly these bytes, so a caller that builds the exchange by
/// hand must use the same message rather than one with its own flags.
pub fn Client::type1_token(self : Client) -> Bytes {
  @ntlm.encode_type1(self.flags)
}

///|
/// The first `Authorization` value, to be sent after a bare 401.
pub fn Client::start(self : Client) -> String {
  let token = self.type1_token()
  if self.spnego {
    authorization_header("Negotiate", @spnego.wrap_init(token))
  } else {
    authorization_header("NTLM", token)
  }
}

///|
/// Whether the server's `NegTokenTarg` asks for a `mechListMIC`: either the
/// `negState` is `request-mic` (RFC 4178 section 4.2.2), or the token already
/// carries one, which obliges the initiator to answer in kind.
fn challenge_wants_mic(token : Bytes) -> Bool {
  let targ = @spnego.parse_neg_targ(token) catch { _ => return false }
  let asks = match targ.state() {
    Some(state) => state.to_int() == 3
    None => false
  }
  if asks {
    return true
  }
  match targ.mech_list_mic() {
    Some(mic) => mic.length() > 0
    None => false
  }
}

///|
/// The second `Authorization` value, built from the server's
/// `WWW-Authenticate` header. The answer uses the scheme the server offered,
/// so a server that skips SPNEGO still gets a bare NTLM message back.
///
/// Three things can end up in the answer: the NTLMv2 response, the message MIC
/// when the challenge carries `MsvAvFlags` bit 1 or a timestamp, and the
/// `mechListMIC` when the acceptor asked for it. The two MICs are different
/// values over different bytes and are computed separately.
pub fn Client::answer(self : Client, www_authenticate : String) -> String raise {
  let challenges = parse_challenges(www_authenticate)
  let challenge = match preferred(challenges) {
    Some(c) => c
    None => raise Malformed("no usable NTLM or Negotiate challenge")
  }
  let bare = @spnego.unwrap(challenge.token())
  let msg = @ntlm.parse_type2(bare)
  // The authenticate message reports the features both sides selected, not
  // everything the client offered. Keeping a bit the acceptor never offered
  // would describe a session the server did not agree to. The target-type
  // bits describe the server rather than the client, so they survive the
  // intersection, and UNICODE stays because every string below is UTF-16.
  let flags = (self.flags & (msg.flags() | 0x00070000U)) | 0x00000001U
  let wants_mic = msg.requires_mic()
  // MS-NLMP 3.1.5.2.1: when the challenge carries MsvAvTimestamp, that value
  // is the blob's timestamp — not the local clock and not zero. A server that
  // sent one compares it with the blob, so a different time fails even with
  // the right password. The same paragraph asks the client to record the MIC
  // in MsvAvFlags, which is how an acceptor knows a MIC is present at all.
  let timestamp = match msg.timestamp() {
    Some(value) => value
    None => self.timestamp
  }
  let mut info = msg.av_pairs()
  if wants_mic {
    info = @ntlm.with_av_flags(info, msg.av_flags() | 0x2U)
  }
  let blob = @ntlm.make_blob(timestamp, self.client_challenge, info)
  let nt = @ntlm.ntlmv2_response(
    self.user,
    self.domain,
    self.password,
    msg.server_challenge(),
    blob,
  )
  let key = @ntlm.session_base_key(
    self.user,
    self.domain,
    self.password,
    first16(nt),
  )
  self.last_session_key = key
  self.last_flags = flags
  let type3 = if wants_mic {
    // The MIC covers the negotiate message, the challenge and the answer, with
    // the MIC field itself zero while it is computed.
    let zero_mic = b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
    let unsigned = @ntlm.encode_type3_with_mic(
      self.user,
      self.domain,
      self.workstation,
      b"",
      nt,
      b"",
      flags,
      zero_mic,
    )
    let mic = @ntlm.compute_mic(key, self.type1_token(), bare, unsigned)
    @ntlm.encode_type3_with_mic(
      self.user,
      self.domain,
      self.workstation,
      b"",
      nt,
      b"",
      flags,
      mic,
    )
  } else {
    @ntlm.encode_type3(
      self.user,
      self.domain,
      self.workstation,
      b"",
      nt,
      b"",
      flags,
    )
  }
  if self.spnego && same_scheme(challenge.scheme(), "Negotiate") {
    if challenge_wants_mic(challenge.token()) {
      if !@ntlm.can_sign(flags) {
        raise Malformed(
          "the acceptor asked for a mechListMIC, but extended session security was not negotiated",
        )
      }
      // Signing the mechanism list the client itself offered, with the
      // exported session key and the client-to-server signing key.
      let mic = @ntlm.mech_list_mic(key, flags, @spnego.mech_list_der())
      self.last_mech_list_mic = mic
      authorization_header(
        "Negotiate",
        @spnego.wrap_targ(type3, None, Some(mic)),
      )
    } else {
      self.last_mech_list_mic = b""
      authorization_header("Negotiate", @spnego.wrap_response(type3))
    }
  } else {
    self.last_mech_list_mic = b""
    authorization_header("NTLM", type3)
  }
}

///|
/// The `mechListMIC` the last answer carried, empty when it carried none.
pub fn Client::mech_list_mic(self : Client) -> Bytes {
  self.last_mech_list_mic
}

///|
/// Check the acceptor's `mechListMIC`, which arrives in the `WWW-Authenticate`
/// of the reply that ends the negotiation. A server that asked for a MIC and
/// does not send its own is not rejected here — RFC 4178 makes the acceptor's
/// MIC conditional — but one that sends a wrong value is.
pub fn Client::verify_acceptor_mic(
  self : Client,
  www_authenticate : String,
) -> Bool raise {
  let challenges = parse_challenges(www_authenticate)
  let challenge = match preferred(challenges) {
    Some(c) => c
    None => raise Malformed("no usable NTLM or Negotiate challenge")
  }
  let targ = @spnego.parse_neg_targ(challenge.token())
  if self.last_session_key.length() != 16 || !@ntlm.can_sign(self.last_flags) {
    return false
  }
  match targ.mech_list_mic() {
    Some(mic) =>
      @ntlm.verify_acceptor_mech_list_mic(
        self.last_session_key,
        self.last_flags,
        @spnego.mech_list_der(),
        mic,
      )
    None => false
  }
}

///|
pub struct Server {
  user : String
  domain : String
  password : String
  challenge : Bytes
  target_domain : String
  computer : String
  mic_required : Bool
  mech_list_mic_required : Bool
  mut last_type1 : Bytes
  mut last_type2 : Bytes
  /// The `MechTypeList` DER the client offered, taken from its NegTokenInit.
  mut last_mech_list : Bytes
  mut last_session_key : Bytes
  mut last_flags : UInt
}

///|
/// `challenge` must be fresh per connection in real use; it is a parameter so
/// that tests and demos can pin it.
pub fn Server::new(
  user : String,
  domain : String,
  password : String,
  challenge : Bytes,
) -> Server {
  if challenge.length() != 8 {
    abort("Server::new: the challenge must be 8 bytes")
  }
  {
    user,
    domain,
    password,
    challenge,
    target_domain: domain,
    computer: "SERVER",
    mic_required: false,
    mech_list_mic_required: false,
    last_type1: b"",
    last_type2: b"",
    last_mech_list: b"",
    last_session_key: b"",
    last_flags: 0U,
  }
}

///|
/// Ask the client for a MIC. The challenge then carries `MsvAvFlags = 0x2` and
/// a timestamp, and `accept` checks the field instead of ignoring it.
pub fn Server::require_mic(self : Server) -> Server {
  {
    user: self.user,
    domain: self.domain,
    password: self.password,
    challenge: self.challenge,
    target_domain: self.target_domain,
    computer: self.computer,
    mic_required: true,
    mech_list_mic_required: self.mech_list_mic_required,
    last_type1: b"",
    last_type2: b"",
    last_mech_list: b"",
    last_session_key: b"",
    last_flags: 0U,
  }
}

///|
/// Ask the client for a `mechListMIC` as well (RFC 4178 section 5). The
/// challenge goes out with `negState = request-mic`, `accept` refuses an answer
/// that does not carry the value, and `finish_token` produces the acceptor's
/// own MIC so the client can check the other direction.
pub fn Server::require_mech_list_mic(self : Server) -> Server {
  {
    user: self.user,
    domain: self.domain,
    password: self.password,
    challenge: self.challenge,
    target_domain: self.target_domain,
    computer: self.computer,
    mic_required: self.mic_required,
    mech_list_mic_required: true,
    last_type1: b"",
    last_type2: b"",
    last_mech_list: b"",
    last_session_key: b"",
    last_flags: 0U,
  }
}

///|
/// The type 2 message this server would send, wrapped if the client spoke
/// SPNEGO. `authorization` is what arrived, so the reply mirrors its scheme.
pub fn Server::challenge_for(
  self : Server,
  authorization : String,
) -> String raise {
  let request = parse_authorization(authorization)
  let token = request.token()
  self.last_type1 = @spnego.unwrap(token)
  self.last_session_key = b""
  self.last_flags = 0U
  self.last_mech_list = b""
  if self.mech_list_mic_required {
    // Verify against the bytes the client sent, not against our own encoding.
    self.last_mech_list = @spnego.offered_mech_list(token) catch { _ => b"" }
  }
  let type2 = @ntlm.encode_type2(
    SERVER_FLAGS,
    self.challenge,
    utf16(self.target_domain),
    target_info(self.target_domain, self.computer, self.mic_required, 0UL),
  )
  self.last_type2 = type2
  if same_scheme(request.scheme(), "Negotiate") {
    let state = if self.mech_list_mic_required {
      @spnego.RequestMic
    } else {
      @spnego.AcceptIncomplete
    }
    challenge_header_with_token(
      "Negotiate",
      @spnego.wrap_challenge(type2, state),
    )
  } else {
    if self.mech_list_mic_required {
      // A mechListMIC only exists inside SPNEGO. Sending a bare NTLM
      // challenge would leave the client with no way to answer the demand,
      // so the conversation would fail one step later for no visible reason.
      raise Malformed(
        "a mechListMIC requires SPNEGO, but the client sent a bare NTLM request",
      )
    }
    challenge_header_with_token("NTLM", type2)
  }
}

///|
/// Check a client's answer against the password this server knows: the NTLMv2
/// proof, the message MIC when one was demanded, and the `mechListMIC` when the
/// challenge asked for it.
pub fn Server::accept(self : Server, authorization : String) -> Bool raise {
  let request = parse_authorization(authorization)
  let token = request.token()
  let bare = @spnego.unwrap(token)
  let msg = @ntlm.parse_type3(bare)
  // Nothing is finished until every check here has passed: `finish_token`
  // keys off this value, and an answer that was refused must not leave a
  // session behind for a caller that did not look at the result.
  self.last_session_key = b""
  self.last_flags = 0U
  let proof_ok = @ntlm.verify_response(
    self.user,
    self.domain,
    self.password,
    self.challenge,
    msg.nt_response(),
  )
  if !proof_ok {
    return false
  }
  let key = @ntlm.session_base_key(
    self.user,
    self.domain,
    self.password,
    first16(msg.nt_response()),
  )
  // MS-NLMP 3.2.5.1.2: the message says whether it carries a MIC through
  // MsvAvFlags bit 1, and a server has to check a MIC the client claims even
  // if it did not ask for one. Trusting only the server's own configuration
  // is the shape of CVE-2019-1040 — a signed answer could be downgraded to an
  // unchecked one. A demanded MIC that the blob does not acknowledge is
  // refused for the same reason.
  let claims_mic = @ntlm.blob_claims_mic(msg.nt_response())
  if claims_mic || self.mic_required {
    if !@ntlm.verify_mic(key, self.last_type1, self.last_type2, bare) {
      return false
    }
  }
  if self.mech_list_mic_required {
    if self.last_mech_list.length() == 0 {
      return false
    }
    let targ = @spnego.parse_neg_targ(token) catch { _ => return false }
    let mic = match targ.mech_list_mic() {
      Some(value) => value
      None => return false
    }
    // The flags come from the client. Asserting inside `mac` on flags this
    // library cannot sign would turn a malformed message into a panic, so an
    // unusable set is a rejection, not an exception.
    if !@ntlm.can_sign(msg.flags()) {
      return false
    }
    if !@ntlm.verify_mech_list_mic(key, msg.flags(), self.last_mech_list, mic) {
      return false
    }
  }
  self.last_session_key = key
  self.last_flags = msg.flags()
  true
}

///|
/// The acceptor's closing `NegTokenTarg`: `accept-completed` plus its own
/// `mechListMIC`. Over HTTP this travels in the `WWW-Authenticate` of the
/// reply that ends the negotiation, and the client's next request carries an
/// empty `Negotiate` token to collect the `200`.
pub fn Server::finish_token(self : Server) -> String raise {
  if !self.mech_list_mic_required {
    raise Malformed("finish_token: this server did not ask for a mechListMIC")
  }
  if self.last_session_key.length() != 16 || self.last_mech_list.length() == 0 {
    raise Malformed("finish_token: no accepted session to finish")
  }
  if !@ntlm.can_sign(self.last_flags) {
    raise Malformed("finish_token: these flags do not allow a signature")
  }
  let mic = @ntlm.acceptor_mech_list_mic(
    self.last_session_key,
    self.last_flags,
    self.last_mech_list,
  )
  challenge_header_with_token(
    "Negotiate",
    @spnego.wrap_final(@spnego.AcceptCompleted, mic),
  )
}