id: ldap-stale-account-lockout-guard
namespace: company.team
description: |
Find LDAP accounts whose shadowExpire date has passed but that still carry no lock attribute, then lock each one and re-search to prove the lock landed.
inputs:
- id: dry_run
type: BOOL
defaults: true
description: When true the flow only reports expired unlocked accounts and never
writes to the directory.
- id: auto_remediate
type: BOOL
defaults: false
description: When true (and dry_run is false) the flow builds an LDIF modify and
locks the accounts after approval.
- id: ldap_host
type: STRING
defaults: ldap.example.com
description: Hostname of the LDAP server.
- id: ldap_port
type: INT
defaults: 389
description: LDAP port.
- id: bind_dn
type: STRING
defaults: cn=admin,dc=example,dc=org
description: Bind DN with permission to search and modify accounts.
- id: base_dn
type: STRING
defaults: dc=example,dc=org
description: Base DN to search under.
- id: ldap_password
type: STRING
defaults: "{{ secret('LDAP_PASSWORD') }}"
description: Bind password. Defaults to the LDAP_PASSWORD secret.
- id: lock_attribute
type: STRING
defaults: pwdAccountLockedTime
description: Attribute that marks an account as locked. pwdAccountLockedTime for
the OpenLDAP ppolicy overlay, nsAccountLock for 389 Directory Server.
- id: lock_value
type: STRING
defaults: 000001010000Z
description: Value written to the lock attribute. 000001010000Z is the ppolicy
permanent-lock sentinel.
- id: inactive_grace_days
type: INT
defaults: 0
description: Only lock accounts whose expiry passed at least this many days ago.
tasks:
- id: detect
type: io.kestra.plugin.ldap.Search
description: Search for shadowAccount entries that have a shadowExpire value and
no lock attribute. The date threshold is applied in the next step because
shadowExpire has no ordering rule for a server-side range filter.
hostname: "{{ inputs.ldap_host }}"
port: "{{ inputs.ldap_port }}"
userDn: "{{ inputs.bind_dn }}"
password: "{{ inputs.ldap_password }}"
baseDn: "{{ inputs.base_dn }}"
filter: "(&(objectClass=shadowAccount)(shadowExpire=*)(!({{
inputs.lock_attribute }}=*)))"
attributes:
- uid
- shadowExpire
- id: parse_detect
type: io.kestra.plugin.scripts.python.Script
description: Read the candidate entries, keep the ones whose shadowExpire is a
day in the past (minus the grace window) then build an LDIF modify that
locks each target.
containerImage: python:3.12-slim
inputFiles:
candidates.ldif: "{{ outputs.detect.uri }}"
outputFiles:
- remediate.ldif
script: |
import time, json, re, base64
GRACE = {{ inputs.inactive_grace_days }}
LOCK_ATTR = "{{ inputs.lock_attribute }}"
LOCK_VALUE = "{{ inputs.lock_value }}"
today = int(time.time() // 86400)
cutoff = today - GRACE
raw = open("candidates.ldif", "r", encoding="utf-8", errors="replace").read()
unfolded = re.sub(r"\n[ ]", "", raw)
targets = []
dn = None
sx = None
def flush(dn, sx):
if dn is None or sx is None:
return
try:
v = int(sx)
except ValueError:
return
if 1 <= v <= cutoff:
targets.append(dn)
for line in unfolded.splitlines():
if not line.strip():
flush(dn, sx)
dn, sx = None, None
continue
if line.startswith("#") or ":" not in line:
continue
key, _, val = line.partition(":")
key = key.strip().lower()
val = val.lstrip()
if val.startswith(":"):
val = base64.b64decode(val[1:].strip()).decode("utf-8", "replace")
if key == "dn":
dn = val
elif key == "shadowexpire":
sx = val
flush(dn, sx)
lines = []
for d in targets:
lines.append("dn: " + d)
lines.append("changetype: modify")
lines.append("replace: " + LOCK_ATTR)
lines.append(LOCK_ATTR + ": " + LOCK_VALUE)
lines.append("-")
lines.append("")
open("remediate.ldif", "w", encoding="utf-8").write("\n".join(lines) + "\n")
count = len(targets)
print("DETECT today={} cutoff={} grace={} candidates_parsed targets={}".format(today, cutoff, GRACE, count))
for d in targets:
print("TARGET " + d)
out = {"count": count, "has_targets": "yes" if count else "no", "target_dns": ", ".join(targets)}
print("::" + json.dumps({"outputs": out}) + "::")
- id: findings_alert
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.parse_detect.vars.has_targets == 'yes' }}"
then:
- id: log_findings
type: io.kestra.plugin.core.log.Log
message: "Expired unlocked accounts: {{ outputs.parse_detect.vars.count }}. DNs:
{{ outputs.parse_detect.vars.target_dns }}."
- id: notify_findings
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Post the detection result to Slack so an operator sees stale
accounts even on a read-only run.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "LDAP stale account guard found {{ outputs.parse_detect.vars.count }} expired account(s) still unlocked under {{ inputs.base_dn }}. DNs: {{ outputs.parse_detect.vars.target_dns }}. dry_run={{ inputs.dry_run }} auto_remediate={{ inputs.auto_remediate }}."
}
- id: remediate_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ inputs.auto_remediate and not inputs.dry_run and
outputs.parse_detect.vars.has_targets == 'yes' }}"
then:
- id: approval_hold
type: io.kestra.plugin.core.flow.Pause
description: >-
Locking accounts can log people out, so the write waits for a human.
Resume with approved set to true to apply the lock. Set it false to
cancel.
onResume:
- id: approved
type: BOOL
defaults: false
description: Set true to lock the accounts listed by the detection step.
- id: apply_gate
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.approval_hold.onResume.approved ?? false }}"
then:
- id: remediate
type: io.kestra.plugin.ldap.Modify
description: Apply the LDIF modify that sets the lock attribute on every target
DN. The plugin logs a rejected record and keeps going, so the
re-search below is the real gate.
hostname: "{{ inputs.ldap_host }}"
port: "{{ inputs.ldap_port }}"
userDn: "{{ inputs.bind_dn }}"
password: "{{ inputs.ldap_password }}"
inputs:
- "{{ outputs.parse_detect.outputFiles['remediate.ldif'] }}"
- id: verify
type: io.kestra.plugin.ldap.Search
description: Re-run the detection search after the modify.
hostname: "{{ inputs.ldap_host }}"
port: "{{ inputs.ldap_port }}"
userDn: "{{ inputs.bind_dn }}"
password: "{{ inputs.ldap_password }}"
baseDn: "{{ inputs.base_dn }}"
filter: "(&(objectClass=shadowAccount)(shadowExpire=*)(!({{
inputs.lock_attribute }}=*)))"
attributes:
- uid
- shadowExpire
- id: parse_verify
type: io.kestra.plugin.scripts.python.Script
description: Apply the same past-expiry test to the re-search output. Any
account still here is still unlocked.
containerImage: python:3.12-slim
inputFiles:
candidates.ldif: "{{ outputs.verify.uri }}"
outputFiles:
- remediate.ldif
script: |
import time, json, re, base64
GRACE = {{ inputs.inactive_grace_days }}
LOCK_ATTR = "{{ inputs.lock_attribute }}"
LOCK_VALUE = "{{ inputs.lock_value }}"
today = int(time.time() // 86400)
cutoff = today - GRACE
raw = open("candidates.ldif", "r", encoding="utf-8", errors="replace").read()
unfolded = re.sub(r"\n[ ]", "", raw)
targets = []
dn = None
sx = None
def flush(dn, sx):
if dn is None or sx is None:
return
try:
v = int(sx)
except ValueError:
return
if 1 <= v <= cutoff:
targets.append(dn)
for line in unfolded.splitlines():
if not line.strip():
flush(dn, sx)
dn, sx = None, None
continue
if line.startswith("#") or ":" not in line:
continue
key, _, val = line.partition(":")
key = key.strip().lower()
val = val.lstrip()
if val.startswith(":"):
val = base64.b64decode(val[1:].strip()).decode("utf-8", "replace")
if key == "dn":
dn = val
elif key == "shadowexpire":
sx = val
flush(dn, sx)
lines = []
for d in targets:
lines.append("dn: " + d)
lines.append("changetype: modify")
lines.append("replace: " + LOCK_ATTR)
lines.append(LOCK_ATTR + ": " + LOCK_VALUE)
lines.append("-")
lines.append("")
open("remediate.ldif", "w", encoding="utf-8").write("\n".join(lines) + "\n")
count = len(targets)
print("VERIFY today={} cutoff={} grace={} still_unlocked={}".format(today, cutoff, GRACE, count))
for d in targets:
print("STILL_UNLOCKED " + d)
out = {"count": count, "has_targets": "yes" if count else "no", "target_dns": ", ".join(targets)}
print("::" + json.dumps({"outputs": out}) + "::")
- id: assert_locked
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.parse_verify.vars.has_targets == 'yes' }}"
then:
- id: still_unlocked
type: io.kestra.plugin.core.execution.Fail
errorMessage: "Remediation did not lock every target. Still unlocked: {{
outputs.parse_verify.vars.target_dns }}."
triggers:
- id: daily_audit
type: io.kestra.plugin.core.trigger.Schedule
description: Daily audit. Disabled by default and pinned to safe mode so
enabling it never writes without a deliberate change.
cron: "0 6 * * *"
disabled: true
inputs:
dry_run: true
auto_remediate: false
errors:
- id: alert_on_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Alert on any failure, including a run that failed because an
account was still unlocked after remediation.
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "LDAP stale account lockout guard FAILED (execution {{ execution.id }}). Some expired accounts may still be unlocked. Check the directory and the run logs."
}