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