1#!/bin/sh -e
2#-
3# Copyright (c) 2012-2013 SRI International
4# Copyright (c) 2012 Robert N. M. Watson
5# All rights reserved.
6#
7# This software was developed by SRI International and the University of
8# Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
9# ("CTSRD"), as part of the DARPA CRASH research programme.
10#
11# Redistribution and use in source and binary forms, with or without
12# modification, are permitted provided that the following conditions
13# are met:
14# 1. Redistributions of source code must retain the above copyright
15#    notice, this list of conditions and the following disclaimer.
16# 2. Redistributions in binary form must reproduce the above copyright
17#    notice, this list of conditions and the following disclaimer in the
18#    documentation and/or other materials provided with the distribution.
19#
20# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30# SUCH DAMAGE.
31#
32
33usage()
34{
35	cat <<EOF 1>&2
36usage: makeroot.sh [-B byte-order] [-d] [-e <extras manifest>] [-f <filelist>]
37                   [-k <keydir> [-K <user>]]
38                   [-p <master.passwd> [-g <groupfile>]] [-s <size>]
39		   <image> <bsdroot>
40EOF
41	exit 1
42}
43
44warn()
45{
46	echo `basename $0` "$@" 1>&2
47}
48
49err()
50{
51	ret=$1
52	shift
53	warn "$@"
54	exit $ret
55}
56
57atexit()
58{
59	if [ -z "${DEBUG}" ]; then
60		rm -rf ${tmpdir}
61	else
62		warn "temp directory left at ${tmpdir}"
63	fi
64}
65
66DEBUG=
67# Allow duplicate manifest entries when not file list is given because the
68# FreeBSD METALOG still includes it.
69DUPFLAG=-D
70EXTRAS=
71FILELIST=
72GROUP=
73KEYDIR=
74KEYUSERS=
75PASSWD=
76
77while getopts "B:de:f:g:K:k:l:p:s:" opt; do
78	case "$opt" in
79	B)	BFLAG="-B ${OPTARG}" ;;
80	d)	DEBUG=1 ;;
81	e)	EXTRAS="${EXTRAS} ${OPTARG}" ;;
82	f)	FILELIST="${OPTARG}";;
83	g)	GROUP="${OPTARG}" ;;
84	K)	KEYUSERS="${KEYUSERS} ${OPTARG}" ;;
85	k)	KEYDIR="${OPTARG}" ;;
86	l)	LABEL="${OPTARG}" ;;
87	p)	PASSWD="${OPTARG}" ;;
88	s)	SIZE="${OPTARG}" ;;
89	*)	usage ;;
90	esac
91done
92shift $(($OPTIND - 1))
93
94if [ $# -ne 2 ]; then
95	usage;
96fi
97
98IMGFILE=$(realpath $(dirname $1))/$(basename $1)
99BSDROOT=$2
100
101DBDIR=${BSDROOT}/etc
102
103if [ ! -r ${BSDROOT}/METALOG ]; then
104	err 1 "${BSDROOT} does not contain a METALOG"
105fi
106
107if [ -n "${GROUP}" -a -z "${PASSWD}" ]; then
108	warn "-g requires -p"
109	usage
110fi
111
112if [ -n "${KEYUSERS}" -a -z "${KEYDIR}" ]; then
113	warn "-K requires -k"
114	usage
115fi
116if [ -n "${KEYDIR}" -a -z "${KEYUSERS}" ]; then
117	KEYUSERS=root
118fi
119
120tmpdir=`mktemp -d /tmp/makeroot.XXXXX`
121if [ -z "${tmpdir}" -o ! -d "${tmpdir}" ]; then
122	err 1 "failed to create tmpdir"
123fi
124trap atexit EXIT
125
126manifest=${tmpdir}/manifest
127
128echo "#mtree 2.0" > ${manifest}
129
130if [ -n "${PASSWD}" ]; then
131	cp ${PASSWD} ${tmpdir}/master.passwd
132	pwd_mkdb -d ${tmpdir} -p ${tmpdir}/master.passwd
133	if [ -z "${GROUP}" ]; then
134		cp ${DBDIR}/group ${tmpdir}
135	else
136		cp ${GROUP} ${tmpdir}
137	fi
138
139	cat <<EOF >> ${tmpdir}/passwd.mtree
140./etc/group type=file uname=root gname=wheel mode=0644 contents=${tmpdir}/group
141./etc/master.passwd type=file uname=root gname=wheel mode=0600 contents=${tmpdir}/master.passwd
142./etc/passwd type=file mode=0644 uname=root gname=wheel contents=${tmpdir}/passwd
143./etc/pwd.db type=file mode=0644 uname=root gname=wheel contents=${tmpdir}/pwd.db
144./etc/spwd.db type=file mode=0600 uname=root gname=wheel contents=${tmpdir}/spwd.db
145EOF
146	EXTRAS="${EXTRAS} ${tmpdir}/passwd.mtree"
147
148	DBDIR=${tmpdir}
149fi
150
151if [ -n "${FILELIST}" ]; then
152	# build manifest from root manifest and FILELIST
153	(echo .; grep -v ^# ${FILELIST} | while read path; do
154		# Print each included path and all its sub-paths with a ./
155		# prepended.  The "sort -u" will then discard all the
156		# duplicate directory entries.  This ensures that we
157		# extract the permissions for each unlisted directory
158		# from the METALOG.
159		path="/${path}"
160		while [ -n "${path}" ]; do
161			echo ".${path}"
162			path="${path%/*}"
163		done
164	done) | sort -u ${BSDROOT}/METALOG - | \
165	    awk '
166		!/ type=/ { file = $1 }
167		/ type=/ { if ($1 == file) {print} }' >> ${manifest}
168elif [ -n "${EXTRAS}" ]; then
169	# Start with all the files in BSDROOT/METALOG except those in
170	# one of the EXTRAS manifests.
171	grep -h type=file ${EXTRAS} | cut -d' ' -f1 | \
172	    sort -u ${BSDROOT}/METALOG - | awk '
173		!/ type=/ { file = $1 }
174		/ type=/ { if ($1 != file) {print} }' >> ${manifest}
175else
176	sort -u ${BSDROOT}/METALOG >> ${manifest}
177fi
178
179# For each extras file, add contents keys relative to the directory the
180# manifest lives in for each file line that does not have one.  Adjust
181# contents keys relative to ./ to be relative to the same directory.
182for eman in ${EXTRAS}; do
183	if [ ! -f ${eman} ]; then
184		err 1 "${eman} is not a regular file"
185	fi
186	extradir=`realpath ${eman}`; extradir=`dirname ${extradir}`
187
188	awk '{
189		if ($0 !~ /type=file/) {
190			print
191		} else {
192			if ($0 !~ /contents=/) {
193				printf ("%s contents=%s\n", $0, $1)
194			} else {
195				print
196			}
197		}
198	}' ${eman} | \
199	    sed -e "s|contents=\./|contents=${extradir}/|" >> ${manifest}
200done
201
202# /etc/rcorder.start allows the startup order to be stable even if
203# not all startup scripts are installed.  In theory it should be
204# unnecessary, but dependencies in rc.d appear to be under recorded.
205# This is a hack local to beri/cheribsd.
206#
207echo /etc/rc.d/FIRST > ${tmpdir}/rcorder.start
208rcorder -s nostart ${BSDROOT}/etc/rc.d/* | sed -e "s:^${BSDROOT}::" | \
209     grep -v LAST | grep -v FIRST >> \
210    ${tmpdir}/rcorder.start
211echo /etc/rc.d/LAST >> ${tmpdir}/rcorder.start
212echo "./etc/rcorder.start type=file mode=644 uname=root gname=wheel" \
213   "contents=${tmpdir}/rcorder.start" >> ${manifest}
214
215# Add all public keys in KEYDIR to roots' authorized_keys file.
216if [ -n "${KEYDIR}" ]; then
217	cat ${KEYDIR}/*.pub > ${tmpdir}/authorized_keys
218	if [ ! -s ${tmpdir}/authorized_keys ]; then
219		err 1 "no keys found in ${KEYDIR}"
220	fi
221	for user in ${KEYUSERS}; do
222		userdir=`awk -F: "{if (\\\$1 == \"${user}\") {print \\\$9; exit} }" ${DBDIR}/master.passwd`
223		gid=`awk -F: "{if (\\\$1 == \"${user}\") {print \\\$4; exit} }" ${DBDIR}/master.passwd`
224		group=`awk -F: "{if (\\\$3 == \"${gid}\") {print \\\$1; exit} }" ${DBDIR}/group`
225		if [ -z "${userdir}" ]; then
226			err 1 "${user}: not found in ${DBDIR}/master.passwd"
227		fi
228		echo ".${userdir}/.ssh type=dir mode=700 uname=${user} gname=${group}" >> ${manifest}
229		echo ".${userdir}/.ssh/authorized_keys type=file mode=600 uname=${user} gname=${group} contents=${tmpdir}/authorized_keys" >> ${manifest}
230	done
231fi
232
233if [ -n "${LABEL}" ]; then
234LABELFLAG="-o label=${LABEL}"
235fi
236if [ -n "${SIZE}" ]; then
237SIZEFLAG="-s ${SIZE}"
238fi
239
240cd ${BSDROOT}; makefs ${DUPFLAG} -N ${DBDIR} ${SIZEFLAG} ${BFLAG} \
241     -t ffs ${LABELFLAG} -f 256 ${IMGFILE} ${manifest}
242