#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ ldap_raw.py - minimal raw-BER LDAPv3 client (no ldap3) for protocol experiments: SASL bind one step at a time, simple bind, add, modify, search, compare, whoami, optional TLS for LDAPS. Conventions verified against the shipped vmdird (8.0 U3k): [APPLICATION n] tags are IMPLICIT - they REPLACE the SEQUENCE tag, there is never an inner 0x30 (BindRequest 0x60, AddRequest 0x68, ModifyRequest 0x66, SearchRequest 0x63, SaslCredentials [3] 0xa3). Add/Modify still wrap their list of attributes / changes in a real SEQUENCE OF (0x30). simple credentials are [0] IMPLICIT: 0x80 . """ import socket import ssl def L(n): if n < 128: return bytes([n]) b = b"" while n: b = bytes([n & 0xff]) + b n >>= 8 return bytes([0x80 | len(b)]) + b def E(t, c): return bytes([t]) + L(len(c)) + c def octet(b): return E(0x04, b) def integer(v): return E(0x02, v.to_bytes(max(1, (v.bit_length() + 7) // 8), "big")) def enum(v): return E(0x0a, v.to_bytes(1, "big")) def boolean(v): return E(0x01, b"\xff" if v else b"\x00") def tlv(buf, off): """return (tag, content, next_off)""" t = buf[off] l1 = buf[off + 1] if l1 & 0x80: n = l1 & 0x7f ln = int.from_bytes(buf[off + 2:off + 2 + n], "big") cs = off + 2 + n else: ln = l1 cs = off + 2 return t, buf[cs:cs + ln], cs + ln def filter_present(attr): return E(0x87, attr.encode()) def filter_eq(attr, value): return E(0xa3, E(0x30, octet(attr.encode()) + E(0x31, octet(value.encode())))) class LdapRaw(object): RESULT = {0: "success", 1: "operationsError", 2: "protocolError", 4: "sizeLimitExceeded", 7: "authMethodNotSupported", 10: "referral", 11: "adminLimitExceeded", 14: "saslBindInProgress", 16: "noSuchAttribute", 17: "undefinedAttributeType", 19: "constraintViolation", 20: "attributeOrValueExists", 21: "invalidAttributeSyntax", 32: "noSuchObject", 34: "invalidDNSyntax", 35: "objectClassViolation", 49: "invalidCredentials", 50: "insufficientAccessRights", 51: "busy", 53: "unwillingToPerform", 64: "namingViolation", 68: "entryAlreadyExists", 69: "objectClassModsProhibited", 71: "affectsMultipleDSAs", 80: "other"} def __init__(self, host, port=389, timeout=10, tls=False): self.sk = socket.create_connection((host, port), timeout=timeout) self.sk.settimeout(timeout) if tls: ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE self.sk = ctx.wrap_socket(self.sk, server_hostname=None) self.mid = 0 def close(self): try: self.sk.close() except OSError: pass def _rx(self, n): d = b"" while len(d) < n: x = self.sk.recv(n - len(d)) if not x: raise EOFError d += x return d def read_msg(self): self._rx(1) l1 = self._rx(1)[0] if l1 & 0x80: n = l1 & 0x7f length = int.from_bytes(self._rx(n), "big") else: length = l1 return self._rx(length) def send(self, op): self.mid += 1 self.sk.sendall(E(0x30, integer(self.mid) + op)) @staticmethod def _result(body): """Parse the COMPONENTS OF LDAPResult at the start of `body`. Returns (resultCode, matchedDN, diagnostic, offset_after).""" rc = None strs = [] o = 0 while o < len(body): t, c, n = tlv(body, o) if t == 0x0a and rc is None: rc = int.from_bytes(c, "big") o = n elif t == 0x04 and len(strs) < 2: strs.append(c) # matchedDN, then diagnosticMessage o = n else: break # first element after LDAPResult: leave it for the caller return rc, (strs[0] if strs else b""), (strs[1] if len(strs) > 1 else b""), o def _parse_referral(self, c, expect): """c = LDAPMessage content. Returns (resultCode, diag, extra_by_tag).""" _, _, off = tlv(c, 0) t, body, _ = tlv(c, off) if t != expect: raise ValueError("expected op tag 0x%02x, got 0x%02x" % (expect, t)) rc, _m, diag, o = self._result(body) extra = {} while o < len(body): tt, cc, o = tlv(body, o) extra[tt] = cc return rc, diag.decode("utf-8", "replace"), extra # ---- bind ------------------------------------------------------------- def sasl_bind(self, mech, creds=None): """One SASL bind step. creds=None omits the credentials field.""" inner = octet(mech) + (octet(creds) if creds is not None else b"") self.send(E(0x60, integer(3) + octet(b"") + E(0xa3, inner))) rc, diag, extra = self._parse_referral(self.read_msg(), 0x61) return rc, diag, extra.get(0x87) # serverSaslCreds [7] def simple_bind(self, dn, password): self.send(E(0x60, integer(3) + octet(dn.encode()) + E(0x80, password.encode()))) rc, diag, _ = self._parse_referral(self.read_msg(), 0x61) return rc, diag def unbind(self): try: self.send(E(0x42, b"")) except OSError: pass self.close() # ---- write ------------------------------------------------------------ def add(self, dn, attrs): av = b"".join(E(0x30, octet(k.encode()) + E(0x31, b"".join(octet(v.encode()) for v in vs))) for k, vs in attrs) self.send(E(0x68, octet(dn.encode()) + E(0x30, av))) rc, diag, _ = self._parse_referral(self.read_msg(), 0x69) return rc, diag def modify_add(self, dn, attr, val): change = E(0x30, enum(0) + E(0x30, octet(attr.encode()) + E(0x31, octet(val.encode())))) self.send(E(0x66, octet(dn.encode()) + E(0x30, change))) rc, diag, _ = self._parse_referral(self.read_msg(), 0x67) return rc, diag def delete(self, dn): # DelRequest ::= [APPLICATION 10] LDAPDN -- IMPLICIT: 0x4a replaces the OCTET STRING tag self.send(E(0x4a, dn.encode())) rc, diag, _ = self._parse_referral(self.read_msg(), 0x6b) # DeleteResponse [APPLICATION 11] return rc, diag def modify_del(self, dn, attr, val): change = E(0x30, enum(1) + E(0x30, octet(attr.encode()) + E(0x31, octet(val.encode())))) self.send(E(0x66, octet(dn.encode()) + E(0x30, change))) rc, diag, _ = self._parse_referral(self.read_msg(), 0x67) return rc, diag # ---- read ------------------------------------------------------------- def search_sub(self, base, filt, scope=2, attrs=()): """Returns (entries, resultCode); entries = [(dn, {attr: [values]})].""" sel = b"".join(octet(a.encode()) for a in attrs) req = E(0x63, octet(base.encode()) + enum(scope) + enum(0) + integer(0) + integer(0) + boolean(False) + filt + E(0x30, sel)) self.send(req) entries = [] while True: c = self.read_msg() _, _, off = tlv(c, 0) t, body, _ = tlv(c, off) if t == 0x64: # SearchResultEntry o = 0 _, dn, o = tlv(body, o) _, attrs_seq, o = tlv(body, o) d = {} ao = 0 while ao < len(attrs_seq): _, a, ao = tlv(attrs_seq, ao) _, atype, x = tlv(a, 0) _, vals, _ = tlv(a, x) vo = 0 vv = [] while vo < len(vals): _, v, vo = tlv(vals, vo) vv.append(v.decode("utf-8", "replace")) d[atype.decode()] = vv entries.append((dn.decode("utf-8", "replace"), d)) elif t == 0x65: # SearchResultDone rc, _m, _d, _ = self._result(body) return entries, rc def compare(self, dn, attr, value): self.send(E(0x6e, octet(dn.encode()) + E(0x30, octet(attr.encode()) + octet(value.encode())))) c = self.read_msg() _, _, off = tlv(c, 0) t, body, _ = tlv(c, off) rc, _m, _d, _ = self._result(body) return t, rc # t: 0x6f CompareTrue, 0x70 CompareFalse def whoami(self): """RFC 4532. Returns (resultCode, authzId or None).""" oid = bytes.fromhex("060a2b06010401b373030414") # 2.16.840.1.113730.3.4.20 self.send(E(0x77, octet(oid))) c = self.read_msg() _, _, off = tlv(c, 0) t, body, _ = tlv(c, off) rc, _m, diag, o = self._result(body) val = None while o < len(body): tt, cc, o = tlv(body, o) if tt == 0x8b: val = cc return rc, (val.decode("utf-8", "replace") if val is not None else None), diag.decode("utf-8", "replace")