1# This module defines a systemd service that obtains the SSH key and
2# host name of virtual machines running on Amazon EC2, Eucalyptus and
3# OpenStack Compute (Nova).
4
5{ config, lib, pkgs, ... }:
6
7with lib;
8
9{
10 config = {
11
12 systemd.services."fetch-ec2-data" =
13 { description = "Fetch EC2 Data";
14
15 wantedBy = [ "multi-user.target" "sshd.service" ];
16 before = [ "sshd.service" ];
17 wants = [ "ip-up.target" ];
18 after = [ "ip-up.target" ];
19
20 path = [ pkgs.wget pkgs.iproute ];
21
22 script =
23 ''
24 wget="wget -q --retry-connrefused -O -"
25
26 ${optionalString (config.networking.hostName == "") ''
27 echo "setting host name..."
28 ${pkgs.nettools}/bin/hostname $($wget http://169.254.169.254/1.0/meta-data/hostname)
29 ''}
30
31 # Don't download the SSH key if it has already been injected
32 # into the image (a Nova feature).
33 if ! [ -e /root/.ssh/authorized_keys ]; then
34 echo "obtaining SSH key..."
35 mkdir -m 0700 -p /root/.ssh
36 $wget http://169.254.169.254/1.0/meta-data/public-keys/0/openssh-key > /root/key.pub
37 if [ $? -eq 0 -a -e /root/key.pub ]; then
38 if ! grep -q -f /root/key.pub /root/.ssh/authorized_keys; then
39 cat /root/key.pub >> /root/.ssh/authorized_keys
40 echo "new key added to authorized_keys"
41 fi
42 chmod 600 /root/.ssh/authorized_keys
43 rm -f /root/key.pub
44 fi
45 fi
46
47 # Extract the intended SSH host key for this machine from
48 # the supplied user data, if available. Otherwise sshd will
49 # generate one normally.
50 $wget http://169.254.169.254/2011-01-01/user-data > /root/user-data || true
51 key="$(sed 's/|/\n/g; s/SSH_HOST_DSA_KEY://; t; d' /root/user-data)"
52 key_pub="$(sed 's/SSH_HOST_DSA_KEY_PUB://; t; d' /root/user-data)"
53 if [ -n "$key" -a -n "$key_pub" -a ! -e /etc/ssh/ssh_host_dsa_key ]; then
54 mkdir -m 0755 -p /etc/ssh
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
60 serviceConfig.Type = "oneshot";
61 serviceConfig.RemainAfterExit = true;
62 };
63
64 systemd.services."print-host-key" =
65 { description = "Print SSH Host Key";
66 wantedBy = [ "multi-user.target" ];
67 after = [ "sshd.service" ];
68 script =
69 ''
70 # Print the host public key on the console so that the user
71 # can obtain it securely by parsing the output of
72 # ec2-get-console-output.
73 echo "-----BEGIN SSH HOST KEY FINGERPRINTS-----" > /dev/console
74 ${config.programs.ssh.package}/bin/ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub > /dev/console
75 echo "-----END SSH HOST KEY FINGERPRINTS-----" > /dev/console
76 '';
77 serviceConfig.Type = "oneshot";
78 serviceConfig.RemainAfterExit = true;
79 };
80
81 };
82}