-
Notifications
You must be signed in to change notification settings - Fork 4
/
mkchroot-passwd.sh
executable file
·113 lines (98 loc) · 2.54 KB
/
mkchroot-passwd.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#!/bin/sh
#
# mkchroot-passwd.sh - build rssh compatible /etc/passwd
#
progname=`basename $0`
Usage() {
echo "$progname [ CHROOTDIR ]"
exit 1
}
if [ $# -gt 1 ]; then
Usage
elif [ -n "$1" ]; then
CHROOTDIR=$1
else
CHROOTDIR=/chroot/
fi
# Sanitize CHROOTDIR to prevent confusion
CHROOTDIR="`readlink --canonicalize "$CHROOTDIR"`"
case $CHROOTDIR in
'')
echo "Error: blank CHROOTDIR" >&2
exit 1
;;
/|*:*|*' '*)
echo "Error: unallowed CHROOTDIR \"$CHROOTDIR\"" >&2
exit 1
;;
*:*)
esac
if [ ! -d $CHROOTDIR ]; then
echo "Error: non-existent \"$CHROOTDIR\"" >&2
exit 1
fi
# Ensure correct umask for file generation
umask 022
# Clear credential files before starting
rm -f $CHROOTDIR/etc/passwd
rm -f $CHROOTDIR/etc/group
mkchrootuser() {
user=$1
if [ -z "$user" ]; then
echo "Error: user cannot be blank, returning" >&2
return 1
fi
echo "mkchrootuser: creating $user"
groups="`id -n --groups $user`"
if [ -z "$groups" ]; then
echo "Error: cannot deduce groups for $user, returning" >&2
return 1
fi
homeowner="`getent passwd $user | awk -F: '{print $3}'`"
homegroup="`getent passwd $user | awk -F: '{print $4}'`"
# extract normalized homedir
homedir="`getent passwd $user | awk -F: '{print $6}'`"
if [ -z "$homedir" ]; then
echo "Error, getent cannot resolve homedir of $user, returning" >&2
return 1
fi
case $homedir in
"${CHROOTDIR}")
echo " Replacing $homedir with /"
homedir="/"
;;
"${CHROOTDIR}"/*)
echo " Stripping CHROOTDIR from $homedir"
homedir="`echo "$homedir" | sed "s|^$CHROOTDIR/|/|g"`"
;;
*)
;;
esac
# Encure presence of at least empty homedir inside chroot cage
if [ ! -e "$CHROOTDIR/$homedir" ]; then
echo "Creating empty $homedir in $CHOROOTDIR"
install -d -o $homeowner -g $homegroup "$CHROOTDIR"/"$homedir"
fi
cat <<EOF
Putting $user in $CHROOTDIR/etc/passwd
homedir: $homedir
EOF
getent passwd $user | \
sed "s|:$CHROOTDIR:|:/:|g" | \
sed "s|:$CHROOTDIR/|:/|g" >> $CHROOTDIR/etc/passwd
sort -u -n -k3 -t: -o $CHROOTDIR/etc/passwd $CHROOTDIR/etc/passwd
# not perfect, leaves extraneous group members!!
for group in $groups; do
grep "^$group:" /etc/group >> $CHROOTDIR/etc/group
done
sort -u -n -k3 -t: -o $CHROOTDIR/etc/group $CHROOTDIR/etc/group
}
# Only creat accounts for rssh enabled users
getent passwd | \
grep ":$CHROOTDIR" | \
cut -f1 -d: | \
while read user; do
mkchrootuser "$user"
done
# Add root user for debugging
#mkchrootuser root