#!/bin/sh
# Generate secure SSH host keys with proper permissions

set -e

SSH_DIR="/etc/ssh"
KEY_PERMS="600"
DIR_PERMS="700"

echo "[*] Removing old host keys..."
rm -f $SSH_DIR/ssh_host_*

echo "[*] Generating new secure host keys..."

# Generate Ed25519 key (256 bits)
ssh-keygen -t ed25519 -f $SSH_DIR/ssh_host_ed25519_key -N "" -C ""

# Generate RSA key with 4096 bits
ssh-keygen -t rsa -b 4096 -f $SSH_DIR/ssh_host_rsa_key -N "" -C ""

echo "[*] Setting secure permissions..."
chmod $KEY_PERMS $SSH_DIR/ssh_host_*
chmod $DIR_PERMS $SSH_DIR

echo "[*] Filtering moduli for safe DH groups..."
if [ -f $SSH_DIR/moduli ]; then
    awk '$5 >= 3071' $SSH_DIR/moduli > $SSH_DIR/moduli.safe
    mv $SSH_DIR/moduli.safe $SSH_DIR/moduli
    chmod 644 $SSH_DIR/moduli
fi

echo "[*] Verifying key sizes..."
RSA_SIZE=$(ssh-keygen -l -f $SSH_DIR/ssh_host_rsa_key | awk '{print $1}')
ED25519_SIZE=$(ssh-keygen -l -f $SSH_DIR/ssh_host_ed25519_key | awk '{print $1}')

echo "[+] RSA key size: $RSA_SIZE bits"
echo "[+] Ed25519 key size: $ED25519_SIZE bits"

if [ "$RSA_SIZE" -ge 4096 ] && [ "$ED25519_SIZE" -ge 256 ]; then
    echo "[+] Secure host keys generated successfully"
    echo "[+] Keys meet security requirements"
else
    echo "[!] Warning: Key sizes may not meet security requirements"
    exit 1
fi 