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