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