Compare commits
11
Commits
76b8a9417e
...
cf93e737aa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf93e737aa | ||
|
|
9f7a332fb6 | ||
|
|
781ca46713 | ||
|
|
7d0e8eb800 | ||
|
|
a49f2d1055 | ||
|
|
d672afe22c | ||
|
|
f34ddf31de | ||
|
|
8a3a3cefaa | ||
|
|
c294a8e2d3 | ||
|
|
896d38fd63 | ||
|
|
9a8469db6f |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
name: lint
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
shell:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: bash -n
|
||||
run: for f in *.sh; do bash -n "$f"; done
|
||||
- name: shellcheck
|
||||
run: |
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq shellcheck
|
||||
shellcheck --severity=warning *.sh
|
||||
|
||||
python:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
- name: Syntax-Check
|
||||
run: python -m py_compile create-deploy-user.py
|
||||
- name: ruff
|
||||
run: pip install -q ruff && ruff check create-deploy-user.py
|
||||
@@ -0,0 +1,4 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.claude/
|
||||
.codegraph/
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# check-sshd-ldap.sh <username> [server]
|
||||
#
|
||||
# Diagnose der Kette authentik-LDAP-Outpost → SSSD → NSS/PAM → sshd.
|
||||
set -uo pipefail
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
USER_NAME="${1:-}"
|
||||
SERVER="${2:-H1}"
|
||||
[[ -n "$USER_NAME" ]] || { echo "Verwendung: $(basename "$0") <username> [server]" >&2; exit 1; }
|
||||
|
||||
fail=0
|
||||
check() { # check "Beschreibung" befehl...
|
||||
local desc="$1"; shift
|
||||
if "$@" >/dev/null 2>&1; then printf '✅ %s\n' "$desc"; else printf '❌ %s\n' "$desc"; fail=1; fi
|
||||
}
|
||||
|
||||
check "sssd läuft" systemctl is-active --quiet sssd
|
||||
check "sssd.conf: Rechte 0600 root" test "$(stat -c '%a %u' /etc/sssd/sssd.conf)" = "600 0"
|
||||
check "sshd-Konfiguration gültig" sshd -t
|
||||
check "sshd: AuthorizedKeysCommand gesetzt" bash -c "sshd -T | grep -qi '^authorizedkeyscommand .*sss_ssh_authorizedkeys'"
|
||||
check "NSS: passwd enthält sss" bash -c "grep -Eq '^passwd:.*\bsss\b' /etc/nsswitch.conf"
|
||||
check "User '$USER_NAME' per NSS auflösbar" getent passwd "$USER_NAME"
|
||||
check "Gruppe server_${SERVER}_ssh_access" bash -c "id -nG '$USER_NAME' | tr ' ' '\n' | grep -qx 'server_${SERVER}_ssh_access'"
|
||||
check "Gruppe server_${SERVER}_docker_compose" bash -c "id -nG '$USER_NAME' | tr ' ' '\n' | grep -qx 'server_${SERVER}_docker_compose'"
|
||||
check "SSH-Keys-Abfrage funktioniert (Aufruf)" sss_ssh_authorizedkeys "$USER_NAME"
|
||||
|
||||
echo
|
||||
echo "── getent passwd $USER_NAME"; getent passwd "$USER_NAME" || true
|
||||
echo "── id $USER_NAME"; id "$USER_NAME" 2>&1 || true
|
||||
echo "── sssctl domain-status authentik"; sssctl domain-status authentik 2>&1 | head -n 15 || true
|
||||
|
||||
if [[ $fail -ne 0 ]]; then
|
||||
echo
|
||||
echo "Hinweis: Debug mit 'sssctl debug-level 6' und 'journalctl -u sssd -u ssh -f'."
|
||||
fi
|
||||
exit "$fail"
|
||||
Executable
+219
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env -S uv run --script
|
||||
# /// script
|
||||
# requires-python = ">=3.13"
|
||||
# dependencies = [
|
||||
# "authentik-client>=2026.8.5",
|
||||
# "requests>=2.34.2",
|
||||
# ]
|
||||
# ///
|
||||
"""Legt in authentik einen Deploy-User für ein Gitea-Repository an und hinterlegt
|
||||
die Zugangsdaten als Gitea-Actions-Secrets/-Variablen."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from getpass import getpass
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import authentik_client
|
||||
import requests
|
||||
from authentik_client.rest import ApiException
|
||||
|
||||
DEFAULT_AUTHENTIK_URL = "https://auth.share-fix.de/api/v3"
|
||||
DEFAULT_GITEA_URL = "https://git.share-fix.de"
|
||||
DEFAULT_SERVER = "H1"
|
||||
HOME_DIR_BASE = "/home"
|
||||
USERNAME_RE = re.compile(r"^[a-z_][a-z0-9_-]{0,31}$")
|
||||
|
||||
|
||||
# ── Gitea ────────────────────────────────────────────────────────────────────
|
||||
class Gitea:
|
||||
def __init__(self, base_url: str, token: str):
|
||||
self.base = base_url.rstrip("/") + "/api/v1"
|
||||
self.session = requests.Session()
|
||||
self.session.headers["Authorization"] = f"token {token}"
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
response = self.session.request(method, self.base + path, timeout=30, **kwargs)
|
||||
response.raise_for_status()
|
||||
return response
|
||||
|
||||
def get_repo(self, repo_path: str) -> dict:
|
||||
print(f"Retrieving repository {repo_path}")
|
||||
return self._request("GET", f"/repos/{repo_path}").json()
|
||||
|
||||
def set_secret(self, repo_path: str, key: str, value: str):
|
||||
print(f"Setting secret {key} for {repo_path}")
|
||||
self._request("PUT", f"/repos/{repo_path}/actions/secrets/{key}", json={"data": value})
|
||||
|
||||
def set_variable(self, repo_path: str, key: str, value: str):
|
||||
print(f"Setting variable {key} for {repo_path}")
|
||||
url = f"/repos/{repo_path}/actions/variables/{key}"
|
||||
try:
|
||||
self._request("PUT", url, json={"value": value})
|
||||
except requests.HTTPError as e:
|
||||
if e.response is None or e.response.status_code != 404:
|
||||
raise
|
||||
self._request("POST", url, json={"value": value})
|
||||
|
||||
|
||||
def normalize_repo_path(raw: str, gitea_url: str) -> str:
|
||||
"""Akzeptiert 'owner/repo', Web-URLs und Clone-URLs (mit/ohne .git)."""
|
||||
raw = raw.strip()
|
||||
if raw.startswith(("http://", "https://")):
|
||||
raw = urlparse(raw).path
|
||||
raw = raw.strip("/").removesuffix(".git")
|
||||
if raw.count("/") != 1:
|
||||
raise ValueError(f"Repository muss die Form 'owner/repo' haben, bekam: '{raw}'")
|
||||
return raw
|
||||
|
||||
|
||||
# ── authentik ────────────────────────────────────────────────────────────────
|
||||
def authentik_get_group_by_name(client: authentik_client.CoreApi, name: str):
|
||||
groups = client.core_groups_list(search=name)
|
||||
for group in groups.results or []:
|
||||
if group.name == name:
|
||||
print(f"{name} group found: uuid={group.pk}")
|
||||
return group
|
||||
raise RuntimeError(f"Gruppe '{name}' nicht gefunden")
|
||||
|
||||
|
||||
def authentik_create_user(client: authentik_client.CoreApi, username: str, home_directory: str, groups, repo_url: str) -> str:
|
||||
print(f"Creating user: {username}")
|
||||
users = client.core_users_list(username=username)
|
||||
if users.results:
|
||||
print(f"User {username} already exists")
|
||||
user = users.results[0]
|
||||
client.core_users_partial_update(
|
||||
id=user.pk,
|
||||
patched_user_request=authentik_client.PatchedUserRequest(
|
||||
attributes={**(user.attributes or {}), "notes": repo_url, "homeDirectory": home_directory}
|
||||
),
|
||||
)
|
||||
else:
|
||||
user = client.core_users_create(
|
||||
user_request=authentik_client.UserRequest(
|
||||
username=username,
|
||||
name=username,
|
||||
type=authentik_client.UserTypeEnum.SERVICE_ACCOUNT,
|
||||
is_active=True,
|
||||
path="goauthentik.io/service-accounts",
|
||||
attributes={
|
||||
"notes": repo_url,
|
||||
"homeDirectory": home_directory,
|
||||
"goauthentik.io/user/token-expires": False,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
print(f"Adding user {username} to groups: {', '.join(g.name for g in groups)}")
|
||||
for group in groups:
|
||||
client.core_groups_add_user_create(
|
||||
group_uuid=group.pk,
|
||||
user_account_request=authentik_client.UserAccountRequest(pk=user.pk),
|
||||
)
|
||||
|
||||
token_identifier = f"service-account-{username}-password"
|
||||
if client.core_tokens_list(identifier=token_identifier).results:
|
||||
print(f"Token {token_identifier} already exists")
|
||||
else:
|
||||
print(f"Creating token for user {username}")
|
||||
client.core_tokens_create(
|
||||
authentik_client.TokenRequest(
|
||||
identifier=token_identifier,
|
||||
user=user.pk,
|
||||
intent=authentik_client.IntentEnum.APP_PASSWORD,
|
||||
expiring=False,
|
||||
)
|
||||
)
|
||||
return client.core_tokens_view_key_retrieve(token_identifier).key
|
||||
|
||||
|
||||
# ── CLI ──────────────────────────────────────────────────────────────────────
|
||||
def parse_args() -> argparse.Namespace:
|
||||
p = argparse.ArgumentParser(description="Deploy-User für ein Gitea-Repository in authentik anlegen")
|
||||
p.add_argument("--server", default=DEFAULT_SERVER,
|
||||
help=f"Zielserver; bestimmt server_<SERVER>_ssh_access und server_<SERVER>_docker_compose (Standard: {DEFAULT_SERVER})")
|
||||
p.add_argument("--project-path", help="Gitea-Repository: 'owner/repo' oder URL")
|
||||
p.add_argument("--username", help="Username des Deploy-Users (Standard: deploy_<owner>_<repo>)")
|
||||
p.add_argument("--docker-group",
|
||||
help="Gruppe für Docker-Deploys (Standard: server_<SERVER>_docker_compose)")
|
||||
p.add_argument("--no-docker-group", action="store_true", help="Docker-Deploy-Gruppe nicht zuweisen")
|
||||
p.add_argument("--authentik-url", default=DEFAULT_AUTHENTIK_URL)
|
||||
p.add_argument("--authentik-token", default=os.environ.get("AUTHENTIK_TOKEN"),
|
||||
help="Bearer-Token für die authentik-API (oder Env AUTHENTIK_TOKEN)")
|
||||
p.add_argument("--gitea-url", default=DEFAULT_GITEA_URL)
|
||||
p.add_argument("--gitea-token", default=os.environ.get("GITEA_TOKEN"),
|
||||
help="Gitea-Access-Token mit Scope write:repository (oder Env GITEA_TOKEN)")
|
||||
p.add_argument("--dry-run", action="store_true", help="Nichts anlegen, nur ausgeben")
|
||||
p.add_argument("-y", "--yes", action="store_true", help="Bestätigungsabfrage überspringen")
|
||||
return p.parse_args()
|
||||
|
||||
|
||||
def make_username(repo_path: str) -> str:
|
||||
name = "deploy_" + re.sub(r"[^a-z0-9]+", "_", repo_path.lower()).strip("_")
|
||||
return name[:32].rstrip("_")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]+", args.server):
|
||||
sys.exit(f"Ungültiger Servername: '{args.server}'")
|
||||
if not args.dry_run and not args.authentik_token:
|
||||
print(f"Authentik-API-Token erstellen unter {args.authentik_url.split('/api')[0]}/if/user/#/settings;page=page-tokens")
|
||||
args.authentik_token = getpass("Enter authentik token: ")
|
||||
if not args.gitea_token:
|
||||
print(f"Gitea-Token erstellen unter {args.gitea_url}/user/settings/applications (Scope: write:repository)")
|
||||
args.gitea_token = getpass("Enter gitea token: ")
|
||||
if not args.project_path:
|
||||
args.project_path = input("Enter Gitea repository (owner/repo): ")
|
||||
|
||||
gitea = Gitea(args.gitea_url, args.gitea_token)
|
||||
repo_path = normalize_repo_path(args.project_path, args.gitea_url)
|
||||
repo = gitea.get_repo(repo_path)
|
||||
repo_path = repo["full_name"] # kanonische Schreibweise
|
||||
|
||||
username = args.username or make_username(repo_path)
|
||||
if not USERNAME_RE.match(username):
|
||||
sys.exit(f"Ungültiger Username '{username}' (erlaubt: ^[a-z_][a-z0-9_-]{{0,31}}$)")
|
||||
home_dir = f"{HOME_DIR_BASE}/{username}"
|
||||
|
||||
group_names = [f"server_{args.server}_ssh_access"]
|
||||
if not args.no_docker_group:
|
||||
group_names.append(args.docker_group or f"server_{args.server}_docker_compose")
|
||||
|
||||
print(f"\nRepository: {repo_path} (id {repo['id']})")
|
||||
print(f"Deploy-User: {username}")
|
||||
print(f"Home-Verz.: {home_dir}")
|
||||
print(f"Gruppen: {', '.join(group_names)}")
|
||||
print(f"Notes: {repo['html_url']}")
|
||||
print(f"Gitea-Secrets: deploy_user, deploy_pass")
|
||||
if args.dry_run:
|
||||
print("\n[dry-run] Es wurde nichts angelegt.")
|
||||
return 0
|
||||
if not args.yes and input("\nBestätigen? Fortfahren? [y/N] ").lower() != "y":
|
||||
return 0
|
||||
|
||||
configuration = authentik_client.Configuration(host=args.authentik_url, access_token=args.authentik_token)
|
||||
with authentik_client.ApiClient(configuration) as api_client:
|
||||
core_api = authentik_client.CoreApi(api_client)
|
||||
try:
|
||||
groups = [authentik_get_group_by_name(core_api, n) for n in group_names]
|
||||
key = authentik_create_user(core_api, username, home_dir, groups, repo["html_url"])
|
||||
except (ApiException, RuntimeError) as e:
|
||||
sys.exit(f"Fehler in authentik: {e}")
|
||||
|
||||
try:
|
||||
gitea.set_variable(repo_path, "deploy_user", username)
|
||||
gitea.set_secret(repo_path, "deploy_pass", key)
|
||||
except requests.RequestException as e:
|
||||
sys.exit(f"Fehler in Gitea: {e}")
|
||||
|
||||
print(f"\nFertig: {username} für {repo_path}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+114
-73
@@ -1,131 +1,172 @@
|
||||
#!/bin/bash
|
||||
# /usr/local/bin/app-deploy.sh
|
||||
set -euo pipefail
|
||||
#!/usr/bin/env bash
|
||||
# /usr/local/bin/docker-deploy.sh
|
||||
#
|
||||
# Docker-Compose-Wrapper für Funktions-User (gedacht für Aufruf per sudo).
|
||||
set -Eeuo pipefail
|
||||
IFS=$'\n\t'
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
DEPLOY_SUBDIR="its-deploy"
|
||||
DEPLOY_GROUP="server_APPS_docker_compose"
|
||||
ALLOWED_ACTIONS=("build" "up" "down" "restart" "logs" "pull" "deploy")
|
||||
readonly SCRIPT_NAME="$(basename "$0")"
|
||||
readonly DEPLOY_SUBDIR="deployment"
|
||||
readonly CONFIG_FILE="/etc/docker-deploy.conf"
|
||||
readonly ALLOWED_ACTIONS=(build up down restart logs pull deploy)
|
||||
|
||||
# ── Konfiguration ────────────────────────────────────────────────────────────
|
||||
# Optional: /etc/docker-deploy.conf (root-owned, nicht group/world-writable) mit
|
||||
# DEPLOY_SERVER=H1
|
||||
# Berechtigte Gruppe: server_${DEPLOY_SERVER}_docker_compose.
|
||||
# Bewusst keine Umgebungsvariable/kein Parameter: sudo-Aufrufer sollen die
|
||||
# Berechtigungsprüfung nicht selbst umstellen können.
|
||||
DEPLOY_SERVER="H1"
|
||||
if [[ -e "$CONFIG_FILE" ]]; then
|
||||
IFS=' ' read -r cfg_owner cfg_mode < <(stat -c '%u %a' "$CONFIG_FILE")
|
||||
if [[ "$cfg_owner" != 0 ]] || (( 8#$cfg_mode & 8#022 )); then
|
||||
echo "❌ $CONFIG_FILE muss root gehören und darf nicht group/world-writable sein" >&2
|
||||
exit 1
|
||||
fi
|
||||
DEPLOY_SERVER="$(sed -n 's/^DEPLOY_SERVER=//p' "$CONFIG_FILE" | tail -n1 | tr -d "\"' ")"
|
||||
fi
|
||||
[[ "$DEPLOY_SERVER" =~ ^[A-Za-z0-9_-]+$ ]] || { echo "❌ Ungültiger DEPLOY_SERVER: '$DEPLOY_SERVER'" >&2; exit 1; }
|
||||
readonly DEPLOY_GROUP="server_${DEPLOY_SERVER}_docker_compose"
|
||||
|
||||
# ── Hilfsfunktionen ──────────────────────────────────────────────────────────
|
||||
log() { printf '[%(%Y-%m-%d %H:%M:%S)T] %s\n' -1 "$*"; }
|
||||
die() { printf '❌ %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
usage() {
|
||||
echo "Verwendung: sudo $(basename "$0") <username> <action>"
|
||||
echo ""
|
||||
echo "Aktionen: ${ALLOWED_ACTIONS[*]}"
|
||||
echo ""
|
||||
echo "Beispiel: sudo $(basename "$0") func_123 deploy"
|
||||
cat >&2 <<EOF
|
||||
Verwendung: sudo ${SCRIPT_NAME} <username> <action> [--cache]
|
||||
|
||||
Aktionen: ${ALLOWED_ACTIONS[*]}
|
||||
Optionen: --cache Build mit Layer-Cache (Standard bei build/deploy: --no-cache)
|
||||
|
||||
Beispiel: sudo ${SCRIPT_NAME} func_123 deploy
|
||||
EOF
|
||||
exit 1
|
||||
}
|
||||
|
||||
is_allowed_action() {
|
||||
local value="$1"
|
||||
for item in "${ALLOWED_ACTIONS[@]}"; do
|
||||
[[ "$item" == "$value" ]] && return 0
|
||||
done
|
||||
in_array() {
|
||||
local needle="$1"; shift
|
||||
local item
|
||||
for item in "$@"; do [[ "$item" == "$needle" ]] && return 0; done
|
||||
return 1
|
||||
}
|
||||
|
||||
is_in_group() {
|
||||
local user="$1"
|
||||
local group="$2"
|
||||
id -nG "$user" 2>/dev/null | tr ' ' '\n' | grep -qx "$group"
|
||||
user_in_group() {
|
||||
local -a groups
|
||||
read -ra groups <<<"$(id -nG "$1")"
|
||||
in_array "$2" "${groups[@]}"
|
||||
}
|
||||
|
||||
log() {
|
||||
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
|
||||
on_error() {
|
||||
local rc=$? line=$1
|
||||
log "💥 Fehlgeschlagen (Exit $rc, Zeile $line): ${APP_USER:-?} ${ACTION:-?}" >&2
|
||||
exit "$rc"
|
||||
}
|
||||
trap 'on_error $LINENO' ERR
|
||||
|
||||
# ── Argument-Validierung ─────────────────────────────────────────────────────
|
||||
if [[ $# -lt 2 ]]; then
|
||||
usage
|
||||
fi
|
||||
# ── Argumente ────────────────────────────────────────────────────────────────
|
||||
[[ $# -ge 2 && $# -le 3 ]] || usage
|
||||
|
||||
APP_USER="$1"
|
||||
ACTION="$2"
|
||||
|
||||
if ! id "$APP_USER" &>/dev/null; then
|
||||
echo "❌ User '$APP_USER' existiert nicht auf diesem System"
|
||||
exit 1
|
||||
NO_CACHE=(--no-cache)
|
||||
USE_CACHE=false
|
||||
if [[ "${3:-}" == "--cache" ]]; then
|
||||
NO_CACHE=()
|
||||
USE_CACHE=true
|
||||
elif [[ -n "${3:-}" ]]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
if ! is_in_group "$APP_USER" "$DEPLOY_GROUP"; then
|
||||
echo "❌ User '$APP_USER' ist nicht in Gruppe '$DEPLOY_GROUP'"
|
||||
exit 1
|
||||
# ── Validierung ──────────────────────────────────────────────────────────────
|
||||
[[ $EUID -eq 0 ]] || die "Muss als root laufen (sudo)"
|
||||
[[ "$APP_USER" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || die "Ungültiger Username: '$APP_USER'"
|
||||
id "$APP_USER" &>/dev/null || die "User '$APP_USER' existiert nicht auf diesem System"
|
||||
user_in_group "$APP_USER" "$DEPLOY_GROUP" || die "User '$APP_USER' ist nicht in Gruppe '$DEPLOY_GROUP'"
|
||||
# Per sudo darf jeder nur für sich selbst deployen (sudoers erlaubt die ganze Gruppe)
|
||||
if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" != "root" && "$SUDO_USER" != "$APP_USER" ]]; then
|
||||
die "'$SUDO_USER' darf nicht für '$APP_USER' deployen"
|
||||
fi
|
||||
in_array "$ACTION" "${ALLOWED_ACTIONS[@]}" || die "Unbekannte Aktion: '$ACTION' (erlaubt: ${ALLOWED_ACTIONS[*]})"
|
||||
if $USE_CACHE && [[ "$ACTION" != "build" && "$ACTION" != "deploy" ]]; then
|
||||
die "--cache ist nur bei build/deploy sinnvoll"
|
||||
fi
|
||||
|
||||
if ! is_allowed_action "$ACTION"; then
|
||||
echo "❌ Unbekannte Aktion: '$ACTION'"
|
||||
echo " Erlaubt: ${ALLOWED_ACTIONS[*]}"
|
||||
exit 1
|
||||
fi
|
||||
command -v docker >/dev/null || die "docker nicht gefunden"
|
||||
docker compose version &>/dev/null || die "Docker-Compose-Plugin nicht verfügbar"
|
||||
|
||||
# ── Pfad-Auflösung ───────────────────────────────────────────────────────────
|
||||
HOME_DIR=$(getent passwd "$APP_USER" | cut -d: -f6)
|
||||
if [[ -z "$HOME_DIR" ]]; then
|
||||
echo "❌ Home-Verzeichnis für '$APP_USER' nicht ermittelbar"
|
||||
exit 1
|
||||
fi
|
||||
# ── Pfade ────────────────────────────────────────────────────────────────────
|
||||
HOME_DIR="$(getent passwd "$APP_USER" | cut -d: -f6)"
|
||||
[[ -n "$HOME_DIR" ]] || die "Home-Verzeichnis für '$APP_USER' nicht ermittelbar"
|
||||
|
||||
# Symlink-Tricks verhindern: aufgelöster Pfad muss unter dem Home bleiben
|
||||
APP_DIR="$(realpath -e -- "${HOME_DIR}/${DEPLOY_SUBDIR}" 2>/dev/null)" \
|
||||
|| die "Verzeichnis nicht gefunden: ${HOME_DIR}/${DEPLOY_SUBDIR}"
|
||||
HOME_REAL="$(realpath -e -- "$HOME_DIR")"
|
||||
[[ "$APP_DIR" == "$HOME_REAL"/* ]] || die "Deploy-Verzeichnis liegt außerhalb des Home: $APP_DIR"
|
||||
|
||||
APP_DIR="${HOME_DIR}/${DEPLOY_SUBDIR}"
|
||||
COMPOSE_FILE="${APP_DIR}/docker-compose.yml"
|
||||
COMPOSE_OVERRIDE="${APP_DIR}/docker-compose.override.yml"
|
||||
[[ -f "$COMPOSE_FILE" ]] || die "docker-compose.yml nicht gefunden: $COMPOSE_FILE"
|
||||
|
||||
if [[ ! -d "$APP_DIR" ]]; then
|
||||
echo "❌ Verzeichnis nicht gefunden: $APP_DIR"
|
||||
exit 1
|
||||
fi
|
||||
# ── Nebenläufigkeit: pro User nur ein Lauf gleichzeitig ──────────────────────
|
||||
exec 9>"/run/lock/${SCRIPT_NAME}.${APP_USER}.lock"
|
||||
flock -n 9 || die "Für '$APP_USER' läuft bereits ein Deploy"
|
||||
|
||||
if [[ ! -f "$COMPOSE_FILE" ]]; then
|
||||
echo "❌ docker-compose.yml nicht gefunden: $COMPOSE_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ── Compose-Args aufbauen ────────────────────────────────────────────────────
|
||||
# ── Compose-Setup ────────────────────────────────────────────────────────────
|
||||
export COMPOSE_PROJECT_NAME="$APP_USER"
|
||||
COMPOSE_ARGS=(-f "$COMPOSE_FILE")
|
||||
if [[ -f "$COMPOSE_OVERRIDE" ]]; then
|
||||
COMPOSE_ARGS+=(-f "$COMPOSE_OVERRIDE")
|
||||
log "📎 Override wird verwendet: $COMPOSE_OVERRIDE"
|
||||
log "📎 Override: $COMPOSE_OVERRIDE"
|
||||
fi
|
||||
|
||||
# ── Prefix setzen ────────────────────────────────────────────────────────────
|
||||
export COMPOSE_PROJECT_NAME="$APP_USER"
|
||||
log "🏷️ Project-Prefix: $COMPOSE_PROJECT_NAME"
|
||||
compose() { docker compose "${COMPOSE_ARGS[@]}" "$@"; }
|
||||
|
||||
# ── Ausführung ───────────────────────────────────────────────────────────────
|
||||
log "🚀 User: $APP_USER | Pfad: $APP_DIR | Aktion: $ACTION"
|
||||
log "🚀 Aufrufer: ${SUDO_USER:-root} | User: $APP_USER | Projekt: $COMPOSE_PROJECT_NAME | Pfad: $APP_DIR | Aktion: $ACTION"
|
||||
cd "$APP_DIR"
|
||||
|
||||
# Fehlerhafte Compose-Dateien früh abfangen (nicht bei down/logs)
|
||||
case "$ACTION" in
|
||||
build|up|restart|pull|deploy)
|
||||
compose config --quiet || die "Compose-Konfiguration ungültig"
|
||||
;;
|
||||
esac
|
||||
|
||||
# ── Ausführung ───────────────────────────────────────────────────────────────
|
||||
case "$ACTION" in
|
||||
build)
|
||||
log "📦 Build starten..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" build --no-cache
|
||||
log "📦 Build..."
|
||||
compose build "${NO_CACHE[@]}"
|
||||
;;
|
||||
up)
|
||||
log "▶️ Container starten..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" up -d
|
||||
compose up -d --remove-orphans
|
||||
;;
|
||||
down)
|
||||
log "⏹️ Container stoppen..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" down
|
||||
compose down
|
||||
;;
|
||||
restart)
|
||||
log "🔄 Container neu starten..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" restart
|
||||
compose restart
|
||||
;;
|
||||
logs)
|
||||
log "📋 Logs (letzte 100 Zeilen)..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" logs --tail=100
|
||||
compose logs --tail=100
|
||||
;;
|
||||
pull)
|
||||
log "⬇️ Images aktualisieren..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" pull
|
||||
compose pull
|
||||
;;
|
||||
deploy)
|
||||
log "🚢 Full Deploy: pull → build → up..."
|
||||
docker compose "${COMPOSE_ARGS[@]}" pull
|
||||
docker compose "${COMPOSE_ARGS[@]}" build --no-cache
|
||||
docker compose "${COMPOSE_ARGS[@]}" up -d
|
||||
log "🚢 Deploy: pull → build → up..."
|
||||
compose pull --ignore-buildable
|
||||
compose build --pull "${NO_CACHE[@]}"
|
||||
compose up -d --remove-orphans
|
||||
compose ps
|
||||
;;
|
||||
esac
|
||||
|
||||
log "✅ Fertig: $APP_USER $ACTION"
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# authentik-LDAP-Outpost ↔ sshd
|
||||
|
||||
Anmeldung per SSH gegen authentik: **sshd → PAM/NSS → SSSD → LDAP-Outpost (LDAPS) → authentik**.
|
||||
Die Deploy-User aus `create-deploy-user.py` (Service-Accounts) melden sich mit ihrem
|
||||
App-Passwort an, normale User per Passwort oder SSH-Key.
|
||||
|
||||
```
|
||||
Client ──ssh──▶ sshd ──PAM/NSS──▶ SSSD ──ldaps:636──▶ LDAP-Outpost ──API──▶ authentik
|
||||
│ (Bind: Service-Account)
|
||||
└─ AuthorizedKeysCommand: sss_ssh_authorizedkeys
|
||||
```
|
||||
|
||||
| Baustein | Aufgabe |
|
||||
|---|---|
|
||||
| `setup-sshd-ldap.sh` | Konfiguriert SSSD, NSS, PAM, sshd, `docker-deploy.sh`-Gruppe und sudoers |
|
||||
| `check-sshd-ldap.sh` | Diagnose der gesamten Kette |
|
||||
| `create-deploy-user.py` | Legt Deploy-User + Gruppenmitgliedschaften in authentik an |
|
||||
| `docker-deploy.sh` | Deployt per sudo; Berechtigung über `server_<SERVER>_docker_compose` |
|
||||
|
||||
## 1. authentik vorbereiten
|
||||
|
||||
1. **Gruppen** anlegen (Verzeichnis *Gruppen*):
|
||||
- `server_<SERVER>_ssh_access` (Login auf dem Server erlaubt)
|
||||
- `server_<SERVER>_docker_compose` (darf `docker-deploy.sh` nutzen)
|
||||
- Server-Standard ist `H1`.
|
||||
2. **Bind-Account** für SSSD: Service-Account `ldapsvc` anlegen (*Verzeichnis → User → Service-Account*), Token/Passwort notieren.
|
||||
Eine Gruppe `ldap-search` anlegen, den Account hinzufügen und dieser Gruppe die
|
||||
Berechtigung *Search full LDAP directory* geben. Ohne diese Berechtigung sieht SSSD keine Gruppen.
|
||||
3. **LDAP-Provider** anlegen (*Anwendungen → Provider → LDAP Provider*):
|
||||
- Bind-Flow: `default-authentication-flow` (oder ein Flow ohne MFA, wenn Service-Accounts per App-Passwort binden – MFA lässt sich per LDAP nicht beantworten)
|
||||
- Search-Group: `ldap-search`
|
||||
- Base-DN: z. B. `dc=ldap,dc=goauthentik,dc=io`
|
||||
- *Bind mode* / *Search mode*: Direct (keine Cached-Variante, damit Gruppenänderungen sofort greifen)
|
||||
4. **Application** zum Provider anlegen, dann einen **LDAP-Outpost** erstellen und die Application zuweisen.
|
||||
5. **TLS:** Der Outpost liefert LDAPS auf 636. Für ein vertrauenswürdiges Zertifikat dem Outpost ein Zertifikat zuweisen (Provider → *TLS Server name* / Zertifikat) und die CA auf dem SSH-Server hinterlegen (`--ca-cert`). Klartext-LDAP wird vom Setup-Skript abgelehnt.
|
||||
6. **User-Attribute** (setzt `create-deploy-user.py` für Deploy-User automatisch):
|
||||
- `homeDirectory`: Home-Verzeichnis, Standard `/home/<username>`
|
||||
- `notes`: Link zum Gitea-Repo
|
||||
- `sshPublicKey` (optional): öffentlicher SSH-Schlüssel für Key-Login
|
||||
- `uidNumber`/`gidNumber` berechnet authentik selbst.
|
||||
|
||||
## 2. SSH-Server einrichten
|
||||
|
||||
Voraussetzung: Debian/Ubuntu, root-Zugriff, Netzwerkzugang zum Outpost auf Port 636.
|
||||
|
||||
```bash
|
||||
sudo ./setup-sshd-ldap.sh \
|
||||
--ldap-uri ldaps://ldap.example.org:636 \
|
||||
--base-dn dc=ldap,dc=goauthentik,dc=io \
|
||||
--bind-dn cn=ldapsvc,ou=users,dc=ldap,dc=goauthentik,dc=io \
|
||||
--server H1 \
|
||||
--ca-cert /pfad/zur/ca.pem
|
||||
```
|
||||
|
||||
Das Skript (idempotent, sichert vorhandene `sssd.conf`):
|
||||
|
||||
- installiert `sssd`, `sssd-ldap`, `libnss-sss`, `libpam-sss`
|
||||
- schreibt `/etc/sssd/sssd.conf` (0600) mit Zugriffsfilter
|
||||
`(memberOf=cn=server_<SERVER>_ssh_access,ou=groups,<BASE_DN>)` – nur Gruppenmitglieder dürfen sich per LDAP anmelden
|
||||
- ergänzt `sss` in `/etc/nsswitch.conf` und aktiviert `pam_sss` sowie `pam_mkhomedir`
|
||||
(Home wird beim ersten Login angelegt; `/etc/skel/deployment` legt das Deploy-Verzeichnis gleich mit an)
|
||||
- schreibt `/etc/ssh/sshd_config.d/50-authentik-ldap.conf` (`UsePAM`, `AuthorizedKeysCommand sss_ssh_authorizedkeys`)
|
||||
- schreibt `/etc/docker-deploy.conf` (`DEPLOY_SERVER=<SERVER>`) und `/etc/sudoers.d/docker-deploy`
|
||||
(`%server_<SERVER>_docker_compose ALL=(root) NOPASSWD: /usr/local/bin/docker-deploy.sh`; abschaltbar mit `--no-sudoers`)
|
||||
|
||||
Danach `docker-deploy.sh` nach `/usr/local/bin/` kopieren (`install -m 0755 docker-deploy.sh /usr/local/bin/`).
|
||||
|
||||
## 3. Prüfen
|
||||
|
||||
```bash
|
||||
./check-sshd-ldap.sh <username> [server]
|
||||
ssh <username>@<host>
|
||||
```
|
||||
|
||||
Typische Fehler:
|
||||
|
||||
| Symptom | Ursache / Lösung |
|
||||
|---|---|
|
||||
| `getent passwd <user>` leer | Bind-Account ohne *Search full LDAP directory*; falsche Base-DN; Outpost nicht erreichbar → `sssctl domain-status authentik` |
|
||||
| Gruppen fehlen in `id` | Nutzer nicht in der Gruppe; `ldap_group_*`-Suchbasis falsch; Cache: `sss_cache -E` |
|
||||
| Login abgelehnt trotz korrektem Passwort | Nicht in `server_<SERVER>_ssh_access` (SSSD-Access-Filter) |
|
||||
| TLS-Fehler | CA fehlt oder Hostname passt nicht zum Zertifikat (`ldap_tls_reqcert = demand`) |
|
||||
| Key-Login klappt nicht | Attribut `sshPublicKey` fehlt/falsch benannt; `sss_ssh_authorizedkeys <user>` testen |
|
||||
| `sudo`: *darf nicht für … deployen* | Gewollt: Aufrufer darf nur für sich selbst deployen (Admins als echter root) |
|
||||
|
||||
Debug: `sssctl debug-level 6`, `journalctl -u sssd -u ssh -f`.
|
||||
|
||||
## 4. Deploy-Ablauf
|
||||
|
||||
1. `create-deploy-user.py --project-path owner/repo [--server H1]` legt User und Gruppen an und setzt `deploy_user`/`deploy_pass` im Gitea-Repo.
|
||||
2. Die CI meldet sich per SSH als Deploy-User an, lädt `docker-compose.yml` nach `~/deployment/` und ruft
|
||||
`sudo docker-deploy.sh <username> deploy` auf.
|
||||
|
||||
## Sicherheitshinweise
|
||||
|
||||
- Bind-Passwort steht in `/etc/sssd/sssd.conf` (0600, root) – für den Bind-Account nur minimale Rechte vergeben.
|
||||
- Wer `docker compose` als root aus einem User-Verzeichnis ausführen lässt, gibt dem User faktisch root-Rechte (Compose-Datei kann beliebige Mounts definieren). Die Gruppe `server_<SERVER>_docker_compose` nur an vertrauenswürdige Projekte vergeben.
|
||||
- Passwort-Login ist für Service-Accounts nötig; für normale User sollte zusätzlich Key-Login bevorzugt und MFA auf einem separaten Flow gehalten werden.
|
||||
- Die genauen Attributnamen (`sshPublicKey`, `homeDirectory`, `memberOf`) und die Berechtigung des Search-Accounts hängen von der authentik-Version ab. Beim ersten Einsatz mit `ldapsearch -H ldaps://… -D <bind-dn> -W -b <base-dn> "(cn=<user>)"` verifizieren.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Beispiel: .gitea/workflows/deploy.yml im Repo eines Dienstes
|
||||
#
|
||||
# Voraussetzungen (Setup mit create-deploy-user.py --project-path owner/repo):
|
||||
# Variable deploy_user – Deploy-User (wird vom Skript gesetzt)
|
||||
# Secret deploy_pass – Passwort/App-Token des Users (wird vom Skript gesetzt)
|
||||
# Variable deploy_host – Hostname/IP des Zielservers (manuell setzen)
|
||||
#
|
||||
# Das Repo enthält docker-compose.yml (und optional docker-compose.override.yml)
|
||||
# im Wurzelverzeichnis; sie landen in ~/deployment auf dem Server.
|
||||
name: deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# Nie zwei Deploys gleichzeitig für denselben Dienst
|
||||
concurrency:
|
||||
group: deploy-${{ gitea.repository }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
DEPLOY_USER: ${{ vars.deploy_user }}
|
||||
DEPLOY_HOST: ${{ vars.deploy_host }}
|
||||
SSHPASS: ${{ secrets.deploy_pass }}
|
||||
SSH_OPTS: -o StrictHostKeyChecking=accept-new -o PubkeyAuthentication=no
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Compose-Datei validieren
|
||||
run: docker compose -f docker-compose.yml config --quiet
|
||||
|
||||
- name: Tools installieren
|
||||
run: sudo apt-get update -qq && sudo apt-get install -y -qq sshpass rsync
|
||||
|
||||
- name: Dateien nach ~/deployment synchronisieren
|
||||
run: |
|
||||
sshpass -e rsync -az --delete \
|
||||
--exclude '.git' --exclude '.gitea' --exclude '.env' \
|
||||
-e "ssh $SSH_OPTS" \
|
||||
./ "$DEPLOY_USER@$DEPLOY_HOST:deployment/"
|
||||
|
||||
- name: Deploy (pull → build → up)
|
||||
run: |
|
||||
sshpass -e ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" \
|
||||
"sudo /usr/local/bin/docker-deploy.sh $DEPLOY_USER deploy"
|
||||
|
||||
- name: Logs bei Fehler
|
||||
if: failure()
|
||||
run: |
|
||||
sshpass -e ssh $SSH_OPTS "$DEPLOY_USER@$DEPLOY_HOST" \
|
||||
"sudo /usr/local/bin/docker-deploy.sh $DEPLOY_USER logs" || true
|
||||
Executable
+186
@@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env bash
|
||||
# setup-sshd-ldap.sh
|
||||
#
|
||||
# Bindet sshd über SSSD an den authentik-LDAP-Outpost an (Debian/Ubuntu).
|
||||
# Siehe docs/authentik-ldap-sshd.md.
|
||||
#
|
||||
# Verwendung:
|
||||
# sudo ./setup-sshd-ldap.sh --ldap-uri ldaps://ldap.example.org:636 \
|
||||
# --base-dn dc=ldap,dc=goauthentik,dc=io \
|
||||
# --bind-dn cn=ldapsvc,ou=users,dc=ldap,dc=goauthentik,dc=io \
|
||||
# [--server H1] [--ca-cert /pfad/ca.pem] [--bind-password-file /pfad]
|
||||
set -Eeuo pipefail
|
||||
IFS=$'\n\t'
|
||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
|
||||
readonly SSSD_CONF="/etc/sssd/sssd.conf"
|
||||
readonly SSHD_DROPIN="/etc/ssh/sshd_config.d/50-authentik-ldap.conf"
|
||||
readonly SUDOERS_FILE="/etc/sudoers.d/docker-deploy"
|
||||
readonly DEPLOY_CONF="/etc/docker-deploy.conf"
|
||||
readonly CA_TARGET="/etc/sssd/authentik-ldap-ca.pem"
|
||||
|
||||
SERVER="H1"
|
||||
LDAP_URI="" BASE_DN="" BIND_DN="" CA_CERT="" PW_FILE=""
|
||||
INSTALL_SUDOERS=true
|
||||
|
||||
log() { printf '[%(%H:%M:%S)T] %s\n' -1 "$*"; }
|
||||
die() { printf '❌ %s\n' "$*" >&2; exit 1; }
|
||||
|
||||
usage() {
|
||||
cat >&2 <<EOF
|
||||
Verwendung: sudo $(basename "$0") --ldap-uri URI --base-dn DN --bind-dn DN [Optionen]
|
||||
|
||||
Pflicht:
|
||||
--ldap-uri URI z. B. ldaps://ldap.example.org:636
|
||||
--base-dn DN Base-DN des Outposts (authentik-Standard: dc=ldap,dc=goauthentik,dc=io)
|
||||
--bind-dn DN Bind-DN des LDAP-Service-Accounts
|
||||
|
||||
Optional:
|
||||
--bind-password-file FILE Passwort/Token des Bind-Accounts (sonst Abfrage)
|
||||
--server NAME Servername, Standard H1 -> server_H1_ssh_access / server_H1_docker_compose
|
||||
--ca-cert FILE CA-Zertifikat für das LDAPS-Zertifikat des Outposts
|
||||
--no-sudoers sudoers-Regel für docker-deploy.sh nicht anlegen
|
||||
EOF
|
||||
exit 1
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--ldap-uri) LDAP_URI="${2:?}"; shift 2 ;;
|
||||
--base-dn) BASE_DN="${2:?}"; shift 2 ;;
|
||||
--bind-dn) BIND_DN="${2:?}"; shift 2 ;;
|
||||
--bind-password-file) PW_FILE="${2:?}"; shift 2 ;;
|
||||
--server) SERVER="${2:?}"; shift 2 ;;
|
||||
--ca-cert) CA_CERT="${2:?}"; shift 2 ;;
|
||||
--no-sudoers) INSTALL_SUDOERS=false; shift ;;
|
||||
-h|--help) usage ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ $EUID -eq 0 ]] || die "Muss als root laufen"
|
||||
[[ -n "$LDAP_URI" && -n "$BASE_DN" && -n "$BIND_DN" ]] || usage
|
||||
[[ "$LDAP_URI" == ldaps://* ]] || die "Nur ldaps:// ist erlaubt (Passwörter dürfen nicht im Klartext übertragen werden)"
|
||||
[[ "$SERVER" =~ ^[A-Za-z0-9_-]+$ ]] || die "Ungültiger Servername: '$SERVER'"
|
||||
[[ -z "$CA_CERT" || -r "$CA_CERT" ]] || die "CA-Zertifikat nicht lesbar: $CA_CERT"
|
||||
command -v apt-get >/dev/null || die "Nur Debian/Ubuntu (apt) unterstützt"
|
||||
|
||||
if [[ -n "$PW_FILE" ]]; then
|
||||
[[ -r "$PW_FILE" ]] || die "Passwortdatei nicht lesbar: $PW_FILE"
|
||||
BIND_PW="$(<"$PW_FILE")"
|
||||
else
|
||||
read -rsp "Bind-Passwort für $BIND_DN: " BIND_PW; echo
|
||||
fi
|
||||
[[ -n "$BIND_PW" ]] || die "Leeres Bind-Passwort"
|
||||
|
||||
SSH_GROUP="server_${SERVER}_ssh_access"
|
||||
DOCKER_GROUP="server_${SERVER}_docker_compose"
|
||||
|
||||
# ── Pakete ───────────────────────────────────────────────────────────────────
|
||||
log "📦 Pakete installieren"
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
sssd sssd-ldap libnss-sss libpam-sss libsss-sudo openssh-server ldap-utils >/dev/null
|
||||
|
||||
# ── CA ───────────────────────────────────────────────────────────────────────
|
||||
TLS_CACERT_LINE="# ldap_tls_cacert: System-CA-Store"
|
||||
if [[ -n "$CA_CERT" ]]; then
|
||||
install -m 0644 -o root -g root "$CA_CERT" "$CA_TARGET"
|
||||
TLS_CACERT_LINE="ldap_tls_cacert = $CA_TARGET"
|
||||
fi
|
||||
|
||||
# ── SSSD ─────────────────────────────────────────────────────────────────────
|
||||
log "🔧 $SSSD_CONF schreiben"
|
||||
install -d -m 0711 /etc/sssd
|
||||
[[ -e "$SSSD_CONF" ]] && cp -a "$SSSD_CONF" "${SSSD_CONF}.bak.$(date +%s)"
|
||||
umask 077
|
||||
cat >"$SSSD_CONF" <<EOF
|
||||
# Verwaltet von setup-sshd-ldap.sh
|
||||
[sssd]
|
||||
services = nss, pam, ssh
|
||||
domains = authentik
|
||||
|
||||
[domain/authentik]
|
||||
id_provider = ldap
|
||||
auth_provider = ldap
|
||||
chpass_provider = none
|
||||
access_provider = ldap
|
||||
|
||||
ldap_uri = $LDAP_URI
|
||||
ldap_search_base = $BASE_DN
|
||||
ldap_default_bind_dn = $BIND_DN
|
||||
ldap_default_authtok_type = password
|
||||
ldap_default_authtok = $BIND_PW
|
||||
ldap_tls_reqcert = demand
|
||||
$TLS_CACERT_LINE
|
||||
|
||||
ldap_schema = rfc2307
|
||||
ldap_user_search_base = ou=users,$BASE_DN
|
||||
ldap_group_search_base = ou=groups,$BASE_DN
|
||||
ldap_user_object_class = posixAccount
|
||||
ldap_group_object_class = posixGroup
|
||||
ldap_user_name = cn
|
||||
ldap_user_gecos = name
|
||||
ldap_user_home_directory = homeDirectory
|
||||
ldap_user_ssh_public_key = sshPublicKey
|
||||
ldap_group_member = member
|
||||
|
||||
# Nur Mitglieder der Server-Gruppe dürfen sich anmelden
|
||||
ldap_access_order = filter
|
||||
ldap_access_filter = (memberOf=cn=$SSH_GROUP,ou=groups,$BASE_DN)
|
||||
|
||||
fallback_homedir = /home/%u
|
||||
default_shell = /bin/bash
|
||||
enumerate = false
|
||||
cache_credentials = true
|
||||
entry_cache_timeout = 300
|
||||
use_fully_qualified_names = false
|
||||
EOF
|
||||
chown root:root "$SSSD_CONF"
|
||||
chmod 0600 "$SSSD_CONF"
|
||||
umask 022
|
||||
|
||||
# ── NSS / PAM ────────────────────────────────────────────────────────────────
|
||||
log "🔧 NSS/PAM konfigurieren"
|
||||
for db in passwd group; do
|
||||
grep -Eq "^${db}:.*\bsss\b" /etc/nsswitch.conf || sed -i -E "s/^(${db}:.*)$/\1 sss/" /etc/nsswitch.conf
|
||||
done
|
||||
install -d -m 0755 /etc/skel/deployment
|
||||
pam-auth-update --enable sss mkhomedir >/dev/null
|
||||
|
||||
# ── sshd ─────────────────────────────────────────────────────────────────────
|
||||
log "🔧 $SSHD_DROPIN schreiben"
|
||||
install -d -m 0755 /etc/ssh/sshd_config.d
|
||||
grep -Eq '^\s*Include\s+/etc/ssh/sshd_config.d/\*\.conf' /etc/ssh/sshd_config \
|
||||
|| sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config
|
||||
cat >"$SSHD_DROPIN" <<EOF
|
||||
# Verwaltet von setup-sshd-ldap.sh
|
||||
UsePAM yes
|
||||
PubkeyAuthentication yes
|
||||
# Service-Accounts (CI/CD) melden sich mit dem authentik-App-Passwort an
|
||||
PasswordAuthentication yes
|
||||
AuthorizedKeysCommand /usr/bin/sss_ssh_authorizedkeys %u
|
||||
AuthorizedKeysCommandUser nobody
|
||||
EOF
|
||||
sshd -t || die "sshd-Konfiguration ungültig - Drop-in $SSHD_DROPIN prüfen"
|
||||
|
||||
# ── docker-deploy.sh ─────────────────────────────────────────────────────────
|
||||
log "🔧 $DEPLOY_CONF schreiben"
|
||||
printf 'DEPLOY_SERVER=%s\n' "$SERVER" >"$DEPLOY_CONF"
|
||||
chown root:root "$DEPLOY_CONF"; chmod 0644 "$DEPLOY_CONF"
|
||||
|
||||
if $INSTALL_SUDOERS; then
|
||||
log "🔧 $SUDOERS_FILE schreiben"
|
||||
tmp="$(mktemp)"
|
||||
printf '%%%s ALL=(root) NOPASSWD: /usr/local/bin/docker-deploy.sh\n' "$DOCKER_GROUP" >"$tmp"
|
||||
visudo -cf "$tmp" >/dev/null || { rm -f "$tmp"; die "sudoers-Regel ungültig"; }
|
||||
install -m 0440 -o root -g root "$tmp" "$SUDOERS_FILE"
|
||||
rm -f "$tmp"
|
||||
fi
|
||||
|
||||
# ── Dienste ──────────────────────────────────────────────────────────────────
|
||||
log "🔄 Dienste (neu) starten"
|
||||
systemctl enable --now sssd >/dev/null
|
||||
systemctl restart sssd
|
||||
systemctl reload ssh 2>/dev/null || systemctl reload sshd
|
||||
|
||||
log "✅ Fertig. Prüfen mit: ./check-sshd-ldap.sh <username>"
|
||||
Reference in new issue
Block a user