xref: /titanic_44/usr/src/cmd/krb5/kadmin/kclient/kclient.sh (revision 744947dc83c634d985ed3ad79ac9c5e28d1865fd)
1#!/bin/ksh93 -p
2#
3# CDDL HEADER START
4#
5# The contents of this file are subject to the terms of the
6# Common Development and Distribution License (the "License").
7# You may not use this file except in compliance with the License.
8#
9# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10# or http://www.opensolaris.org/os/licensing.
11# See the License for the specific language governing permissions
12# and limitations under the License.
13#
14# When distributing Covered Code, include this CDDL HEADER in each
15# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16# If applicable, add the following below this CDDL HEADER, with the
17# fields enclosed by brackets "[]" replaced with your own identifying
18# information: Portions Copyright [yyyy] [name of copyright owner]
19#
20# CDDL HEADER END
21#
22# Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
23#
24# This script is used to setup the Kerberos client by
25# supplying information about the Kerberos realm and kdc.
26#
27# The kerberos configuration file (/etc/krb5/krb5.conf) would
28# be generated and local host's keytab file setup. The script
29# can also optionally setup the system to do kerberized nfs and
30# bringover a master krb5.conf copy from a specified location.
31#
32
33function cleanup {
34
35	kdestroy -q > $TMP_FILE 2>&1
36	rm -r $TMPDIR > /dev/null 2>&1
37
38	exit $1
39}
40function exiting {
41
42        printf "\n$(gettext "Exiting setup, nothing changed").\n\n"
43
44	cleanup $1
45}
46
47function error_message {
48
49        printf -- "---------------------------------------------------\n" >&2
50        printf "$(gettext "Setup FAILED").\n\n" >&2
51
52        cleanup 1
53}
54
55function check_bin {
56
57	typeset bin=$1
58
59	if [[ ! -x $bin ]]; then
60		printf "$(gettext "Could not access/execute %s").\n" $bin >&2
61		error_message
62	fi
63}
64
65function cannot_create {
66	typeset filename="$1"
67	typeset stat="$2"
68
69	if [[ $stat -ne 0 ]]; then
70		printf "\n$(gettext "Can not create/edit %s, exiting").\n" $filename >&2
71		error_message
72	fi
73}
74
75function update_pam_conf {
76	typeset PAM TPAM service
77
78	PAM=/etc/pam.conf
79
80	TPAM=$(mktemp -q -t kclient-pamconf.XXXXXX)
81	if [[ -z $TPAM ]]; then
82		printf "\n$(gettext "Can not create temporary file, exiting").\n" >&2
83		error_message
84	fi
85
86	cp $PAM $TPAM >/dev/null 2>&1
87
88	printf "$(gettext "Configuring %s").\n\n" $PAM
89
90	for service in $SVCs; do
91		svc=${service%:*}
92		auth_type=${service#*:}
93		if egrep -s "^$svc[ 	][ 	]*auth.*pam_krb5*" $TPAM; then
94			printf "$(gettext "The %s service is already configured for pam_krb5, please merge this service in %s").\n\n" $svc $PAM >&2
95			continue
96		else
97			exec 3>>$TPAM
98			printf "\n$svc\tauth include\t\tpam_krb5_$auth_type\n" 1>&3
99		fi
100	done
101
102	cp $TPAM $PAM > /dev/null 2>&1
103
104	rm $TPAM > /dev/null 2>&1
105}
106
107function modify_nfssec_conf {
108	typeset NFSSEC_FILE="/etc/nfssec.conf"
109
110	if [[ -r $NFSSEC_FILE ]]; then
111		cat $NFSSEC_FILE > $NFSSEC_FILE.sav
112		cannot_create $NFSSEC_FILE.sav $?
113	fi
114
115	cat $NFSSEC_FILE > $TMP_FILE
116	cannot_create $TMP_FILE $?
117
118	if grep -s "#krb5" $NFSSEC_FILE > /dev/null 2>&1; then
119		sed "s%^#krb5%krb5%" $TMP_FILE >$NFSSEC_FILE
120		cannot_create $NFSSEC_FILE $?
121	fi
122}
123
124function call_kadmin {
125	typeset svc="$1"
126	typeset bool1 bool2 bool3 bool4
127	typeset service_princ getprincsubcommand anksubcommand ktaddsubcommand
128	typeset ktremsubcommand
129
130	for listentry in $fqdnlist; do
131
132	# Reset conditional vars to 1
133	bool1=1; bool2=1; bool3=1; bool4=1
134
135	service_princ=$(echo "${svc}/${listentry}")
136	getprincsubcommand="getprinc $service_princ"
137	anksubcommand="addprinc -randkey $service_princ"
138	ktaddsubcommand="ktadd $service_princ"
139	ktremsubcommand="ktrem $service_princ all"
140
141	kadmin -c $KRB5CCNAME -q "$getprincsubcommand" 1>$TMP_FILE 2>&1
142
143	egrep -s "$(gettext "get_principal: Principal does not exist")" $TMP_FILE
144	bool1=$?
145	egrep -s "$(gettext "get_principal: Operation requires ``get")" $TMP_FILE
146	bool2=$?
147
148	if [[ $bool1 -eq 0 || $bool2 -eq 0 ]]; then
149		kadmin -c $KRB5CCNAME -q "$anksubcommand" 1>$TMP_FILE 2>&1
150
151		egrep -s "$(gettext "add_principal: Principal or policy already exists while creating \"$service_princ@$realm\".")" $TMP_FILE
152		bool3=$?
153
154		egrep -s "$(gettext "Principal \"$service_princ@$realm\" created.")" $TMP_FILE
155		bool4=$?
156
157		if [[ $bool3 -eq 0 || $bool4 -eq 0 ]]; then
158			printf "$(gettext "%s entry ADDED to KDC database").\n" $service_princ
159		else
160			cat $TMP_FILE;
161			printf "\n$(gettext "kadmin: add_principal of %s failed, exiting").\n" $service_princ >&2
162			error_message
163		fi
164	else
165		printf "$(gettext "%s entry already exists in KDC database").\n" $service_princ >&2
166	fi
167
168	klist -k 1>$TMP_FILE 2>&1
169	egrep -s "$service_princ@$realm" $TMP_FILE
170	if [[ $? -eq 0 ]]; then
171		printf "$(gettext "%s entry already present in keytab").\n" $service_princ >&2
172		# Don't care is this succeeds or not, just need to replace old
173		# entries as it is assummed that the client is reinitialized
174		kadmin -c $KRB5CCNAME -q "$ktremsubcommand" 1>$TMP_FILE 2>&1
175	fi
176
177	kadmin -c $KRB5CCNAME -q "$ktaddsubcommand" 1>$TMP_FILE 2>&1
178	egrep -s "$(gettext "added to keytab WRFILE:$KRB5_KEYTAB_FILE.")" $TMP_FILE
179	if [[ $? -ne 0 ]]; then
180		cat $TMP_FILE;
181		printf "\n$(gettext "kadmin: ktadd of %s failed, exiting").\n" $service_princ >&2
182		error_message
183	else
184		printf "$(gettext "%s entry ADDED to keytab").\n" $service_princ
185	fi
186
187	done
188}
189
190function writeup_krb5_conf {
191	typeset dh
192
193	printf "\n$(gettext "Setting up %s").\n\n" $KRB5_CONFIG_FILE
194
195	exec 3>$KRB5_CONFIG
196	if [[ $? -ne 0 ]]; then
197		printf "\n$(gettext "Can not write to %s, exiting").\n" $KRB5_CONFIG >&2
198		error_message
199	fi
200
201	printf "[libdefaults]\n" 1>&3
202	if [[ $no_keytab == yes ]]; then
203		printf "\tverify_ap_req_nofail = false\n" 1>&3
204	fi
205	if [[ $dns_lookup == yes ]]; then
206	    printf "\t$dnsarg = on\n" 1>&3
207	    if [[ $dnsarg == dns_lookup_kdc ]]; then
208		printf "\tdefault_realm = $realm\n" 1>&3
209		printf "\n[domain_realm]\n" 1>&3
210		if [[ -n $fkdc_list ]]; then
211			for kdc in $fkdc_list; do
212				printf "\t$kdc = $realm\n" 1>&3
213			done
214		fi
215		printf "\t$FKDC = $realm\n" 1>&3
216		printf "\t$client_machine = $realm\n" 1>&3
217		if [[ -z $short_fqdn ]]; then
218			printf "\t.$domain = $realm\n\n" 1>&3
219		else
220			printf "\t.$short_fqdn = $realm\n\n" 1>&3
221		fi
222		if [[ -n $domain_list ]]; then
223			for dh in $domain_list; do
224				printf "\t$dh = $realm\n" 1>&3
225			done
226		fi
227	    else
228		if [[ $dnsarg = dns_lookup_realm ]]; then
229		    printf "\tdefault_realm = $realm\n" 1>&3
230		    printf "\n[realms]\n" 1>&3
231		    printf "\t$realm = {\n" 1>&3
232		    if [[ -n $kdc_list ]]; then
233			for kdc in $kdc_list; do
234				printf "\t\tkdc = $kdc\n" 1>&3
235			done
236		    else
237		    	printf "\t\tkdc = $KDC\n" 1>&3
238		    fi
239		    printf "\t\tadmin_server = $KDC\n" 1>&3
240		    if [[ $non_solaris == yes ]]; then
241			printf "\n\t\tkpasswd_protocol = SET_CHANGE\n" 1>&3
242		    fi
243		    printf "\t}\n\n" 1>&3
244		else
245		    printf "\tdefault_realm = $realm\n\n" 1>&3
246		fi
247	    fi
248	else
249	    printf "\tdefault_realm = $realm\n\n" 1>&3
250
251	    printf "[realms]\n" 1>&3
252	    printf "\t$realm = {\n" 1>&3
253	    if [[ -n $kdc_list ]]; then
254		for kdc in $kdc_list; do
255			printf "\t\tkdc = $kdc\n" 1>&3
256		done
257	    else
258	    	printf "\t\tkdc = $KDC\n" 1>&3
259	    fi
260	    printf "\t\tadmin_server = $KDC\n" 1>&3
261	    if [[ $non_solaris == yes ]]; then
262	    	printf "\n\t\tkpasswd_protocol = SET_CHANGE\n" 1>&3
263	    fi
264	    printf "\t}\n\n" 1>&3
265
266	    printf "[domain_realm]\n" 1>&3
267	    if [[ -n $fkdc_list ]]; then
268		for kdc in $fkdc_list; do
269			printf "\t$kdc = $realm\n" 1>&3
270		done
271	    fi
272	    printf "\t$FKDC = $realm\n" 1>&3
273	    printf "\t$client_machine = $realm\n" 1>&3
274	    if [[ -z $short_fqdn ]]; then
275		printf "\t.$domain = $realm\n\n" 1>&3
276	    else
277		printf "\t.$short_fqdn = $realm\n\n" 1>&3
278	    fi
279	    if [[ -n $domain_list ]]; then
280		for dh in $domain_list; do
281			printf "\t$dh = $realm\n" 1>&3
282		done
283	    fi
284	fi
285
286	printf "[logging]\n" 1>&3
287	printf "\tdefault = FILE:/var/krb5/kdc.log\n" 1>&3
288	printf "\tkdc = FILE:/var/krb5/kdc.log\n" 1>&3
289	printf "\tkdc_rotate = {\n\t\tperiod = 1d\n\t\tversions = 10\n\t}\n\n" 1>&3
290
291	printf "[appdefaults]\n" 1>&3
292	printf "\tkinit = {\n\t\trenewable = true\n\t\tforwardable = true\n" 1>&3
293	if [[ $no_keytab == yes ]]; then
294		printf "\t\tno_addresses = true\n" 1>&3
295	fi
296	printf "\t}\n" 1>&3
297}
298
299function ask {
300	typeset question=$1
301	typeset default_answer=$2
302
303	if [[ -z $default_answer ]]; then
304		printf "$question :"
305	else
306		printf "$question [$default_answer]: "
307	fi
308	read answer
309	test -z "$answer" && answer="$default_answer"
310}
311
312function yesno {
313	typeset question="$1"
314
315	answer=
316	yn=`printf "$(gettext "y/n")"`
317	y=`printf "$(gettext "y")"`
318	n=`printf "$(gettext "n")"`
319	yes=`printf "$(gettext "yes")"`
320	no=`printf "$(gettext "no")"`
321
322	while [[ -z $answer ]]; do
323		ask "$question" $yn
324		case $answer in
325			$y|$yes)	answer=yes;;
326			$n|$no)		answer=no;;
327			*)		answer=;;
328		esac
329	done
330}
331
332function query {
333	yesno "$*"
334
335	if [[ $answer == no ]]; then
336		printf "\t$(gettext "No action performed").\n"
337	fi
338}
339
340
341function read_profile {
342	typeset param value
343	typeset file="$1"
344
345	if [[ ! -d $file && -r $file ]]; then
346		while read param value
347		do
348			case $param in
349			REALM)  if [[ -z $realm ]]; then
350					realm="$value"
351					checkval="REALM"; check_value $realm
352				fi
353				;;
354			KDC)    if [[ -z $KDC ]]; then
355					KDC="$value"
356					checkval="KDC"; check_value $KDC
357				fi
358				;;
359			ADMIN)  if [[ -z $ADMIN_PRINC ]]; then
360					ADMIN_PRINC="$value"
361					checkval="ADMIN_PRINC"
362    					check_value $ADMIN_PRINC
363				fi
364				;;
365			FILEPATH)  if [[ -z $filepath ]]; then
366					filepath="$value"
367				   fi
368				   ;;
369			NFS)    if [[ -z $add_nfs ]]; then
370				    if [[ $value == 1 ]]; then
371					    add_nfs=yes
372				    else
373					    add_nfs=no
374				    fi
375				fi
376				;;
377			NOKEY)    if [[ -z $no_keytab ]]; then
378				    if [[ $value == 1 ]]; then
379					    no_keytab=yes
380				    else
381					    no_keytab=no
382				    fi
383				fi
384				;;
385			NOSOL)  if [[ -z $non_solaris ]]; then
386				    if [[ $value == 1 ]]; then
387					    non_solaris=yes
388					    no_keytab=yes
389				    else
390					    non_solaris=no
391				    fi
392				fi
393				;;
394			LHN)    if [[ -z $logical_hn ]]; then
395					logical_hn="$value"
396					checkval="LOGICAL_HOSTNAME"
397    					check_value $logical_hn
398				fi
399				;;
400			DNSLOOKUP) if [[ -z $dnsarg ]]; then
401					dnsarg="$value"
402					checkval="DNS_OPTIONS"
403					check_value $dnsarg
404				   fi
405				   ;;
406			FQDN) if [[ -z $fqdnlist ]]; then
407					fqdnlist="$value"
408					checkval="FQDN"
409					check_value $fqdnlist
410					verify_fqdnlist "$fqdnlist"
411			      fi
412			      ;;
413			MSAD) if [[ -z $msad ]]; then
414				if [[ $value == 1 ]]; then
415					msad=yes
416					non_solaris=yes
417				else
418					msad=no
419				fi
420			      fi
421			      ;;
422			esac
423		done <$file
424	else
425		printf "\n$(gettext "The kclient profile \`%s' is not valid, exiting").\n" $file >&2
426		error_message
427	fi
428}
429
430function ping_check {
431	typeset machine="$1"
432	typeset string="$2"
433
434	if ping $machine 2 > /dev/null 2>&1; then
435		:
436	else
437		printf "\n$(gettext "%s %s is unreachable, exiting").\n" $string $machine >&2
438		error_message
439	fi
440
441	# Output timesync warning if not using a profile, i.e. in
442	# interactive mode.
443	if [[ -z $profile && $string == KDC ]]; then
444		# It's difficult to sync up time with KDC esp. if in a
445		# zone so just print a warning about KDC time sync.
446		printf "\n$(gettext "Note, this system and the KDC's time must be within 5 minutes of each other for Kerberos to function").\n" >&2
447		printf "$(gettext "Both systems should run some form of time synchronization system like Network Time Protocol (NTP)").\n" >&2
448break
449	fi
450}
451
452function check_value {
453	typeset arg="$1"
454
455	if [[ -z $arg ]]; then
456		printf "\n$(gettext "No input obtained for %s, exiting").\n" $checkval >&2
457		error_message
458	else
459		echo "$arg" > $TMP_FILE
460		if egrep -s '[*$^#!]+' $TMP_FILE; then
461			printf "\n$(gettext "Invalid input obtained for %s, exiting").\n" $checkval >&2
462			error_message
463		fi
464	fi
465}
466
467function set_dns_value {
468	typeset -l arg="$1"
469
470	if [[ $arg == dns_lookup_kdc  ||  $arg == dns_lookup_realm  || $arg == dns_fallback ]]; then
471		dns_lookup=yes
472	else
473		if [[ $arg == none ]]; then
474			dns_lookup=no
475		else
476			printf "\n$(gettext "Invalid DNS lookup option, exiting").\n" >&2
477			error_message
478		fi
479	fi
480}
481
482function verify_kdcs {
483	typeset k_list="$1"
484	typeset -l kdc
485	typeset list fqhn f_list
486
487	kdc_list=$(echo "$k_list" | sed 's/,/ /g')
488
489	if [[ -z $k_list ]]; then
490		printf "\n$(gettext "At least one KDC should be listed").\n\n" >&2
491		usage
492	fi
493
494	for kdc in $k_list; do
495		if [[ $kdc != $KDC ]]; then
496			list="$list $kdc"
497			fkdc=`$KLOOKUP $kdc`
498			if ping $fkdc 2 > /dev/null; then
499				:
500			else
501				printf "\n$(gettext "%s %s is unreachable, no action performed").\n" "KDC" $fkdc >&2
502			fi
503			f_list="$f_list $fkdc"
504		fi
505	done
506
507	fkdc_list="$f_list"
508	kdc_list="$list"
509}
510
511function parse_service {
512	typeset service_list=$1
513
514	service_list=${service_list//,/ }
515	for service in $service_list; do
516		svc=${service%:}
517		auth_type=${service#:}
518		[[ -z $svc || -z $auth_type ]] && return
519		print -- $svc $auth_type
520	done
521}
522
523function verify_fqdnlist {
524	typeset list="$1"
525	typeset -l hostname
526	typeset -i count=1
527	typeset fqdnlist eachfqdn tmpvar fullhost
528
529	list=$(echo "$list" | tr -d " " | tr -d "\t")
530	hostname=$(uname -n | cut -d"." -f1)
531	fqdnlist=$client_machine
532
533	eachfqdn=$(echo "$list" | cut -d"," -f$count)
534	if [[ -z $eachfqdn ]]; then
535		printf "\n$(gettext "If the -f option is used, at least one FQDN should be listed").\n\n" >&2
536		usage
537	else
538		while [[ ! -z $eachfqdn ]]; do
539			tmpvar=$(echo "$eachfqdn" | cut -d"." -f1)
540			if [[ -z $tmpvar ]]; then
541				fullhost="$hostname$eachfqdn"
542			else
543				fullhost="$hostname.$eachfqdn"
544			fi
545
546			ping_check $fullhost $(gettext "System")
547			if [[ $fullhost == $client_machine ]]; then
548				:
549			else
550				fqdnlist="$fqdnlist $fullhost"
551			fi
552
553			if [[ $list == *,* ]]; then
554				((count = count + 1))
555				eachfqdn=$(echo "$list" | cut -d"," -f$count)
556			else
557				break
558			fi
559		done
560	fi
561}
562
563function setup_keytab {
564	typeset cname ask_fqdns current_release
565
566	#
567	# 1. kinit with ADMIN_PRINC
568	#
569
570	if [[ -z $ADMIN_PRINC ]]; then
571		printf "\n$(gettext "Enter the krb5 administrative principal to be used"): "
572		read ADMIN_PRINC
573		checkval="ADMIN_PRINC"; check_value $ADMIN_PRINC
574	fi
575
576	echo "$ADMIN_PRINC">$TMP_FILE
577
578	[[ -n $msad ]] && return
579	if egrep -s '\/admin' $TMP_FILE; then
580		# Already in "/admin" format, do nothing
581		:
582	else
583		if egrep -s '\/' $TMP_FILE; then
584			printf "\n$(gettext "Improper entry for krb5 admin principal, exiting").\n" >&2
585			error_message
586		else
587			ADMIN_PRINC=$(echo "$ADMIN_PRINC/admin")
588		fi
589	fi
590
591	printf "$(gettext "Obtaining TGT for %s") ...\n" $ADMIN_PRINC
592
593	cname=$(canon_resolve $KDC)
594	if [[ -n $cname ]]; then
595		kinit -S kadmin/$cname $ADMIN_PRINC
596	else
597		kinit -S kadmin/$FKDC $ADMIN_PRINC
598	fi
599	klist 1>$TMP_FILE 2>&1
600	if egrep -s "$(gettext "Valid starting")" $TMP_FILE && egrep -s "kadmin/$FKDC@$realm" $TMP_FILE; then
601    		:
602	else
603		printf "\n$(gettext "kinit of %s failed, exiting").\n" $ADMIN_PRINC >&2
604		error_message
605	fi
606
607	#
608	# 2. Do we want to create and/or add service principal(s) for fqdn's
609	#    other than the one listed in resolv.conf(4) ?
610	#
611	if [[ -z $options ]]; then
612		query "$(gettext "Do you have multiple DNS domains spanning the Kerberos realm") $realm ?"
613		ask_fqdns=$answer
614		if [[ $ask_fqdns == yes ]]; then
615			printf "$(gettext "Enter a comma-separated list of DNS domain names"): "
616			read fqdnlist
617			verify_fqdnlist "$fqdnlist"
618		else
619			fqdnlist=$client_machine
620		fi
621	else
622		if [[ -z $fqdnlist ]]; then
623			fqdnlist=$client_machine
624		fi
625	fi
626
627	if [[ $add_nfs == yes ]]; then
628		echo; call_kadmin nfs
629	fi
630
631	# Add the host entry to the keytab
632	echo; call_kadmin host
633
634}
635
636function setup_lhn {
637	typeset -l logical_hn
638
639	echo "$logical_hn" > $TMP_FILE
640	if egrep -s '[^.]\.[^.]+$' $TMP_FILE; then
641		# do nothing, logical_hn is in fqdn format
642		:
643	else
644		if egrep -s '\.+' $TMP_FILE; then
645			printf "\n$(gettext "Improper format of logical hostname, exiting").\n" >&2
646			error_message
647		else
648			# Attach fqdn to logical_hn, to get the Fully Qualified
649			# Host Name of the client requested
650			logical_hn=$(echo "$logical_hn.$fqdn")
651		fi
652	fi
653
654	client_machine=$logical_hn
655
656	ping_check $client_machine $(gettext "System")
657}
658
659function usage {
660	printf "\n$(gettext "Usage: kclient [ options ]")\n" >&2
661	printf "\t$(gettext "where options are any of the following")\n\n" >&2
662	printf "\t$(gettext "[ -D domain_list ]  configure a client that has mul
663tiple mappings of doamin and/or hosts to the default realm")\n" >&2
664	printf "\t$(gettext "[ -K ]  configure a client that does not have host/service keys")\n" >&2
665	printf "\t$(gettext "[ -R realm ]  specifies the realm to use")\n" >&2
666	printf "\t$(gettext "[ -T kdc_vendor ]  specifies which KDC vendor is the server")\n" >&2
667	printf "\t$(gettext "[ -a adminuser ]  specifies the Kerberos administrator")\n" >&2
668	printf "\t$(gettext "[ -c filepath ]  specifies the krb5.conf path used to configure this client")\n" >&2
669	printf "\t$(gettext "[ -d dnsarg ]  specifies which information should be looked up in DNS (dns_lookup_kdc, dns_lookup_realm, and dns_fallback)")\n" >&2
670	printf "\t$(gettext "[ -f fqdn_list ]  specifies which domains to configure host keys for this client")\n" >&2
671	printf "\t$(gettext "[ -h logicalhostname ]  configure the logical host name for a client that is in a cluster")\n" >&2
672	printf "\t$(gettext "[ -k kdc_list ]  specify multiple KDCs, if -m is not used the first KDC in the list is assumed to be the master.  KDC host names are used verbatim.")\n" >&2
673	printf "\t$(gettext "[ -m master ]  master KDC server host name")\n" >&2
674	printf "\t$(gettext "[ -n ]  configure client to be an NFS client")\n" >&2
675	printf "\t$(gettext "[ -p profile ]  specifies which profile file to use to configure this client")\n" >&2
676	printf "\t$(gettext "[ -s pam_list ]  update the service for Kerberos authentication")\n" >&2
677	error_message
678}
679
680function discover_domain {
681	typeset dom DOMs
682
683	if [[ -z $realm ]]; then
684		set -A DOMs -- `$KLOOKUP _ldap._tcp.dc._msdcs S`
685	else
686		set -A DOMs -- `$KLOOKUP _ldap._tcp.dc._msdcs.$realm S`
687	fi
688
689	[[ -z ${DOMs[0]} ]] && return 1
690
691	dom=${DOMs[0]}
692
693	dom=${dom#*.}
694	dom=${dom% *}
695
696	domain=$dom
697
698	return 0
699}
700
701function check_nss_hosts_or_ipnodes_config {
702	typeset backend
703
704	for backend in $1
705	do
706		[[ $backend == dns ]] && return 0
707	done
708	return 1
709}
710
711function check_nss_conf {
712	typeset i j hosts_config
713
714	for i in hosts ipnodes
715	do
716		grep "^${i}:" /etc/nsswitch.conf|read j hosts_config
717		check_nss_hosts_or_ipnodes_config "$hosts_config" || return 1
718	done
719
720	return 0
721}
722
723function canon_resolve {
724	typeset name ip
725
726	name=`$KLOOKUP $1 C`
727	[[ -z $name ]] && name=`$KLOOKUP $1 A`
728	[[ -z $name ]] && return
729
730	ip=`$KLOOKUP $name I`
731	[[ -z $ip ]] && return
732	for i in $ip
733	do
734		if ping $i 2 > /dev/null 2>&1; then
735			break
736		else
737			i=
738		fi
739	done
740
741	cname=`$KLOOKUP $ip P`
742	[[ -z $cname ]] && return
743
744	print -- "$cname"
745}
746
747function rev_resolve {
748	typeset name ip
749
750	ip=`$KLOOKUP $1 I`
751
752	[[ -z $ip ]] && return
753	name=`$KLOOKUP $ip P`
754	[[ -z $name ]] && return
755
756	print -- $name
757}
758
759# Convert an AD-style domain DN to a DNS domainname
760function dn2dns {
761	typeset OIFS dname dn comp components
762
763	dn=$1
764	dname=
765
766	OIFS="$IFS"
767	IFS=,
768	set -A components -- $1
769	IFS="$OIFS"
770
771	for comp in "${components[@]}"
772	do
773		[[ "$comp" == [dD][cC]=* ]] || continue
774		dname="$dname.${comp#??=}"
775	done
776
777	print ${dname#.}
778}
779
780# Form a base DN from a DNS domainname and container
781function getBaseDN {
782	if [[ -n "$2" ]]
783	then
784		baseDN="CN=$1,$(dns2dn $2)"
785	else
786		baseDN="$(dns2dn $2)"
787	fi
788}
789
790# Convert a DNS domainname to an AD-style DN for that domain
791function dns2dn {
792	typeset OIFS dn labels
793
794	OIFS="$IFS"
795	IFS=.
796	set -A labels -- $1
797	IFS="$OIFS"
798
799	dn=
800	for label in "${labels[@]}"
801	do
802		dn="${dn},DC=$label"
803	done
804
805	print -- "${dn#,}"
806}
807
808function getSRVs {
809	typeset srv port
810
811	$KLOOKUP $1 S | while read srv port
812	do
813		if ping $srv 2 > /dev/null 2>&1; then
814			print -- $srv $port
815		fi
816	done
817}
818
819function getKDC {
820	typeset j
821
822	set -A KPWs -- $(getSRVs _kpasswd._tcp.$dom.)
823	kpasswd=${KPWs[0]}
824
825	if [[ -n $siteName ]]
826	then
827		set -A KDCs -- $(getSRVs _kerberos._tcp.$siteName._sites.$dom.)
828		kdc=${KDCs[0]}
829		[[ -n $kdc ]] && return
830	fi
831
832	# No site name
833	set -A KDCs -- $(getSRVs _kerberos._tcp.$dom.)
834	kdc=${KDCs[0]}
835	[[ -n $kdc ]] && return
836
837	# Default
838	set -A KDCs -- $DomainDnsZones 88
839	kdc=$ForestDnsZones
840}
841
842function getDC {
843	typeset j
844
845	if [[ -n $siteName ]]
846	then
847		set -A DCs -- $(getSRVs _ldap._tcp.$siteName._sites.dc._msdcs.$dom.)
848		dc=${DCs[0]}
849		[[ -n $dc ]] && return
850	fi
851
852	# No site name
853	set -A DCs -- $(getSRVs _ldap._tcp.dc._msdcs.$dom.)
854	dc=${DCs[0]}
855	[[ -n $dc ]] && return
856
857	# Default
858	set -A DCs -- $DomainDnsZones 389
859	dc=$DomainDnsZones
860}
861
862function write_ads_krb5conf {
863	typeset kdcs
864
865	printf "\n$(gettext "Setting up %s").\n\n" $KRB5_CONFIG_FILE
866
867	for i in ${KDCs[@]}
868	do
869		[[ $i == +([0-9]) ]] && continue
870		if [[ -n $kdcs ]]
871		then
872			kdcs="$kdcs,$i"
873		else
874			kdcs=$i
875		fi
876	done
877
878	$KCONF -f $KRB5_CONFIG -r $realm -k $kdcs -m $KDC -p SET_CHANGE -d .$dom
879
880	if [[ $? -ne 0 ]]; then
881		printf "\n$(gettext "Can not update %s, exiting").\n" $KRB5_CONFIG >&2
882		error_message
883	fi
884}
885
886function getForestName {
887	ldapsearch -R -T -h $dc $ldap_args \
888	    -b "" -s base "" schemaNamingContext| \
889		grep ^schemaNamingContext|read j schemaNamingContext
890
891	if [[ $? -ne 0 ]]; then
892		printf "$(gettext "Can't find forest").\n" >&2
893		error_message
894	fi
895	schemaNamingContext=${schemaNamingContext#CN=Schema,CN=Configuration,}
896
897	[[ -z $schemaNamingContext ]] && return 1
898
899	forest=
900	while [[ -n $schemaNamingContext ]]
901	do
902		schemaNamingContext=${schemaNamingContext#DC=}
903		forest=${forest}.${schemaNamingContext%%,*}
904		[[ "$schemaNamingContext" = *,* ]] || break
905		schemaNamingContext=${schemaNamingContext#*,}
906	done
907	forest=${forest#.}
908}
909
910function getGC {
911	typeset j
912
913	[[ -n $gc ]] && return 0
914
915	if [[ -n $siteName ]]
916	then
917		set -A GCs -- $(getSRVs _ldap._tcp.$siteName._sites.gc._msdcs.$forest.)
918		gc=${GCs[0]}
919		[[ -n $gc ]] && return
920	fi
921
922	# No site name
923	set -A GCs -- $(getSRVs _ldap._tcp.gc._msdcs.$forest.)
924	gc=${GCs[0]}
925	[[ -n $gc ]] && return
926
927	# Default
928	set -A GCs -- $ForestDnsZones 3268
929	gc=$ForestDnsZones
930}
931
932#
933# The local variables used to calculate the IP address are of type unsigned
934# integer (-ui), as this is required to restrict the integer to 32b.
935# Starting in ksh88, Solaris has incorrectly assummed that -i represents 64b.
936#
937function ipAddr2num {
938	typeset OIFS
939	typeset -ui16 num
940
941	if [[ "$1" != +([0-9]).+([0-9]).+([0-9]).+([0-9]) ]]
942	then
943		print 0
944		return 0
945	fi
946
947	OIFS="$IFS"
948	IFS=.
949	set -- $1
950	IFS="$OIFS"
951
952	num=$((${1}<<24 | ${2}<<16 | ${3}<<8 | ${4}))
953
954	print -- $num
955}
956
957#
958# The local variables used to calculate the IP address are of type unsigned
959# integer (-ui), as this is required to restrict the integer to 32b.
960# Starting in ksh88, Solaris has incorrectly assummed that -i represents 64b.
961#
962function num2ipAddr {
963	typeset -ui16 num
964	typeset -ui10 a b c d
965
966	num=$1
967	a=$((num>>24        ))
968	b=$((num>>16 & 16#ff))
969	c=$((num>>8  & 16#ff))
970	d=$((num     & 16#ff))
971	print -- $a.$b.$c.$d
972}
973
974#
975# The local variables used to calculate the IP address are of type unsigned
976# integer (-ui), as this is required to restrict the integer to 32b.
977# Starting in ksh88, Solaris has incorrectly assummed that -i represents 64b.
978#
979function netmask2length {
980	typeset -ui16 netmask
981	typeset -i len
982
983	netmask=$1
984	len=32
985	while [[ $((netmask % 2)) -eq 0 ]]
986	do
987		netmask=$((netmask>>1))
988		len=$((len - 1))
989	done
990	print $len
991}
992
993#
994# The local variables used to calculate the IP address are of type unsigned
995# integer (-ui), as this is required to restrict the integer to 32b.
996# Starting in ksh88, Solaris has incorrectly assummed that -i represents 64b.
997#
998function getSubnets {
999	typeset -ui16 addr netmask
1000	typeset -ui16 classa=16\#ff000000
1001
1002	ifconfig -a|while read line
1003	do
1004		addr=0
1005		netmask=0
1006		set -- $line
1007		[[ $1 == inet ]] || continue
1008		while [[ $# -gt 0 ]]
1009		do
1010			case "$1" in
1011				inet) addr=$(ipAddr2num $2); shift;;
1012				netmask) eval netmask=16\#$2; shift;;
1013				*) :;
1014			esac
1015			shift
1016		done
1017
1018		[[ $addr -eq 0 || $netmask -eq 0 ]] && continue
1019		[[ $((addr & classa)) -eq 16\#7f000000 ]] && continue
1020
1021		print $(num2ipAddr $((addr & netmask)))/$(netmask2length $netmask)
1022	done
1023}
1024
1025function getSite {
1026	typeset subnet siteDN j ldapsrv subnet_dom
1027
1028	eval "[[ -n \"\$siteName\" ]]" && return
1029	for subnet in $(getSubnets)
1030	do
1031		ldapsearch -R -T -h $dc $ldap_args \
1032		    -p 3268 -b "" -s sub cn=$subnet dn |grep ^dn|read j subnetDN
1033
1034		[[ -z $subnetDN ]] && continue
1035		subnet_dom=$(dn2dns $subnetDN)
1036		ldapsrv=$(canon_resolve DomainDnsZones.$subnet_dom)
1037		[[ -z $ldapsrv ]] && continue
1038		ldapsearch -R -T -h $ldapsrv $ldap_args \
1039		    -b "$subnetDN" -s base "" siteObject \
1040		    |grep ^siteObject|read j siteDN
1041
1042		[[ -z $siteDN ]] && continue
1043
1044		eval siteName=${siteDN%%,*}
1045		eval siteName=\${siteName#CN=}
1046		return
1047	done
1048}
1049
1050function doKRB5config {
1051	[[ -f $KRB5_CONFIG_FILE ]] && \
1052		cp $KRB5_CONFIG_FILE ${KRB5_CONFIG_FILE}-pre-kclient
1053
1054	[[ -f $KRB5_KEYTAB_FILE ]] && \
1055		cp $KRB5_KEYTAB_FILE ${KRB5_KEYTAB_FILE}-pre-kclient
1056
1057	[[ -s $KRB5_CONFIG ]] && cp $KRB5_CONFIG $KRB5_CONFIG_FILE
1058	[[ -s $KRB5_CONFIG_FILE ]] && chmod 0644 $KRB5_CONFIG_FILE
1059	[[ -s $new_keytab ]] && cp $new_keytab $KRB5_KEYTAB_FILE
1060	[[ -s $KRB5_KEYTAB_FILE ]] && chmod 0600 $KRB5_KEYTAB_FILE
1061}
1062
1063function addDNSRR {
1064	smbFMRI=svc:/network/smb/server:default
1065	ddnsProp=smbd/ddns_enable
1066	enProp=general/enabled
1067
1068	enabled=`svcprop -p $enProp $smbFMRI`
1069	ddns_enable=`svcprop -p $ddnsProp $smbFMRI`
1070
1071	if [[ $enabled == true && $ddns_enable != true ]]; then
1072		printf "$(gettext "Warning: won't create DNS records for client").\n"
1073		printf "$(gettext "%s property not set to 'true' for the %s FMRI").\n" $ddnsProp $smbFMRI
1074		return
1075	fi
1076
1077	# Destroy any existing ccache as GSS_C_NO_CREDENTIAL will pick up any
1078	# residual default credential in the cache.
1079	kdestroy > /dev/null 2>&1
1080
1081	$KDYNDNS -d $1 > /dev/null 2>&1
1082	if [[ $? -ne 0 ]]; then
1083		#
1084		# Non-fatal, we should carry-on as clients may resolve to
1085		# different servers and the client could already exist there.
1086		#
1087		printf "$(gettext "Warning: unable to create DNS records for client").\n"
1088		printf "$(gettext "This could mean that '%s' is not included as a 'nameserver' in the /etc/resolv.conf file or some other type of error").\n" $dc
1089	fi
1090}
1091
1092function setSMB {
1093	typeset domain=$1
1094	typeset server=$2
1095	smbFMRI=svc:/network/smb/server
1096
1097	printf "%s" "$newpw" | $KSMB -d $domain -s $server
1098	if [[ $? -ne 0 ]]; then
1099		printf "$(gettext "Warning: unable to set %s domain, server and password information").\n" $smbFMRI
1100		return
1101	fi
1102
1103	svcadm restart $smbFMRI > /dev/null 2>&1
1104	if [[ $? -ne 0 ]]; then
1105		printf "$(gettext "Warning: unable to restart %s").\n" $smbFMRI
1106	fi
1107}
1108
1109function compareDomains {
1110	typeset oldDom hspn newDom=$1
1111
1112	# If the client has been previously configured in a different
1113	# realm/domain then we need to prompt the user to see if they wish to
1114	# switch domains.
1115	klist -k 2>&1 | grep @ | read j hspn
1116	[[ -z $hspn ]] && return
1117
1118	oldDom=${hspn#*@}
1119	if [[ $oldDom != $newDom ]]; then
1120		printf "$(gettext "The client is currently configured in a different domain").\n"
1121		printf "$(gettext "Currently in the '%s' domain, trying to join the '%s' domain").\n" $oldDom $newDom
1122		query "$(gettext "Do you want the client to join a new domain") ?"
1123		printf "\n"
1124		if [[ $answer != yes ]]; then
1125			printf "$(gettext "Client will not be joined to the new domain").\n" >&2
1126			error_message
1127		fi
1128	fi
1129}
1130
1131function getKDCDC {
1132
1133	getKDC
1134	if [[ -n $kdc ]]; then
1135		KDC=$kdc
1136		dc=$kdc
1137	else
1138		getDC
1139		if [[ -n $dc ]]; then
1140			KDC=$dc
1141		else
1142			printf "$(gettext "Could not find domain controller server for '%s'.  Exiting").\n" $realm >&2
1143			error_message
1144		fi
1145	fi
1146}
1147
1148function gen_rand {
1149	typeset -u hex
1150
1151	dd if=/dev/random bs=1 count=1 2>/dev/null | od -A n -tx1 | read hex
1152
1153	printf %s $((16#$hex))
1154}
1155
1156function join_domain {
1157	typeset -u upcase_nodename
1158	typeset -l locase_nodename
1159	typeset -L15 string15
1160	typeset netbios_nodename fqdn
1161
1162	container=Computers
1163	ldap_args="-o authzid= -o mech=gssapi"
1164	userAccountControlBASE=4096
1165
1166	if [[ -z $ADMIN_PRINC ]]; then
1167		cprinc=Administrator
1168	else
1169		cprinc=$ADMIN_PRINC
1170	fi
1171
1172	if ! discover_domain; then
1173		printf "$(gettext "Can not find realm") '%s'.\n" $realm >&2
1174		error_message
1175	fi
1176
1177	dom=$domain
1178	realm=$domain
1179
1180	if [[ ${#hostname} -gt 15 ]]; then
1181		string15=$hostname
1182		upcase_nodename=$string15
1183		locase_nodename=$string15
1184	else
1185		upcase_nodename=$hostname
1186		locase_nodename=$hostname
1187	fi
1188
1189	netbios_nodename="${upcase_nodename}\$"
1190	fqdn=$hostname.$domain
1191	upn=host/${fqdn}@${realm}
1192
1193	grep=/usr/xpg4/bin/grep
1194
1195	object=$(mktemp -q -t kclient-computer-object.XXXXXX)
1196	if [[ -z $object ]]; then
1197		printf "\n$(gettext "Can not create temporary file, exiting").\n
1198" >&2
1199		error_message
1200        fi
1201
1202	grep=/usr/xpg4/bin/grep
1203
1204	modify_existing=false
1205	recreate=false
1206
1207	DomainDnsZones=$(rev_resolve DomainDnsZones.$dom.)
1208	ForestDnsZones=$(rev_resolve ForestDnsZones.$dom.)
1209
1210	getBaseDN "$container" "$dom"
1211
1212	if [[ -n $KDC ]]; then
1213		dc=$KDC
1214	else
1215		getKDCDC
1216	fi
1217
1218	write_ads_krb5conf
1219
1220	printf "$(gettext "Attempting to join '%s' to the '%s' domain").\n\n" $upcase_nodename $realm
1221
1222	kinit $cprinc@$realm
1223	if [[ $? -ne 0 ]]; then
1224		printf "$(gettext "Could not authenticate %s.  Exiting").\n" $cprinc@$realm >&2
1225		error_message
1226	fi
1227
1228	if getForestName
1229	then
1230		printf "\n$(gettext "Forest name found: %s")\n\n" $forest
1231	else
1232		printf "\n$(gettext "Forest name not found, assuming forest is the domain name").\n"
1233	fi
1234
1235	getGC
1236	getSite
1237
1238	if [[ -z $siteName ]]
1239	then
1240    		printf "$(gettext "Site name not found.  Local DCs/GCs will not be discovered").\n\n"
1241	else
1242    		printf "$(gettext "Looking for _local_ KDCs, DCs and global catalog servers (SRV RRs)").\n"
1243		getKDCDC
1244		getGC
1245
1246		write_ads_krb5conf
1247	fi
1248
1249	if [[ ${#GCs} -eq 0 ]]; then
1250		printf "$(gettext "Could not find global catalogs.  Exiting").\n" >&2
1251		error_message
1252	fi
1253
1254	# Check to see if the client is transitioning between domains.
1255	compareDomains $realm
1256
1257	# Here we check domainFunctionality to see which release:
1258	# 0, 1, 2: Windows 2000, 2003 Interim, 2003 respecitively
1259	# 3: Windows 2008
1260	level=0
1261	ldapsearch -R -T -h "$dc" $ldap_args -b "" -s base "" \
1262	 domainControllerFunctionality| grep ^domainControllerFunctionality| \
1263	 read j level
1264	if [[ $? -ne 0 ]]; then
1265		printf "$(gettext "Search for domain functionality failed, exiting").\n" >&2
1266		error_message
1267	fi
1268
1269	if ldapsearch -R -T -h "$dc" $ldap_args -b "$baseDN" \
1270	    -s sub sAMAccountName="$netbios_nodename" dn > /dev/null 2>&1
1271	then
1272		:
1273	else
1274		printf "$(gettext "Search for node failed, exiting").\n" >&2
1275		error_message
1276	fi
1277	ldapsearch -R -T -h "$dc" $ldap_args -b "$baseDN" -s sub \
1278	    sAMAccountName="$netbios_nodename" dn|grep "^dn:"|read j dn
1279
1280	if [[ -z $dn ]]; then
1281		: # modify_existing is already false, which is what we want.
1282	else
1283		printf "$(gettext "Computer account '%s' already exists in the '%s' domain").\n" $upcase_nodename $realm
1284		query "$(gettext "Do you wish to recreate this computer account") ?"
1285		printf "\n"
1286		if [[ $answer == yes ]]; then
1287			recreate=true
1288		else
1289			modify_existing=true
1290		fi
1291	fi
1292
1293	if [[ $modify_existing == false && -n $dn ]]; then
1294		query "$(gettext "Would you like to delete any sub-object found for this computer account") ?"
1295		if [[ $answer == yes ]]; then
1296			printf "$(gettext "Looking to see if the machine account contains other objects")...\n"
1297			ldapsearch -R -T -h "$dc" $ldap_args -b "$dn" -s sub "" dn | while read j sub_dn
1298			do
1299				[[ $j != dn: || -z $sub_dn || $dn == $sub_dn ]] && continue
1300				if $recreate; then
1301					printf "$(gettext "Deleting the following object: %s")\n" ${sub_dn#$dn}
1302					ldapdelete -h "$dc" $ldap_args "$sub_dn" > /dev/null 2>&1
1303					if [[ $? -ne 0 ]]; then
1304						printf "$(gettext "Error in deleting object: %s").\n" ${sub_dn#$dn}
1305					fi
1306				else
1307					printf "$(gettext "The following object will not be deleted"): %s\n" ${sub_dn#$dn}
1308				fi
1309			done
1310		fi
1311
1312		if $recreate; then
1313			ldapdelete -h "$dc" $ldap_args "$dn" > /dev/null 2>&1
1314			if [[ $? -ne 0 ]]; then
1315				printf "$(gettext "Error in deleting object: %s").\n" ${sub_dn#$dn} >&2
1316				error_message
1317			fi
1318		elif $modify_existing; then
1319			: # Nothing to delete
1320		else
1321			printf "$(gettext "A machine account already exists").\n" >&2
1322			error_message
1323		fi
1324	fi
1325
1326	[[ -z $dn ]] && dn="CN=${upcase_nodename},${baseDN}"
1327	if $modify_existing; then
1328		cat > "$object" <<EOF
1329dn: $dn
1330changetype: modify
1331replace: userPrincipalName
1332userPrincipalName: $upn
1333-
1334replace: servicePrincipalName
1335servicePrincipalName: host/${fqdn}
1336-
1337replace: userAccountControl
1338userAccountControl: $((userAccountControlBASE + 32 + 2))
1339-
1340replace: dNSHostname
1341dNSHostname: ${fqdn}
1342EOF
1343
1344		printf "$(gettext "A machine account already exists; updating it").\n"
1345		ldapadd -h "$dc" $ldap_args -f "$object" > /dev/null 2>&1
1346		if [[ $? -ne 0 ]]; then
1347			printf "$(gettext "Failed to modify the AD object via LDAP").\n" >&2
1348			error_message
1349		fi
1350	else
1351		dn="CN=${upcase_nodename},${baseDN}"
1352		cat > "$object" <<EOF
1353dn: $dn
1354objectClass: computer
1355cn: $upcase_nodename
1356sAMAccountName: ${netbios_nodename}
1357userPrincipalName: $upn
1358servicePrincipalName: host/${fqdn}
1359userAccountControl: $((userAccountControlBASE + 32 + 2))
1360dNSHostname: ${fqdn}
1361EOF
1362
1363		printf "$(gettext "Creating the machine account in AD via LDAP").\n\n"
1364
1365		ldapadd -h "$dc" $ldap_args -f "$object" > /dev/null 2>&1
1366		if [[ $? -ne 0 ]]; then
1367			printf "$(gettext "Failed to create the AD object via LDAP").\n" >&2
1368			error_message
1369		fi
1370	fi
1371
1372	# Generate a new password for the new account
1373	MAX_PASS=120
1374        i=0
1375
1376	# first check to see if /dev/random exists to generate a new password
1377	if [[ ! -h /dev/random ]]; then
1378		printf "$(gettext "/dev/random does not exist").\n" >&2
1379		error_message
1380	fi
1381
1382	while ((MAX_PASS > i))
1383	do
1384		# [MS-DISO] A machine password is an ASCII string of randomly
1385		# chosen characters. Each character's ASCII code is between 32
1386		# and 122 inclusive.
1387		c=$(printf "\\$(printf %o $(($(gen_rand) % 91 + 32)))\n")
1388		p="$p$c"
1389		((i+=1))
1390	done
1391
1392	newpw=$p
1393	if [[ ${#newpw} -ne MAX_PASS ]]; then
1394		printf "$(gettext "Password created was of incorrect length").\n" >&2
1395		error_message
1396	fi
1397
1398	# Set the new password
1399	printf "%s" "$newpw" | $KSETPW ${netbios_nodename}@${realm} > /dev/null 2>&1
1400	if [[ $? -ne 0 ]]
1401	then
1402		printf "$(gettext "Failed to set account password").\n" >&2
1403		error_message
1404	fi
1405
1406	# Lookup the new principal's kvno:
1407	ldapsearch -R -T -h "$dc" $ldap_args -b "$baseDN" \
1408		 -s sub cn=$upcase_nodename msDS-KeyVersionNumber| \
1409		grep "^msDS-KeyVersionNumber"|read j kvno
1410	[[ -z $kvno ]] && kvno=1
1411
1412	# Set supported enctypes.  This only works for Longhorn/Vista, so we
1413	# ignore errors here.
1414	userAccountControl=$((userAccountControlBASE + 524288 + 65536))
1415	set -A enctypes --
1416
1417	# Do we have local support for AES?
1418	encrypt -l|grep ^aes|read j minkeysize maxkeysize
1419	val=
1420	if [[ $maxkeysize -eq 256 ]]; then
1421		val=16
1422		enctypes[${#enctypes[@]}]=aes256-cts-hmac-sha1-96
1423	fi
1424	if [[ $minkeysize -eq 128 ]]; then
1425		((val=val+8))
1426		enctypes[${#enctypes[@]}]=aes128-cts-hmac-sha1-96
1427	fi
1428
1429	# RC4 comes next (whether it's better than 1DES or not -- AD prefers it)
1430	if encrypt -l|$grep -q ^arcfour
1431	then
1432		((val=val+4))
1433		enctypes[${#enctypes[@]}]=arcfour-hmac-md5
1434	else
1435		# Use 1DES ONLY if we don't have arcfour
1436		userAccountControl=$((userAccountControl + 2097152))
1437	fi
1438	if encrypt -l | $grep -q ^des
1439	then
1440		((val=val+2))
1441		enctypes[${#enctypes[@]}]=des-cbc-md5
1442	fi
1443
1444	if [[ ${#enctypes[@]} -eq 0 ]]
1445	then
1446		printf "$(gettext "No enctypes are supported").\n"
1447		printf "$(gettext "Please enable arcfour or 1DES, then re-join; see cryptoadm(1M)").\n" >&2
1448		error_message
1449	fi
1450
1451	# If domain crontroller is Longhorn or above then set new supported
1452	# encryption type attributes.
1453	if [[ $level -gt 2 ]]; then
1454		cat > "$object" <<EOF
1455dn: $dn
1456changetype: modify
1457replace: msDS-SupportedEncryptionTypes
1458msDS-SupportedEncryptionTypes: $val
1459EOF
1460		ldapmodify -h "$dc" $ldap_args -f "$object" >/dev/null 2>&1
1461		if [[ $? -ne 0 ]]; then
1462			printf "$(gettext "Warning: Could not set the supported encryption type for computer account").\n"
1463		fi
1464	fi
1465
1466	# We should probably check whether arcfour is available, and if not,
1467	# then set the 1DES only flag, but whatever, it's not likely NOT to be
1468	# available on S10/Nevada!
1469
1470	# Reset userAccountControl
1471	#
1472	#  NORMAL_ACCOUNT (512) | DONT_EXPIRE_PASSWORD (65536) |
1473	#  TRUSTED_FOR_DELEGATION (524288)
1474	#
1475	# and possibly UseDesOnly (2097152) (see above)
1476	#
1477	cat > "$object" <<EOF
1478dn: $dn
1479changetype: modify
1480replace: userAccountControl
1481userAccountControl: $userAccountControl
1482EOF
1483	ldapmodify -h "$dc" $ldap_args -f "$object" >/dev/null 2>&1
1484	if [[ $? -ne 0 ]]; then
1485		printf "$(gettext "ldapmodify failed to modify account attribute").\n" >&2
1486		error_message
1487	fi
1488
1489	# Setup a keytab file
1490	set -A args --
1491	for enctype in "${enctypes[@]}"
1492	do
1493		args[${#args[@]}]=-e
1494		args[${#args[@]}]=$enctype
1495	done
1496
1497	rm $new_keytab > /dev/null 2>&1
1498
1499	cat > "$object" <<EOF
1500dn: $dn
1501changetype: modify
1502add: servicePrincipalName
1503servicePrincipalName: nfs/${fqdn}
1504servicePrincipalName: HTTP/${fqdn}
1505servicePrincipalName: root/${fqdn}
1506servicePrincipalName: cifs/${fqdn}
1507servicePrincipalName: host/${upcase_nodename}
1508EOF
1509	ldapmodify -h "$dc" $ldap_args -f "$object" >/dev/null 2>&1
1510	if [[ $? -ne 0 ]]; then
1511		printf "$(gettext "ldapmodify failed to modify account attribute").\n" >&2
1512		error_message
1513	fi
1514
1515	#
1516	# In Windows, unlike MIT based implementations we salt the keys with
1517	# the UPN, which is based on the host/string15@realm elements, not
1518	# with the individual SPN strings.
1519	#
1520	salt=host/${locase_nodename}.${domain}@${realm}
1521
1522	skeys=(host/${fqdn}@${realm} nfs/${fqdn}@${realm} HTTP/${fqdn}@${realm})
1523	skeys+=(root/${fqdn}@${realm} cifs/${fqdn}@${realm})
1524	skeys+=(${netbios_nodename}@${realm} host/${upcase_nodename}@${realm})
1525	skeys+=(cifs/${upcase_nodename}@${realm})
1526
1527	ks_args="-n -s $salt -v $kvno -k $new_keytab ${args[@]}"
1528
1529	for skey in ${skeys[@]}
1530	do
1531		printf "%s" "$newpw" | $KSETPW $ks_args $skey > /dev/null 2>&1
1532		if [[ $? -ne 0 ]]
1533		then
1534			printf "$(gettext "Failed to set password").\n" >&2
1535			error_message
1536		fi
1537	done
1538
1539	doKRB5config
1540
1541	addDNSRR $dom
1542
1543	setSMB $dom $dc
1544
1545	printf -- "---------------------------------------------------\n"
1546	printf "$(gettext "Setup COMPLETE").\n\n"
1547
1548	kdestroy -q 1>$TMP_FILE 2>&1
1549	rm -f $TMP_FILE
1550	rm -rf $TMPDIR > /dev/null 2>&1
1551
1552	exit 0
1553}
1554
1555###########################
1556#	Main section	  #
1557###########################
1558#
1559# Set the Kerberos config file and some default strings/files
1560#
1561KRB5_CONFIG_FILE=/etc/krb5/krb5.conf
1562KRB5_KEYTAB_FILE=/etc/krb5/krb5.keytab
1563RESOLV_CONF_FILE=/etc/resolv.conf
1564
1565KLOOKUP=/usr/lib/krb5/klookup;	check_bin $KLOOKUP
1566KSETPW=/usr/lib/krb5/ksetpw;	check_bin $KSETPW
1567KSMB=/usr/lib/krb5/ksmb;	check_bin $KSMB
1568KDYNDNS=/usr/lib/krb5/kdyndns;	check_bin $KDYNDNS
1569KCONF=/usr/lib/krb5/kconf;	check_bin $KCONF
1570
1571dns_lookup=no
1572ask_fqdns=no
1573adddns=no
1574no_keytab=no
1575checkval=""
1576profile=""
1577typeset -u realm
1578typeset -l hostname KDC
1579
1580export TMPDIR="/var/run/kclient"
1581
1582mkdir $TMPDIR > /dev/null 2>&1
1583if [[ $? -ne 0 ]]; then
1584	printf "\n$(gettext "Can not create directory: %s")\n\n" $TMPDIR >&2
1585	exit 1
1586fi
1587
1588TMP_FILE=$(mktemp -q -t kclient-tmpfile.XXXXXX)
1589export KRB5_CONFIG=$(mktemp -q -t kclient-krb5conf.XXXXXX)
1590export KRB5CCNAME=$(mktemp -q -t kclient-krb5ccache.XXXXXX)
1591new_keytab=$(mktemp -q -t kclient-krb5keytab.XXXXXX)
1592if [[ -z $TMP_FILE || -z $KRB5_CONFIG || -z $KRB5CCNAME || -z $new_keytab ]]
1593then
1594	printf "\n$(gettext "Can not create temporary files, exiting").\n\n" >&2
1595	exit 1
1596fi
1597
1598#
1599# If we are interrupted, cleanup after ourselves
1600#
1601trap "exiting 1" HUP INT QUIT TERM
1602
1603if [[ -d /usr/bin ]]; then
1604	if [[ -d /usr/sbin ]]; then
1605		PATH=/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:$PATH
1606		export PATH
1607	else
1608		printf "\n$(gettext "Directory /usr/sbin not found, exiting").\n" >&2
1609		exit 1
1610	fi
1611else
1612	printf "\n$(gettext "Directory /usr/bin not found, exiting").\n" >&2
1613	exit 1
1614fi
1615
1616printf "\n$(gettext "Starting client setup")\n\n"
1617printf -- "---------------------------------------------------\n"
1618
1619#
1620# Check for uid 0, disallow otherwise
1621#
1622id 1>$TMP_FILE 2>&1
1623if [[ $? -eq 0 ]]; then
1624	if egrep -s "uid=0\(root\)" $TMP_FILE; then
1625		# uid is 0, go ahead ...
1626		:
1627	else
1628		printf "\n$(gettext "Administrative privileges are required to run this script, exiting").\n" >&2
1629		error_message
1630	fi
1631else
1632	cat $TMP_FILE;
1633	printf "\n$(gettext "uid check failed, exiting").\n" >&2
1634	error_message
1635fi
1636
1637uname=$(uname -n)
1638hostname=${uname%%.*}
1639
1640#
1641# Process the command-line arguments (if any)
1642#
1643OPTIND=1
1644while getopts nD:Kp:R:k:a:c:d:f:h:m:s:T: OPTIONS
1645do
1646	case $OPTIONS in
1647	    D) options="$options -D"
1648	       domain_list="$OPTARG"
1649	       ;;
1650	    K) options="$options -K"
1651	       no_keytab=yes
1652	       ;;
1653	    R) options="$options -R"
1654	       realm="$OPTARG"
1655	       checkval="REALM"; check_value $realm
1656	       ;;
1657	    T) options="$options -T"
1658	       type="$OPTARG"
1659	       if [[ $type == ms_ad ]]; then
1660		msad=yes
1661		adddns=yes
1662	       else
1663		non_solaris=yes
1664		no_keytab=yes
1665	       fi
1666	       ;;
1667	    a) options="$options -a"
1668	       ADMIN_PRINC="$OPTARG"
1669	       checkval="ADMIN_PRINC"; check_value $ADMIN_PRINC
1670	       ;;
1671	    c) options="$options -c"
1672	       filepath="$OPTARG"
1673	       ;;
1674	    d) options="$options -d"
1675	       dnsarg="$OPTARG"
1676	       checkval="DNS_OPTIONS"; check_value $dnsarg
1677	       ;;
1678	    f) options="$options -f"
1679	       fqdnlist="$OPTARG"
1680 	       ;;
1681	    h) options="$options -h"
1682	       logical_hn="$OPTARG"
1683	       checkval="LOGICAL_HOSTNAME"; check_value $logical_hn
1684	       ;;
1685	    k) options="$options -k"
1686	       kdc_list="$OPTARG"
1687	       ;;
1688	    m) options="$options -m"
1689	       KDC="$OPTARG"
1690	       checkval="KDC"; check_value $KDC
1691	       ;;
1692	    n) options="$options -n"
1693	       add_nfs=yes
1694	       ;;
1695	    p) options="$options -p"
1696	       profile="$OPTARG"
1697	       read_profile $profile
1698	       ;;
1699	    s) options="$options -s"
1700	       svc_list="$OPTARG"
1701	       SVCs=${svc_list//,/ }
1702 	       ;;
1703	    \?) usage
1704	       ;;
1705	    *) usage
1706	       ;;
1707	esac
1708done
1709
1710#correct argument count after options
1711shift `expr $OPTIND - 1`
1712
1713if [[ -z $options ]]; then
1714	:
1715else
1716	if [[ $# -ne 0 ]]; then
1717		usage
1718	fi
1719fi
1720
1721#
1722# Check to see if we will be a client of a MIT, Heimdal, Shishi, etc.
1723#
1724if [[ -z $options ]]; then
1725	query "$(gettext "Is this a client of a non-Solaris KDC") ?"
1726	non_solaris=$answer
1727	if [[ $non_solaris == yes ]]; then
1728		printf "$(gettext "Which type of KDC is the server"):\n"
1729		printf "\t$(gettext "ms_ad: Microsoft Active Directory")\n"
1730		printf "\t$(gettext "mit: MIT KDC server")\n"
1731		printf "\t$(gettext "heimdal: Heimdal KDC server")\n"
1732		printf "\t$(gettext "shishi: Shishi KDC server")\n"
1733		printf "$(gettext "Enter required KDC type"): "
1734		read kdctype
1735		if [[ $kdctype == ms_ad ]]; then
1736			msad=yes
1737		elif [[ $kdctype == mit || $kdctype == heimdal || \
1738		    $kdctype == shishi ]]; then
1739			no_keytab=yes
1740		else
1741			printf "\n$(gettext "Invalid KDC type option, valid types are ms_ad, mit, heimdal, or shishi, exiting").\n" >&2
1742			error_message
1743		fi
1744	fi
1745fi
1746
1747[[ $msad == yes ]] && join_domain
1748
1749#
1750# Check for /etc/resolv.conf
1751#
1752if [[ -r $RESOLV_CONF_FILE ]]; then
1753	client_machine=`$KLOOKUP`
1754
1755	if [[ $? -ne 0 ]]; then
1756		if [[ $adddns == no ]]; then
1757			printf "\n$(gettext "%s does not have a DNS record and is required for Kerberos setup")\n" $hostname >&2
1758			error_message
1759		fi
1760
1761	else
1762		#
1763		# If client entry already exists then do not recreate it
1764		#
1765		adddns=no
1766
1767		hostname=${client_machine%%.*}
1768		domain=${client_machine#*.}
1769	fi
1770
1771	short_fqdn=${domain#*.*}
1772	short_fqdn=$(echo $short_fqdn | grep "\.")
1773else
1774	#
1775	# /etc/resolv.conf not present, exit ...
1776	#
1777	printf "\n$(gettext "%s does not exist and is required for Kerberos setup")\n" $RESOLV_CONF_FILE >&2
1778	printf "$(gettext "Refer to resolv.conf(4), exiting").\n" >&2
1779	error_message
1780fi
1781
1782check_nss_conf || printf "$(gettext "/etc/nsswitch.conf does not make use of DNS for hosts and/or ipnodes").\n"
1783
1784[[ -n $fqdnlist ]] && verify_fqdnlist "$fqdnlist"
1785
1786if [[ -z $dnsarg && (-z $options || -z $filepath) ]]; then
1787	query "$(gettext "Do you want to use DNS for kerberos lookups") ?"
1788	if [[ $answer == yes ]]; then
1789		printf "\n$(gettext "Valid DNS lookup options are dns_lookup_kdc, dns_lookup_realm,\nand dns_fallback. Refer krb5.conf(4) for further details").\n"
1790		printf "\n$(gettext "Enter required DNS option"): "
1791		read dnsarg
1792		checkval="DNS_OPTIONS"; check_value $dnsarg
1793		set_dns_value $dnsarg
1794	fi
1795else
1796	[[ -z $dnsarg ]] && dnsarg=none
1797	set_dns_value $dnsarg
1798fi
1799
1800if [[ -n $kdc_list ]]; then
1801	if [[ -z $KDC ]]; then
1802		for kdc in $kdc_list; do
1803			break
1804		done
1805		KDC="$kdc"
1806	fi
1807fi
1808
1809if [[ -z $realm ]]; then
1810	printf "$(gettext "Enter the Kerberos realm"): "
1811	read realm
1812	checkval="REALM"; check_value $realm
1813fi
1814if [[ -z $KDC ]]; then
1815	printf "$(gettext "Specify the master KDC hostname for the above realm"): "
1816	read KDC
1817	checkval="KDC"; check_value $KDC
1818fi
1819
1820FKDC=`$KLOOKUP $KDC`
1821
1822#
1823# Ping to see if the kdc is alive !
1824#
1825ping_check $FKDC "KDC"
1826
1827if [[ -z $kdc_list && (-z $options || -z $filepath) ]]; then
1828	query "$(gettext "Do you have any slave KDC(s)") ?"
1829	if [[ $answer == yes ]]; then
1830		printf "$(gettext "Enter a comma-separated list of slave KDC host names"): "
1831		read kdc_list
1832	fi
1833fi
1834
1835[[ -n $kdc_list ]] && verify_kdcs "$kdc_list"
1836
1837#
1838# Check to see if we will have a dynamic presence in the realm
1839#
1840if [[ -z $options ]]; then
1841	query "$(gettext "Will this client need service keys") ?"
1842	if [[ $answer == no ]]; then
1843		no_keytab=yes
1844	fi
1845fi
1846
1847#
1848# Check to see if we are configuring the client to use a logical host name
1849# of a cluster environment
1850#
1851if [[ -z $options ]]; then
1852	query "$(gettext "Is this client a member of a cluster that uses a logical host name") ?"
1853	if [[ $answer == yes ]]; then
1854		printf "$(gettext "Specify the logical hostname of the cluster"): "
1855		read logical_hn
1856		checkval="LOGICAL_HOSTNAME"; check_value $logical_hn
1857		setup_lhn
1858	fi
1859fi
1860
1861if [[ -n $domain_list && (-z $options || -z $filepath) ]]; then
1862	query "$(gettext "Do you have multiple domains/hosts to map to realm %s"
1863) ?" $realm
1864	if [[ $answer == yes ]]; then
1865		printf "$(gettext "Enter a comma-separated list of domain/hosts
1866to map to the default realm"): "
1867		read domain_list
1868	fi
1869fi
1870[[ -n domain_list ]] && domain_list=${domain_list//,/ }
1871
1872#
1873# Start writing up the krb5.conf file, save the existing one
1874# if already present
1875#
1876writeup_krb5_conf
1877
1878#
1879# Is this client going to use krb-nfs?  If so then we need to at least
1880# uncomment the krb5* sec flavors in nfssec.conf.
1881#
1882if [[ -z $options ]]; then
1883	query "$(gettext "Do you plan on doing Kerberized nfs") ?"
1884	add_nfs=$answer
1885fi
1886
1887if [[ $add_nfs == yes ]]; then
1888	modify_nfssec_conf
1889
1890	#
1891	# We also want to enable gss as we now live in a SBD world
1892	#
1893	svcadm enable svc:/network/rpc/gss:default
1894	[[ $? -ne 0 ]] && printf "$(gettext "Warning: could not enable gss service").\n"
1895fi
1896
1897if [[ -z $options ]]; then
1898	query "$(gettext "Do you want to update /etc/pam.conf") ?"
1899	if [[ $answer == yes ]]; then
1900		printf "$(gettext "Enter a list of PAM service names in the following format: service:{first|only|optional}[,..]"): "
1901		read svc_list
1902		SVCs=${svc_list//,/ }
1903	fi
1904fi
1905[[ -n $svc_list ]] && update_pam_conf
1906
1907#
1908# Copy over krb5.conf master copy from filepath
1909#
1910if [[ -z $options || -z $filepath ]]; then
1911	query "$(gettext "Do you want to copy over the master krb5.conf file") ?"
1912	if [[ $answer == yes ]]; then
1913		printf "$(gettext "Enter the pathname of the file to be copied"): "
1914		read filepath
1915	fi
1916fi
1917
1918if [[ -n $filepath && -r $filepath ]]; then
1919	cp $filepath $KRB5_CONFIG
1920	if [[ $? -eq 0 ]]; then
1921		printf "$(gettext "Copied %s to %s").\n" $filepath $KRB5_CONFIG
1922	else
1923		printf "$(gettext "Copy of %s failed, exiting").\n" $filepath >&2
1924		error_message
1925	fi
1926elif [[ -n $filepath ]]; then
1927	printf "\n$(gettext "%s not found, exiting").\n" $filepath >&2
1928	error_message
1929fi
1930
1931doKRB5config
1932
1933#
1934# Populate any service keys needed for the client in the keytab file
1935#
1936if [[ $no_keytab != yes ]]; then
1937	setup_keytab
1938else
1939	printf "\n$(gettext "Note: %s file not created, please refer to verify_ap_req_nofail in krb5.conf(4) for the implications").\n" $KRB5_KEYTAB_FILE
1940	printf "$(gettext "Client will also not be able to host services that use Kerberos").\n"
1941fi
1942
1943printf -- "\n---------------------------------------------------\n"
1944printf "$(gettext "Setup COMPLETE").\n\n"
1945
1946#
1947# If we have configured the client in a cluster we need to remind the user
1948# to propagate the keytab and configuration files to the other members.
1949#
1950if [[ -n $logical_hn ]]; then
1951	printf "\n$(gettext "Note, you will need to securely transfer the /etc/krb5/krb5.keytab and /etc/krb5/krb5.conf files to all the other members of your cluster").\n"
1952fi
1953
1954#
1955# Cleanup.
1956#
1957kdestroy -q 1>$TMP_FILE 2>&1
1958rm -f $TMP_FILE
1959rm -rf $TMPDIR > /dev/null 2>&1
1960exit 0
1961