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