# Vulnerable target: OpenSSH compiled FROM SOURCE on musl (Alpine), WITHOUT PAM.
#
# Alpine's packaged OpenSSH already has the fix backported (CVE-2026-123158),
# so we must build from upstream portable source at a pre-fix version.

ARG BASE=alpine:3.24
FROM ${BASE} AS builder

# Build dependencies
RUN apk add --no-cache \
    build-base \
    openssl-dev \
    zlib-dev \
    linux-headers \
    curl

# Download a known-vulnerable portable OpenSSH (10.6p1 = one release before the fix).
ARG OPENSSH_VERSION=10.6p1
RUN curl -fsSL \
      "https://cdn.openbsd.org/pub/OpenBSD/OpenSSH/portable/openssh-${OPENSSH_VERSION}.tar.gz" \
      -o /tmp/openssh.tar.gz \
 && mkdir /tmp/openssh \
 && tar xzf /tmp/openssh.tar.gz -C /tmp/openssh --strip-components=1

# Compile WITHOUT PAM — this is the vulnerable code path.
RUN cd /tmp/openssh \
 && ./configure \
      --prefix=/usr \
      --sysconfdir=/etc/ssh \
      --without-pam \
      --with-privsep-user=sshd \
      --with-privsep-path=/var/empty \
 && make -j"$(nproc)" \
 && make install-nokeys DESTDIR=/openssh-install

# --- Runtime image ---
FROM ${BASE}

RUN apk add --no-cache shadow

# Copy the from-source sshd, overriding any packaged version.
COPY --from=builder /openssh-install/ /

# Privilege-separation directory and user
RUN mkdir -p /var/empty \
 && addgroup -S sshd 2>/dev/null ; \
    adduser -S -D -H -h /var/empty -s /sbin/nologin -G sshd sshd 2>/dev/null ; true

# Host keys
RUN /usr/bin/ssh-keygen -A

# The exploit needs:
#   - An account with "*" as its shadow password → root (Alpine default)
#   - Another account with a real $5$/$6$ hash   → alice
# sshd borrows alice's salt when it sees root's "*" is too short to be a hash.
RUN adduser -D -s /bin/sh alice \
 && echo 'alice:RealPass123!' | chpasswd

# root already has "*" in /etc/shadow on Alpine — verify and enforce it.
RUN sed -i 's/^root:[^:]*:/root:*:/' /etc/shadow

# Config: password auth ON, root login ON, no PAM (compiled without it).
# Verbose logging so you can see the auth flow in docker logs.
RUN printf '\nPasswordAuthentication yes\nPermitRootLogin yes\nKbdInteractiveAuthentication no\nLogLevel VERBOSE\n' \
    >> /etc/ssh/sshd_config

# Smoke-test: print effective config at build time for verification.
RUN /usr/sbin/sshd -T 2>&1 \
    | grep -iE 'passwordauth|permitroot|usepam|kbdinteractive|loglevel' || true
RUN /usr/sbin/sshd -V 2>&1 || /usr/bin/ssh -V 2>&1 || true

EXPOSE 22
CMD ["/usr/sbin/sshd", "-D", "-e"]
