#!/usr/bin/env python3 """exe-ldap: a tiny read-only LDAP directory for OpenProject on exe.dev. OpenProject's header sign-in (OPENPROJECT_AUTH__SOURCE__SSO) takes the email from exe.dev's X-ExeDev-Email header, then looks the user up in an LDAP directory to create or update their account. This server is that directory: it answers a search for (mail=) with an entry for that email, so anyone exe.dev lets through gets an account. It never vouches for a password: every bind with a password is refused, so OpenProject's LDAP password sign-in can't be used to get in. Only anonymous binds (OpenProject's searches) succeed. Names come from the email (ana.lima@x -> Ana Lima), unless names.txt (mounted at NAMES_FILE) has a line "email First Last". Standard library only. Listens on 0.0.0.0:3890 inside its container, which publishes no port: only OpenProject's container reaches it. """ import asyncio import os import re PORT = int(os.environ.get("PORT", "3890")) BASE_DN = os.environ.get("BASE_DN", "ou=people,dc=exe,dc=dev") NAMES_FILE = os.environ.get("NAMES_FILE", "/data/names.txt") EMAIL = re.compile(r"^[^@\s,=+<>#;\\\"]+@[^@\s,=+<>#;\\\"]+\.[^@\s,=+<>#;\\\"]+$") # --- BER, just enough for LDAPv3 bind, search and unbind --------------- def read_tlv(buf, i): """Return (tag, value, next_index) for the element at buf[i].""" tag = buf[i] n = buf[i + 1] i += 2 if n & 0x80: k = n & 0x7F n = int.from_bytes(buf[i:i + k], "big") i += k return tag, buf[i:i + n], i + n def children(value): out, i = [], 0 while i < len(value): tag, v, i = read_tlv(value, i) out.append((tag, v)) return out def tlv(tag, value): n = len(value) if n < 0x80: head = bytes([n]) else: b = n.to_bytes((n.bit_length() + 7) // 8, "big") head = bytes([0x80 | len(b)]) + b return bytes([tag]) + head + value def integer(n): return tlv(0x02, n.to_bytes(max(1, (n.bit_length() + 8) // 8), "big", signed=True)) def octets(s): return tlv(0x04, s.encode() if isinstance(s, str) else s) def message(msg_id, op): return tlv(0x30, integer(msg_id) + op) def result(app_tag, code, text=""): return tlv(app_tag, tlv(0x0A, bytes([code])) + octets("") + octets(text)) # --- the directory ------------------------------------------------------ def equality_matches(filt): """Yield (attribute, value) for every equalityMatch inside a filter.""" tag, value = filt if tag in (0xA0, 0xA1, 0xA2): # and, or, not for child in children(value): yield from equality_matches(child) elif tag == 0xA3: # equalityMatch (_, attr), (_, val) = children(value)[:2] yield attr.decode(errors="replace").lower(), val.decode(errors="replace") def names_for(email): try: with open(NAMES_FILE) as f: for line in f: parts = line.split() if len(parts) >= 3 and parts[0].lower() == email: return parts[1], " ".join(parts[2:]) except OSError: pass local, domain = email.split("@", 1) words = [w.capitalize() for w in re.split(r"[._+-]+", local) if w] if len(words) >= 2: return words[0], " ".join(words[1:]) return (words or [local])[0], domain def entry_for(email): first, last = names_for(email) attrs = {"objectClass": ["inetOrgPerson"], "mail": [email], "uid": [email], "givenName": [first], "sn": [last], "cn": [f"{first} {last}"]} body = b"".join( tlv(0x30, octets(k) + tlv(0x31, b"".join(octets(v) for v in vs))) for k, vs in attrs.items()) return tlv(0x64, octets(f"mail={email},{BASE_DN}") + tlv(0x30, body)) def handle(msg_id, tag, value): """Return the response messages for one request.""" if tag == 0x60: # BindRequest: version, name, simple password [0] parts = children(value) password = parts[2][1] if len(parts) > 2 and parts[2][0] == 0x80 else b"x" if password == b"": return [message(msg_id, result(0x61, 0))] # anonymous: ok return [message(msg_id, result(0x61, 49, "exe-ldap accepts no passwords"))] if tag == 0x63: # SearchRequest parts = children(value) base = parts[0][1].decode(errors="replace").lower() out = [] if base.endswith(BASE_DN.lower()): for attr, val in equality_matches(parts[6]): email = val.strip().lower() if attr in ("mail", "uid") and EMAIL.match(email): out.append(message(msg_id, entry_for(email))) break return out + [message(msg_id, result(0x65, 0))] if tag == 0x77: # ExtendedRequest (StartTLS etc.): not supported return [message(msg_id, result(0x78, 2, "not supported"))] return [] async def serve(reader, writer): buf = b"" try: while True: data = await reader.read(65536) if not data: break buf += data while len(buf) >= 2: try: _, msg, end = read_tlv(buf, 0) except IndexError: break if end > len(buf): break buf = buf[end:] parts = children(msg) msg_id = int.from_bytes(parts[0][1], "big") tag, value = parts[1] if tag == 0x42: # UnbindRequest return for response in handle(msg_id, tag, value): writer.write(response) await writer.drain() except Exception as e: # malformed input: drop the connection print("exe-ldap: dropped connection:", repr(e), flush=True) finally: writer.close() async def main(): server = await asyncio.start_server(serve, "0.0.0.0", PORT) print(f"exe-ldap listening on {PORT}, base {BASE_DN}", flush=True) async with server: await server.serve_forever() if __name__ == "__main__": asyncio.run(main())