xref: /freebsd/release/tools/ec2_setpass (revision a9710349513f4c6ccb8bcff34fa9ea186fae6114)
1#!/bin/sh
2
3# KEYWORD: firstboot
4# PROVIDE: ec2_setpass
5# REQUIRE: ec2_fetchkey
6# BEFORE: LOGIN
7
8# Define ec2_setpass_enable=YES in /etc/rc.conf to enable setting the
9# account password and printing in encrypted format to the console.
10: ${ec2_setpass_enable=NO}
11
12# We reuse the user name from ec2_fetchkey since that creates the user
13# and fetches the SSH key which is used to encrypt the password.
14: ${ec2_fetchkey_user=ec2-user}
15
16. /etc/rc.subr
17
18name="ec2_setpass"
19rcvar=ec2_setpass_enable
20start_cmd="ec2_setpass_run"
21stop_cmd=":"
22
23ec2_setpass_run()
24{
25
26	# If the user does not exist or has no SSH key, return.
27	HOMEDIR=$(pw user show ${ec2_fetchkey_user} 2>/dev/null | awk -F: '{print $9}')
28	SSHKEYFILE="${HOMEDIR}/.ssh/authorized_keys"
29	if [ -z "${HOMEDIR}" ] || ! [ -f "${SSHKEYFILE}" ]; then
30		return
31	fi
32
33	# Print the RDP certificate fingerprint
34	echo "HOSTNAME: freebsd"
35	echo "RDPCERTIFICATE-SUBJECTNAME: freebsd"
36	FINGERSHA1=$(openssl x509 -in /usr/local/etc/xrdp/cert.pem \
37	    -noout -fingerprint -sha1 | cut -f 2- -d = | tr -d :)
38	FINGERSHA256=$(openssl x509 -in /usr/local/etc/xrdp/cert.pem \
39	    -noout -fingerprint -sha256 | cut -f 2- -d = | tr A-F a-f)
40	echo "RDPCERTIFICATE-THUMBPRINT: ${FINGERSHA1}"
41	echo "RDPCERTIFICATE-THUMBPRINT256: ${FINGERSHA256}"
42
43	# Set a random password, and print it in encrypted format
44	PUBKEY=$(mktemp -t ec2_setpass)
45	ssh-keygen -e -m PKCS8 -f ${SSHKEYFILE} > ${PUBKEY}
46	PASSWD=`jot -cr 16 / z | tr '\\`' '-+' | rs -g 0`
47	echo "${PASSWD}" | pw usermod ${ec2_fetchkey_user} -h 0
48	echo "Username: ${ec2_fetchkey_user}"
49	echo "Password: <Password>"
50	printf "%s" "${PASSWD}" |
51	    openssl pkeyutl -encrypt -pubin -inkey ${PUBKEY} -pkeyopt rsa_padding_mode:pkcs1 |
52	    base64 -w 0
53	echo "</Password>"
54	echo 'Message: Windows is Ready to use'
55}
56
57load_rc_config $name
58run_rc_command "$1"
59