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).
5 { config, lib, pkgs, ... }:
11 (mkRemovedOptionModule [ "ec2" "metadata" ] "")
16 systemd.services.apply-ec2-data =
17 { description = "Apply EC2 Data";
19 wantedBy = [ "multi-user.target" "sshd.service" ];
20 before = [ "sshd.service" ];
21 after = ["fetch-ec2-metadata.service"];
23 path = [ pkgs.iproute2 ];
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)
34 if ! [ -e /root/.ssh/authorized_keys ]; then
35 echo "obtaining SSH key..."
38 if [ -s /etc/ec2-metadata/public-keys-0-openssh-key ]; then
39 (umask 177; cat /etc/ec2-metadata/public-keys-0-openssh-key >> /root/.ssh/authorized_keys)
40 echo "new key added to authorized_keys"
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
52 if [ -s "$userData" ]; then
53 key="$(sed 's/|/\n/g; s/SSH_HOST_DSA_KEY://; t; d' $userData)"
54 key_pub="$(sed 's/SSH_HOST_DSA_KEY_PUB://; t; d' $userData)"
55 if [ -n "$key" ] && [ -n "$key_pub" ] && [ ! -e /etc/ssh/ssh_host_dsa_key ]; then
56 (umask 077; echo "$key" > /etc/ssh/ssh_host_dsa_key)
57 echo "$key_pub" > /etc/ssh/ssh_host_dsa_key.pub
60 key="$(sed 's/|/\n/g; s/SSH_HOST_ED25519_KEY://; t; d' $userData)"
61 key_pub="$(sed 's/SSH_HOST_ED25519_KEY_PUB://; t; d' $userData)"
62 if [ -n "$key" ] && [ -n "$key_pub" ] && [ ! -e /etc/ssh/ssh_host_ed25519_key ]; then
63 (umask 077; echo "$key" > /etc/ssh/ssh_host_ed25519_key)
64 echo "$key_pub" > /etc/ssh/ssh_host_ed25519_key.pub
69 serviceConfig.Type = "oneshot";
70 serviceConfig.RemainAfterExit = true;
73 systemd.services.print-host-key =
74 { description = "Print SSH Host Key";
75 wantedBy = [ "multi-user.target" ];
76 after = [ "sshd.service" ];
79 # Print the host public key on the console so that the user
80 # can obtain it securely by parsing the output of
81 # ec2-get-console-output.
82 echo "-----BEGIN SSH HOST KEY FINGERPRINTS-----" > /dev/console
83 for i in /etc/ssh/ssh_host_*_key.pub; do
84 ${config.programs.ssh.package}/bin/ssh-keygen -l -f "$i" || true > /dev/console
86 echo "-----END SSH HOST KEY FINGERPRINTS-----" > /dev/console
88 serviceConfig.Type = "oneshot";
89 serviceConfig.RemainAfterExit = true;