add ldap debug
This commit is contained in:
parent
b591cf3095
commit
c7dcc2efc4
@ -4,6 +4,7 @@ resources:
|
|||||||
- ../base
|
- ../base
|
||||||
- keycloak-krb5.yaml
|
- keycloak-krb5.yaml
|
||||||
- uralkali-ca.yaml
|
- uralkali-ca.yaml
|
||||||
|
- ldap-debug/pod.yaml
|
||||||
patches:
|
patches:
|
||||||
- path: camunda.yaml
|
- path: camunda.yaml
|
||||||
secretGenerator:
|
secretGenerator:
|
||||||
|
|||||||
18
infrastructure/camunda/uralkal/ldap-debug/Dockerfile
Normal file
18
infrastructure/camunda/uralkal/ldap-debug/Dockerfile
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
FROM python:3.14-slim-trixie
|
||||||
|
|
||||||
|
# krb5-user: kinit/klist для проверки keytab; ldap-utils: ldapsearch для ручной отладки;
|
||||||
|
# gcc + libkrb5-dev нужны только для сборки python-gssapi
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends \
|
||||||
|
krb5-user ldap-utils openssl ca-certificates \
|
||||||
|
gcc libkrb5-dev vim \
|
||||||
|
&& pip install --no-cache-dir ldap3 gssapi \
|
||||||
|
&& apt-get purge -y gcc libkrb5-dev \
|
||||||
|
&& apt-get autoremove -y \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY ldap_debug.py /app/ldap_debug.py
|
||||||
|
|
||||||
|
# Под держим живым, скрипт запускаем через kubectl exec
|
||||||
|
ENTRYPOINT ["sleep", "infinity"]
|
||||||
326
infrastructure/camunda/uralkal/ldap-debug/ldap_debug.py
Normal file
326
infrastructure/camunda/uralkal/ldap-debug/ldap_debug.py
Normal file
@ -0,0 +1,326 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""LDAP/AD connection debugger.
|
||||||
|
|
||||||
|
Runs a sequence of checks against an AD/LDAP server the same way Keycloak
|
||||||
|
LDAP federation would use it: DNS -> TCP -> TLS -> bind -> search -> Kerberos.
|
||||||
|
|
||||||
|
Configuration is via environment variables (sensible defaults for uralkali):
|
||||||
|
|
||||||
|
LDAP_HOST default PERM-GL-DC3.local.uralkali.com
|
||||||
|
LDAP_PORTS default "389,636,88,464" (88/464 = Kerberos KDC/passwd)
|
||||||
|
CA_FILE default /opt/uralkali-ca/ber-ca1.crt
|
||||||
|
BASE_DN default DC=local,DC=uralkali,DC=com
|
||||||
|
BIND_DN e.g. svc-keycloak@local.uralkali.com or full DN (optional)
|
||||||
|
BIND_PASSWORD password for simple bind (optional)
|
||||||
|
SEARCH_FILTER default (&(objectClass=user)(sAMAccountName=*))
|
||||||
|
GROUP_DN DN группы: вывести все атрибуты всех её пользователей
|
||||||
|
NESTED "1" — учитывать вложенные группы (AD chain matching rule)
|
||||||
|
KRB5_PRINCIPAL e.g. svc-keycloak@LOCAL.URALKALI.COM (optional)
|
||||||
|
KRB5_KEYTAB path to keytab, e.g. /opt/keytab/sarex.keytab (optional)
|
||||||
|
TIMEOUT seconds per network op, default 10
|
||||||
|
|
||||||
|
Exit code 0 if all enabled checks pass, 1 otherwise.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
HOST = os.environ.get("LDAP_HOST", "PERM-GL-DC3.local.uralkali.com")
|
||||||
|
PORTS = [int(p) for p in os.environ.get("LDAP_PORTS", "389,636,88,464").split(",")]
|
||||||
|
CA_FILE = os.environ.get("CA_FILE", "/opt/uralkali-ca/ber-ca1.crt")
|
||||||
|
BASE_DN = os.environ.get("BASE_DN", "DC=local,DC=uralkali,DC=com")
|
||||||
|
BIND_DN = os.environ.get("BIND_DN", "")
|
||||||
|
BIND_PASSWORD = os.environ.get("BIND_PASSWORD", "")
|
||||||
|
SEARCH_FILTER = os.environ.get("SEARCH_FILTER", "(&(objectClass=user)(sAMAccountName=*))")
|
||||||
|
GROUP_DN = os.environ.get("GROUP_DN", "")
|
||||||
|
NESTED = os.environ.get("NESTED", "") == "1"
|
||||||
|
KRB5_PRINCIPAL = os.environ.get("KRB5_PRINCIPAL", "")
|
||||||
|
KRB5_KEYTAB = os.environ.get("KRB5_KEYTAB", "")
|
||||||
|
TIMEOUT = int(os.environ.get("TIMEOUT", "10"))
|
||||||
|
|
||||||
|
results = []
|
||||||
|
|
||||||
|
|
||||||
|
def step(name):
|
||||||
|
print(f"\n=== {name} " + "=" * max(0, 60 - len(name)))
|
||||||
|
|
||||||
|
|
||||||
|
def ok(msg):
|
||||||
|
print(f"[ OK ] {msg}")
|
||||||
|
results.append((True, msg))
|
||||||
|
|
||||||
|
|
||||||
|
def fail(msg, exc=None):
|
||||||
|
print(f"[FAIL] {msg}")
|
||||||
|
if exc is not None:
|
||||||
|
print("".join(traceback.format_exception_only(type(exc), exc)).strip())
|
||||||
|
results.append((False, msg))
|
||||||
|
|
||||||
|
|
||||||
|
def skip(msg):
|
||||||
|
print(f"[SKIP] {msg}")
|
||||||
|
|
||||||
|
|
||||||
|
def check_dns():
|
||||||
|
step(f"DNS resolve {HOST}")
|
||||||
|
try:
|
||||||
|
infos = socket.getaddrinfo(HOST, None, socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
addrs = sorted({i[4][0] for i in infos})
|
||||||
|
ok(f"{HOST} -> {', '.join(addrs)}")
|
||||||
|
return addrs
|
||||||
|
except OSError as e:
|
||||||
|
fail(f"DNS resolution failed for {HOST}", e)
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def check_tcp(port):
|
||||||
|
try:
|
||||||
|
with socket.create_connection((HOST, port), timeout=TIMEOUT):
|
||||||
|
ok(f"TCP {HOST}:{port} connect")
|
||||||
|
return True
|
||||||
|
except OSError as e:
|
||||||
|
fail(f"TCP {HOST}:{port} connect", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def make_ctx(verify=True):
|
||||||
|
ctx = ssl.create_default_context(cafile=CA_FILE if verify else None)
|
||||||
|
if not verify:
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def check_tls(port):
|
||||||
|
step(f"TLS handshake on {HOST}:{port} (CA: {CA_FILE})")
|
||||||
|
if not os.path.exists(CA_FILE):
|
||||||
|
fail(f"CA file not found: {CA_FILE}")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
with socket.create_connection((HOST, port), timeout=TIMEOUT) as raw:
|
||||||
|
with make_ctx().wrap_socket(raw, server_hostname=HOST) as tls:
|
||||||
|
cert = tls.getpeercert()
|
||||||
|
subj = dict(x[0] for x in cert.get("subject", []))
|
||||||
|
iss = dict(x[0] for x in cert.get("issuer", []))
|
||||||
|
ok(f"TLS {port}: {tls.version()}, cipher {tls.cipher()[0]}")
|
||||||
|
print(f" subject: {subj}")
|
||||||
|
print(f" issuer : {iss}")
|
||||||
|
print(f" valid : {cert.get('notBefore')} .. {cert.get('notAfter')}")
|
||||||
|
san = cert.get("subjectAltName", [])
|
||||||
|
if san:
|
||||||
|
print(f" SAN : {san}")
|
||||||
|
except ssl.SSLCertVerificationError as e:
|
||||||
|
fail(f"TLS {port}: certificate verification failed (chain/hostname)", e)
|
||||||
|
except (ssl.SSLError, OSError) as e:
|
||||||
|
fail(f"TLS {port}: handshake failed", e)
|
||||||
|
|
||||||
|
|
||||||
|
def ldap_server(port, use_ssl):
|
||||||
|
from ldap3 import Server, Tls
|
||||||
|
|
||||||
|
tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=CA_FILE) if (use_ssl or port == 636) else None
|
||||||
|
return Server(
|
||||||
|
HOST, port=port, use_ssl=use_ssl or port == 636,
|
||||||
|
get_info="ALL", connect_timeout=TIMEOUT, tls=tls,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def check_ldap_anonymous(port, use_ssl=False):
|
||||||
|
from ldap3 import Connection
|
||||||
|
|
||||||
|
step(f"LDAP anonymous bind + RootDSE on port {port}")
|
||||||
|
try:
|
||||||
|
conn = Connection(ldap_server(port, use_ssl), receive_timeout=TIMEOUT)
|
||||||
|
if not conn.bind():
|
||||||
|
fail(f"anonymous bind on {port}", None)
|
||||||
|
print(f" result: {conn.result}")
|
||||||
|
return None
|
||||||
|
ok(f"anonymous bind on {port}")
|
||||||
|
if conn.server.info and conn.server.info.other:
|
||||||
|
for k in ("defaultNamingContext", "dnsHostName", "serverName"):
|
||||||
|
v = conn.server.info.other.get(k)
|
||||||
|
if v:
|
||||||
|
print(f" {k}: {v}")
|
||||||
|
return conn
|
||||||
|
except Exception as e: # noqa: BLE001 - debug tool, report everything
|
||||||
|
fail(f"LDAP on {port}", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def check_simple_bind(port, use_ssl=False):
|
||||||
|
from ldap3 import Connection
|
||||||
|
|
||||||
|
step(f"LDAP simple bind as {BIND_DN} on port {port}")
|
||||||
|
try:
|
||||||
|
conn = Connection(
|
||||||
|
ldap_server(port, use_ssl), user=BIND_DN, password=BIND_PASSWORD,
|
||||||
|
receive_timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if not conn.bind():
|
||||||
|
fail(f"simple bind on {port}: {conn.result}")
|
||||||
|
return None
|
||||||
|
ok(f"simple bind on {port}")
|
||||||
|
conn.extend.standard.who_am_i() and print(f" whoami: {conn.extend.standard.who_am_i()}")
|
||||||
|
return conn
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
fail(f"simple bind on {port}", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def check_search(conn, label):
|
||||||
|
step(f"Search: base={BASE_DN} filter={SEARCH_FILTER} ({label})")
|
||||||
|
try:
|
||||||
|
ok_flag = conn.search(
|
||||||
|
BASE_DN, SEARCH_FILTER, size_limit=5,
|
||||||
|
attributes=["sAMAccountName", "displayName", "memberOf"],
|
||||||
|
)
|
||||||
|
if not ok_flag:
|
||||||
|
fail(f"search failed: {conn.result}")
|
||||||
|
return
|
||||||
|
ok(f"search returned {len(conn.entries)} entries (limit 5)")
|
||||||
|
for entry in conn.entries:
|
||||||
|
print(f" {entry.entry_dn}")
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
fail("search", e)
|
||||||
|
|
||||||
|
|
||||||
|
def dump_entry(entry):
|
||||||
|
print(f"\n--- {entry.entry_dn} " + "-" * max(0, 60 - len(entry.entry_dn)))
|
||||||
|
for attr in sorted(entry.entry_attributes, key=str.lower):
|
||||||
|
values = entry[attr].values
|
||||||
|
rendered = []
|
||||||
|
for v in values:
|
||||||
|
if isinstance(v, bytes):
|
||||||
|
try:
|
||||||
|
rendered.append(v.decode("utf-8"))
|
||||||
|
except UnicodeDecodeError:
|
||||||
|
rendered.append(f"0x{v.hex()}")
|
||||||
|
else:
|
||||||
|
rendered.append(str(v))
|
||||||
|
print(f" {attr}: {rendered if len(rendered) > 1 else rendered[0]}")
|
||||||
|
|
||||||
|
|
||||||
|
def check_group_members(conn, label):
|
||||||
|
from ldap3 import SUBTREE
|
||||||
|
|
||||||
|
step(f"Group members: {GROUP_DN} nested={NESTED} ({label})")
|
||||||
|
try:
|
||||||
|
if NESTED:
|
||||||
|
# AD matching rule IN_CHAIN: сразу все пользователи с учётом вложенности
|
||||||
|
found = conn.search(
|
||||||
|
BASE_DN,
|
||||||
|
f"(&(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:={GROUP_DN}))",
|
||||||
|
search_scope=SUBTREE, attributes=["*", "+"],
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
found = conn.search(GROUP_DN, "(objectClass=*)", attributes=["member"])
|
||||||
|
if not found or not conn.entries:
|
||||||
|
fail(f"group not found or unreadable: {conn.result}")
|
||||||
|
return
|
||||||
|
group = conn.entries[0]
|
||||||
|
members = group["member"].values if "member" in group else []
|
||||||
|
ok(f"group has {len(members)} direct members")
|
||||||
|
for dn in members:
|
||||||
|
if conn.search(dn, "(objectClass=*)", attributes=["*", "+"]) and conn.entries:
|
||||||
|
dump_entry(conn.entries[0])
|
||||||
|
else:
|
||||||
|
print(f"\n--- {dn} --- not a readable user entry: {conn.result}")
|
||||||
|
return
|
||||||
|
if not found:
|
||||||
|
fail(f"search failed: {conn.result}")
|
||||||
|
return
|
||||||
|
ok(f"found {len(conn.entries)} user entries")
|
||||||
|
for entry in conn.entries:
|
||||||
|
dump_entry(entry)
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
fail("group members", e)
|
||||||
|
|
||||||
|
|
||||||
|
def check_kerberos():
|
||||||
|
step(f"Kerberos kinit {KRB5_PRINCIPAL} with {KRB5_KEYTAB}")
|
||||||
|
if not os.path.exists(KRB5_KEYTAB):
|
||||||
|
fail(f"keytab not found: {KRB5_KEYTAB}")
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
["kinit", "-k", "-t", KRB5_KEYTAB, KRB5_PRINCIPAL],
|
||||||
|
capture_output=True, text=True, timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if proc.returncode != 0:
|
||||||
|
fail(f"kinit failed: {proc.stderr.strip()}")
|
||||||
|
return
|
||||||
|
ok("kinit")
|
||||||
|
print(subprocess.run(["klist"], capture_output=True, text=True).stdout)
|
||||||
|
except FileNotFoundError:
|
||||||
|
skip("kinit not installed in image")
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
fail("kinit", e)
|
||||||
|
|
||||||
|
step("LDAP SASL GSSAPI bind on port 389")
|
||||||
|
try:
|
||||||
|
from ldap3 import Connection, SASL, GSSAPI
|
||||||
|
|
||||||
|
conn = Connection(
|
||||||
|
ldap_server(389, False), authentication=SASL, sasl_mechanism=GSSAPI,
|
||||||
|
receive_timeout=TIMEOUT,
|
||||||
|
)
|
||||||
|
if not conn.bind():
|
||||||
|
fail(f"GSSAPI bind: {conn.result}")
|
||||||
|
return
|
||||||
|
ok("GSSAPI bind")
|
||||||
|
check_search(conn, "GSSAPI")
|
||||||
|
if GROUP_DN:
|
||||||
|
check_group_members(conn, "GSSAPI")
|
||||||
|
conn.unbind()
|
||||||
|
except ImportError:
|
||||||
|
skip("python gssapi module not installed")
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
fail("GSSAPI bind", e)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print(f"LDAP debug: host={HOST} base={BASE_DN} ca={CA_FILE}")
|
||||||
|
|
||||||
|
if not check_dns():
|
||||||
|
summary(1)
|
||||||
|
|
||||||
|
for port in PORTS:
|
||||||
|
check_tcp(port)
|
||||||
|
|
||||||
|
if 636 in PORTS:
|
||||||
|
check_tls(636)
|
||||||
|
|
||||||
|
conn = check_ldap_anonymous(389) or check_ldap_anonymous(636)
|
||||||
|
|
||||||
|
if BIND_DN and BIND_PASSWORD:
|
||||||
|
bound = check_simple_bind(389) or check_simple_bind(636)
|
||||||
|
if bound:
|
||||||
|
check_search(bound, "simple bind")
|
||||||
|
if GROUP_DN:
|
||||||
|
check_group_members(bound, "simple bind")
|
||||||
|
bound.unbind()
|
||||||
|
elif conn:
|
||||||
|
check_search(conn, "anonymous")
|
||||||
|
|
||||||
|
if KRB5_PRINCIPAL and KRB5_KEYTAB:
|
||||||
|
check_kerberos()
|
||||||
|
|
||||||
|
summary()
|
||||||
|
|
||||||
|
|
||||||
|
def summary(code=None):
|
||||||
|
step("SUMMARY")
|
||||||
|
for passed, msg in results:
|
||||||
|
print(f" {'PASS' if passed else 'FAIL'} {msg}")
|
||||||
|
if code is None:
|
||||||
|
code = 0 if all(p for p, _ in results) and results else 1
|
||||||
|
print(f"\nexit code: {code}")
|
||||||
|
sys.exit(code)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
68
infrastructure/camunda/uralkal/ldap-debug/pod.yaml
Normal file
68
infrastructure/camunda/uralkal/ldap-debug/pod.yaml
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Pod
|
||||||
|
metadata:
|
||||||
|
name: ldap-debug
|
||||||
|
namespace: camunda
|
||||||
|
labels:
|
||||||
|
app: ldap-debug
|
||||||
|
spec:
|
||||||
|
restartPolicy: Never
|
||||||
|
# то же размещение, что у camunda/keycloak, чтобы сетевые проверки были честными
|
||||||
|
nodeSelector:
|
||||||
|
dedicated: processing
|
||||||
|
tolerations:
|
||||||
|
- key: dedicated
|
||||||
|
operator: Equal
|
||||||
|
value: processing
|
||||||
|
effect: NoSchedule
|
||||||
|
imagePullSecrets:
|
||||||
|
- name: regcred
|
||||||
|
containers:
|
||||||
|
- name: ldap-debug
|
||||||
|
# TODO: заменить на собранный и запушенный образ
|
||||||
|
image: cr.yandex/crp3ccidau046kdj8g9q/contour/camunda/ldap-debug:latest
|
||||||
|
env:
|
||||||
|
- name: LDAP_HOST
|
||||||
|
value: PERM-GL-DC3.local.uralkali.com
|
||||||
|
- name: CA_FILE
|
||||||
|
value: /opt/uralkali-ca/ber-ca1.crt
|
||||||
|
- name: BASE_DN
|
||||||
|
value: DC=local,DC=uralkali,DC=com
|
||||||
|
# для проверки simple bind (опционально):
|
||||||
|
# - name: BIND_DN
|
||||||
|
# value: svc-account@local.uralkali.com
|
||||||
|
# - name: BIND_PASSWORD
|
||||||
|
# valueFrom:
|
||||||
|
# secretKeyRef:
|
||||||
|
# name: ldap-debug-bind
|
||||||
|
# key: password
|
||||||
|
# вывод всех атрибутов пользователей группы (опционально):
|
||||||
|
# - name: GROUP_DN
|
||||||
|
# value: CN=some-group,OU=Groups,DC=local,DC=uralkali,DC=com
|
||||||
|
# - name: NESTED
|
||||||
|
# value: "1" # учитывать вложенные группы
|
||||||
|
# для проверки kerberos/gssapi (опционально):
|
||||||
|
# - name: KRB5_PRINCIPAL
|
||||||
|
# value: HTTP/camunda-keycloak.sarex.local.uralkali.com@LOCAL.URALKALI.COM
|
||||||
|
volumeMounts:
|
||||||
|
- name: uralkali-ca
|
||||||
|
mountPath: /opt/uralkali-ca
|
||||||
|
readOnly: true
|
||||||
|
- name: krb5
|
||||||
|
mountPath: /etc/krb5.conf
|
||||||
|
subPath: krb5.conf
|
||||||
|
readOnly: true
|
||||||
|
- name: keytab
|
||||||
|
mountPath: /opt/keytab
|
||||||
|
readOnly: true
|
||||||
|
volumes:
|
||||||
|
- name: uralkali-ca
|
||||||
|
configMap:
|
||||||
|
name: uralkali-ca
|
||||||
|
- name: krb5
|
||||||
|
configMap:
|
||||||
|
name: keycloak-krb5
|
||||||
|
- name: keytab
|
||||||
|
secret:
|
||||||
|
secretName: keycloak-keytab
|
||||||
|
optional: true
|
||||||
Loading…
Reference in New Issue
Block a user