From 0abee3d490616aede2b18f027f2ef4be032dcfa1 Mon Sep 17 00:00:00 2001 From: Shane St Savage Date: Tue, 20 Feb 2024 22:35:04 -0800 Subject: [PATCH] Check authorized keys owner/group/permissions before running chmod/chown Fixes #4 --- README.md | 5 ++++- entrypoint.sh | 44 ++++++++++++++++++++++++++++++++++---------- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d5d7e90..fe89d37 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,10 @@ docker run \ ### Over SSH If you would like to connect over ssh, you may mount your public key or -`authorized_keys` file to `/root/.ssh/authorized_keys`. +`authorized_keys` file to `/root/.ssh/authorized_keys`. This file +must have owner root, group root, and 400 octal permissions. + +Alternatively, you may specify the `AUTHORIZED_KEYS` environment variable. Without setting up an `authorized_keys` file, you will be propted for the password (which was specified in the `PASSWORD` variable). diff --git a/entrypoint.sh b/entrypoint.sh index 8e20825..7dd5033 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -23,18 +23,42 @@ if [ -z "$PASSWORD" ]; then exit 1 fi +check_permissions(){ + # Make sure target has uid 0, gid 0, and provided octal permissions + TARGET_PATH="$1" + TARGET_PERMISSIONS="$2" + + EXISTING_UID=$(stat -c "%u" "$TARGET_PATH") + EXISTING_GID=$(stat -c "%g" "$TARGET_PATH") + EXISTING_PERMISSIONS=$(stat -c "%a" "$TARGET_PATH") + + if [ "$EXISTING_UID" -ne "0" ] || [ "$EXISTING_GID" -ne "0" ]; then + echo "$TARGET_PATH should have owner and group root, attempting chown" >&2 + chown root:root "$TARGET_PATH" + fi + + if [ "$EXISTING_PERMISSIONS" -ne "$TARGET_PERMISSIONS" ]; then + echo "$TARGET_PATH should have $TARGET_PERMISSIONS permissions (currently $EXISTING_PERMISSIONS), attempting chmod" >&2 + chmod "$TARGET_PERMISSIONS" "$TARGET_PATH" + fi +} + setup_sshd(){ - if [ -e "/root/.ssh/authorized_keys" ]; then - chmod 400 /root/.ssh/authorized_keys - chown root:root /root/.ssh/authorized_keys - else - mkdir -p /root/.ssh - chown root:root /root/.ssh - if [ ! -z "$AUTHORIZED_KEYS" ]; then - echo "$AUTHORIZED_KEYS" > /root/.ssh/authorized_keys - fi + SSH_DIR="/root/.ssh" + AUTH_KEYS_PATH="${SSH_DIR}/authorized_keys" + + if [ ! -d "$SSH_DIR" ]; then + install -d -m 700 "$SSH_DIR" + fi + check_permissions "$SSH_DIR" "700" + + if [ ! -z "$AUTHORIZED_KEYS" ]; then + install -m 400 <(echo "$AUTHORIZED_KEYS") "$AUTH_KEYS_PATH" + fi + if [ -e "$AUTH_KEYS_PATH" ]; then + check_permissions "$AUTH_KEYS_PATH" "400" fi - chmod 750 /root/.ssh + echo "root:$PASSWORD" | chpasswd }