at 25.11-pre 3.3 kB view raw
1# This module defines a systemd service that sets the SSH host key and 2# authorized client key and host name of virtual machines running on 3# Amazon EC2, Eucalyptus and OpenStack Compute (Nova). 4 5{ 6 config, 7 lib, 8 pkgs, 9 ... 10}: 11 12with lib; 13 14{ 15 imports = [ 16 (mkRemovedOptionModule [ "ec2" "metadata" ] "") 17 ]; 18 19 config = { 20 21 systemd.services.apply-ec2-data = { 22 description = "Apply EC2 Data"; 23 24 wantedBy = [ 25 "multi-user.target" 26 "sshd.service" 27 ]; 28 before = [ "sshd.service" ]; 29 after = [ "fetch-ec2-metadata.service" ]; 30 31 path = [ pkgs.iproute2 ]; 32 33 script = '' 34 ${optionalString (config.networking.hostName == "") '' 35 echo "setting host name..." 36 if [ -s /etc/ec2-metadata/hostname ]; then 37 ${pkgs.nettools}/bin/hostname $(cat /etc/ec2-metadata/hostname) 38 fi 39 ''} 40 41 if ! [ -e /root/.ssh/authorized_keys ]; then 42 echo "obtaining SSH key..." 43 mkdir -p /root/.ssh 44 chmod 0700 /root/.ssh 45 if [ -s /etc/ec2-metadata/public-keys-0-openssh-key ]; then 46 (umask 177; cat /etc/ec2-metadata/public-keys-0-openssh-key >> /root/.ssh/authorized_keys) 47 echo "new key added to authorized_keys" 48 fi 49 fi 50 51 # Extract the intended SSH host key for this machine from 52 # the supplied user data, if available. Otherwise sshd will 53 # generate one normally. 54 userData=/etc/ec2-metadata/user-data 55 56 mkdir -p /etc/ssh 57 chmod 0755 /etc/ssh 58 59 if [ -s "$userData" ]; then 60 key="$(sed 's/|/\n/g; s/SSH_HOST_DSA_KEY://; t; d' $userData)" 61 key_pub="$(sed 's/SSH_HOST_DSA_KEY_PUB://; t; d' $userData)" 62 if [ -n "$key" ] && [ -n "$key_pub" ] && [ ! -e /etc/ssh/ssh_host_dsa_key ]; then 63 (umask 077; echo "$key" > /etc/ssh/ssh_host_dsa_key) 64 echo "$key_pub" > /etc/ssh/ssh_host_dsa_key.pub 65 fi 66 67 key="$(sed 's/|/\n/g; s/SSH_HOST_ED25519_KEY://; t; d' $userData)" 68 key_pub="$(sed 's/SSH_HOST_ED25519_KEY_PUB://; t; d' $userData)" 69 if [ -n "$key" ] && [ -n "$key_pub" ] && [ ! -e /etc/ssh/ssh_host_ed25519_key ]; then 70 (umask 077; echo "$key" > /etc/ssh/ssh_host_ed25519_key) 71 echo "$key_pub" > /etc/ssh/ssh_host_ed25519_key.pub 72 fi 73 fi 74 ''; 75 76 serviceConfig.Type = "oneshot"; 77 serviceConfig.RemainAfterExit = true; 78 }; 79 80 systemd.services.print-host-key = { 81 description = "Print SSH Host Key"; 82 wantedBy = [ "multi-user.target" ]; 83 after = [ "sshd.service" ]; 84 script = '' 85 # Print the host public key on the console so that the user 86 # can obtain it securely by parsing the output of 87 # ec2-get-console-output. 88 echo "-----BEGIN SSH HOST KEY FINGERPRINTS-----" > /dev/console 89 for i in /etc/ssh/ssh_host_*_key.pub; do 90 ${config.programs.ssh.package}/bin/ssh-keygen -l -f "$i" > /dev/console || true 91 done 92 echo "-----END SSH HOST KEY FINGERPRINTS-----" > /dev/console 93 ''; 94 serviceConfig.Type = "oneshot"; 95 serviceConfig.RemainAfterExit = true; 96 }; 97 98 }; 99 100 meta.maintainers = with maintainers; [ arianvp ]; 101}