#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
srp_cyrus.py - client side of the SASL "SRP" mechanism as implemented by the
cyrus-sasl srp plugin (plugins/srp.c, 2.1.27 line, SHA-1), for driving raw LDAP
SASL binds one step at a time.

Wire dialect (MakeBuffer/UnBuffer): every SASL credentials blob is
    u32BE(total) || payload
with primitives   %m = u16BE len || minimal big-endian MPI
                  %o = u8 len || bytes
                  %s = u16BE len || bytes
  step 1 (client)   { utf8(U) utf8(I) utf8(sid) os(cn) }
  step 1 (server)   { 0x00, mpi(N), mpi(g), os(s), mpi(B), utf8(L) }
  step 2 (client)   { mpi(A), os(M1), utf8(o), os(cIV) }
  step 2 (server)   { os(M2), os(sIV), utf8(sid), uint(ttl) }
Math (MakeHash): k = 3, u = H(A || B), x = H(s || H(U ":" pw)),
  S = (B - 3 g^x) ^ (a + u x), K = H(S),
  M1 = H( (H(N) xor H(g)) || H(U) || s || A || B || K || H(I) || H(L) ).
`client_finish` lets the caller override A and M1, and U / I are passed
independently, so authorization-identity and malformed-token cases can be driven.
"""
import hashlib
import os


def H(b):
    return hashlib.sha1(b).digest()


def s16(b):
    return len(b).to_bytes(2, "big") + b


def o8(b):
    return len(b).to_bytes(1, "big") + b


def minb(n):
    return n.to_bytes(max(1, (n.bit_length() + 7) // 8), "big")


def mpi(n):
    return s16(minb(n))


def blob(payload):
    return len(payload).to_bytes(4, "big") + payload


class R(object):
    def __init__(self, b):
        self.b = b
        self.o = 0

    def take(self, n):
        if self.o + n > len(self.b):
            raise ValueError("short buffer (%d needed at %d, have %d)" % (n, self.o, len(self.b)))
        x = self.b[self.o:self.o + n]
        self.o += n
        return x

    def u8(self):
        return self.take(1)[0]

    def u16(self):
        return int.from_bytes(self.take(2), "big")

    def u32(self):
        return int.from_bytes(self.take(4), "big")

    def os(self):
        return self.take(self.u8())

    def s(self):
        return self.take(self.u16())

    def m(self):
        return int.from_bytes(self.take(self.u16()), "big")

    def left(self):
        return len(self.b) - self.o


def unblob(creds):
    if len(creds) < 4:
        raise ValueError("no SASL data (%d bytes)" % len(creds))
    n = int.from_bytes(creds[:4], "big")
    return creds[4:4 + n]


def client_init(U, I=b"", sid=b"", cn=b""):
    return blob(s16(U) + s16(I) + s16(sid) + o8(cn))


def parse_challenge(creds):
    r = R(unblob(creds))
    return {"tag": r.u8(), "N": r.m(), "g": r.m(), "salt": r.os(), "B": r.m(),
            "L": r.s(), "extra": r.left()}


def calc_m1(U, I, salt, A, B, N, g, K, L):
    ng = bytes(p ^ q for p, q in zip(H(minb(N)), H(minb(g))))
    return H(ng + H(U) + salt + minb(A) + minb(B) + K + H(I) + H(L))


def client_finish(U, I, password, salt, B, N, g, L, a=None, m1=None,
                  opts=b"mda=sha1", civ=b""):
    """Returns (credentials blob, dict(A, K, M1)). `a=None` picks a fresh exponent;
    `m1` overrides the computed client evidence (for negative controls)."""
    a = int.from_bytes(os.urandom(32), "big") if a is None else a
    A = pow(g, a, N)
    u = int.from_bytes(H(mpi(A) + mpi(B)), "big")
    x = int.from_bytes(H(salt + H(U + b":" + password)), "big")
    S = pow((B - 3 * pow(g, x, N)) % N, a + u * x, N)
    K = H(minb(S))
    if m1 is None:
        m1 = calc_m1(U, I, salt, A, B, N, g, K, L)
    return blob(mpi(A) + o8(m1) + s16(opts) + o8(civ)), {"A": A, "K": K, "M1": m1}


def client_finish_A(A, m1, opts=b"mda=sha1", civ=b""):
    """Assemble a step-2 blob from an arbitrary A and M1."""
    return blob(mpi(A) + o8(m1) + s16(opts) + o8(civ))


def parse_final(creds):
    r = R(unblob(creds))
    out = {"M2": r.os(), "sIV": r.os(), "sid": r.s(), "ttl": r.u32()}
    out["extra"] = r.left()
    return out


def calc_m2(A, m1, K, I, opts, sid, ttl):
    return H(minb(A) + m1 + K + H(I) + H(opts) + sid + ttl.to_bytes(4, "big"))
