aboutsummaryrefslogtreecommitdiff
path: root/src/kadmin/server/ovsec_kadmd.c
blob: 776eace1edbe383d4d4c4cf262b4f47fd7658bf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
/*
 * Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved
 *
 */

/*
 * Copyright (C) 1998 by the FundsXpress, INC.
 * 
 * All rights reserved.
 * 
 * Export of this software from the United States of America may require
 * a specific license from the United States Government.  It is the
 * responsibility of any person or organization contemplating export to
 * obtain such a license before exporting.
 * 
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of FundsXpress. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  FundsXpress makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include    <stdio.h>
#include    <signal.h>
#include    <syslog.h>
#include    <sys/types.h>
#ifdef _AIX
#include    <sys/select.h>
#endif
#include    <sys/time.h>
#include    <sys/socket.h>
#include    <unistd.h>
#include    <netinet/in.h>
#include    <arpa/inet.h>  /* inet_ntoa */
#include    <netdb.h>
#include    <gssrpc/rpc.h>
#include    <gssapi/gssapi.h>
#include    <gssrpc/auth_gssapi.h>
#include    <kadm5/admin.h>
#include    <kadm5/kadm_rpc.h>
#include    <kadm5/server_acl.h>
#include    <krb5/adm_proto.h>
#include    <string.h>

#include    "misc.h"

#ifdef PURIFY
#include    "purify.h"

int	signal_pure_report = 0;
int	signal_pure_clear = 0;
void	request_pure_report(int);
void	request_pure_clear(int);
#endif /* PURIFY */

#if defined(NEED_DAEMON_PROTO)
extern int daemon(int, int);
#endif

volatile int	signal_request_exit = 0;
volatile int	signal_request_hup = 0;
void    setup_signal_handlers(void);
void	request_exit(int);
void	request_hup(int);
void	reset_db(void);
void	sig_pipe(int);
void	kadm_svc_run(kadm5_config_params *params);

#ifdef POSIX_SIGNALS
static struct sigaction s_action;
#endif /* POSIX_SIGNALS */


#define	TIMEOUT	15

gss_name_t gss_changepw_name = NULL, gss_oldchangepw_name = NULL;
void *global_server_handle;

/*
 * This is a kludge, but the server needs these constants to be
 * compatible with old clients.  They are defined in <kadm5/admin.h>,
 * but only if USE_KADM5_API_VERSION == 1.
 */
#define OVSEC_KADM_ADMIN_SERVICE	"ovsec_adm/admin"
#define OVSEC_KADM_CHANGEPW_SERVICE	"ovsec_adm/changepw"

/*
 * This enables us to set the keytab that gss_acquire_cred uses, but
 * it also restricts us to linking against the Kv5 GSS-API library.
 * Since this is *k*admind, that shouldn't be a problem.
 */
extern 	char *krb5_overridekeyname;

char *build_princ_name(char *name, char *realm);
void log_badauth(OM_uint32 major, OM_uint32 minor,
		 struct sockaddr_in *addr, char *data);
void log_badverf(gss_name_t client_name, gss_name_t server_name,
		 struct svc_req *rqst, struct rpc_msg *msg,
		 char *data);
void log_miscerr(struct svc_req *rqst, struct rpc_msg *msg, char
		 *error, char *data);
void log_badauth_display_status(char *msg, OM_uint32 major, OM_uint32 minor);
void log_badauth_display_status_1(char *m, OM_uint32 code, int type,
				  int rec);
	
int schpw;
void do_schpw(int s, kadm5_config_params *params);

/*
 * Function: usage
 * 
 * Purpose: print out the server usage message
 *
 * Arguments:
 * Requires:
 * Effects:
 * Modifies:
 */

static void usage()
{
     fprintf(stderr, "Usage: kadmind [-r realm] [-m] [-nofork] "
	     "[-port port-number]\n");
     exit(1);
}

/*
 * Function: display_status
 *
 * Purpose: displays GSS-API messages
 *
 * Arguments:
 *
 * 	msg		a string to be displayed with the message
 * 	maj_stat	the GSS-API major status code
 * 	min_stat	the GSS-API minor status code
 *
 * Effects:
 *
 * The GSS-API messages associated with maj_stat and min_stat are
 * displayed on stderr, each preceeded by "GSS-API error <msg>: " and
 * followed by a newline.
 */
static void display_status_1(char *, OM_uint32, int);

static void display_status(msg, maj_stat, min_stat)
     char *msg;
     OM_uint32 maj_stat;
     OM_uint32 min_stat;
{
     display_status_1(msg, maj_stat, GSS_C_GSS_CODE);
     display_status_1(msg, min_stat, GSS_C_MECH_CODE);
}

static void display_status_1(m, code, type)
     char *m;
     OM_uint32 code;
     int type;
{
	OM_uint32 maj_stat, min_stat;
	gss_buffer_desc msg;
	OM_uint32 msg_ctx;
     
	msg_ctx = 0;
	while (1) {
		maj_stat = gss_display_status(&min_stat, code,
					      type, GSS_C_NULL_OID,
					      &msg_ctx, &msg);
		fprintf(stderr, "GSS-API error %s: %s\n", m,
			(char *)msg.value); 
		(void) gss_release_buffer(&min_stat, &msg);
	  
		if (!msg_ctx)
			break;
	}
}


/* XXX yuck.  the signal handlers need this */
static krb5_context context;

int main(int argc, char *argv[])
{
     register	SVCXPRT *transp;
     extern	char *optarg;
     extern	int optind, opterr;
     int ret, nofork, oldnames = 0;
     OM_uint32 OMret, major_status, minor_status;
     char *whoami;
     gss_buffer_desc in_buf;
     struct sockaddr_in addr;
     int s;
     auth_gssapi_name names[4];
     gss_buffer_desc gssbuf;
     gss_OID nt_krb5_name_oid;
     kadm5_config_params params;
     
     /* This is OID value the Krb5_Name NameType */
     gssbuf.value = "{1 2 840 113554 1 2 2 1}";
     gssbuf.length = strlen(gssbuf.value);
     major_status = gss_str_to_oid(&minor_status, &gssbuf, &nt_krb5_name_oid);
     if (major_status != GSS_S_COMPLETE) {
	     fprintf(stderr, "Couldn't create KRB5 Name NameType OID\n");
	     display_status("str_to_oid", major_status, minor_status);
	     exit(1);
     }
     
     names[0].name = names[1].name = names[2].name = names[3].name = NULL;
     names[0].type = names[1].type = names[2].type = names[3].type =
	     nt_krb5_name_oid;

#ifdef PURIFY
     purify_start_batch();
#endif /* PURIFY */
     whoami = (strrchr(argv[0], '/') ? strrchr(argv[0], '/')+1 : argv[0]);

     nofork = 0;

     memset((char *) &params, 0, sizeof(params));
     
     argc--; argv++;
     while (argc) {
	  if (strcmp(*argv, "-r") == 0) {
	       argc--; argv++;
	       if (!argc)
		    usage();
	       params.realm = *argv;
	       params.mask |= KADM5_CONFIG_REALM;
	       argc--; argv++;
	       continue;
	  } else if (strcmp(*argv, "-m") == 0) {
	       params.mkey_from_kbd = 1;
	       params.mask |= KADM5_CONFIG_MKEY_FROM_KBD;
	  } else if (strcmp(*argv, "-nofork") == 0) {
	       nofork = 1;
	  } else if(strcmp(*argv, "-port") == 0) {
	    argc--; argv++;
	    if(!argc)
	      usage();
	    params.kadmind_port = atoi(*argv);
	    params.mask |= KADM5_CONFIG_KADMIND_PORT;
	  } else
	       break;
	  argc--; argv++;
     }
     
     if (argc != 0)
	  usage();

     if ((ret = krb5_init_context(&context))) {
	  fprintf(stderr, "%s: %s while initializing context, aborting\n",
		  whoami, error_message(ret));
	  exit(1);
     }

     krb5_klog_init(context, "admin_server", whoami, 1);


     krb5_klog_syslog(LOG_INFO, "Seeding random number generator");
          ret = krb5_c_random_os_entropy(context, 1, NULL);
	  if(ret) {
	    krb5_klog_syslog(LOG_ERR, "Error getting random seed: %s, aborting",
			     error_message(ret));
	    exit(1);
	  }
	  
     if((ret = kadm5_init("kadmind", NULL,
			  NULL, &params,
			  KADM5_STRUCT_VERSION,
			  KADM5_API_VERSION_2,
			  &global_server_handle)) != 
	KADM5_OK) {
	  krb5_klog_syslog(LOG_ERR, "%s while initializing, aborting",
		 error_message(ret));
	  fprintf(stderr, "%s: %s while initializing, aborting\n",
		  whoami, error_message(ret));
	  krb5_klog_close(context);
	  exit(1);
     }
     
     if ((ret = kadm5_get_config_params(context, NULL, NULL, &params,
					&params))) {
	  krb5_klog_syslog(LOG_ERR, "%s: %s while initializing, aborting",
			   whoami, error_message(ret));
	  fprintf(stderr, "%s: %s while initializing, aborting\n",
		  whoami, error_message(ret));
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);
	  exit(1);
     }

#define REQUIRED_PARAMS (KADM5_CONFIG_REALM | KADM5_CONFIG_ACL_FILE | \
			 KADM5_CONFIG_ADMIN_KEYTAB)

     if ((params.mask & REQUIRED_PARAMS) != REQUIRED_PARAMS) {
	  krb5_klog_syslog(LOG_ERR, "%s: Missing required configuration values "
			   "while initializing, aborting", whoami,
			   (params.mask & REQUIRED_PARAMS) ^ REQUIRED_PARAMS);
	  fprintf(stderr, "%s: Missing required configuration values "
		  "(%lx) while initializing, aborting\n", whoami,
		  (params.mask & REQUIRED_PARAMS) ^ REQUIRED_PARAMS);
	  krb5_klog_close(context);
	  kadm5_destroy(global_server_handle);
	  exit(1);
     }

     memset(&addr, 0, sizeof(addr));
     addr.sin_family = AF_INET;
     addr.sin_addr.s_addr = INADDR_ANY;
     addr.sin_port = htons(params.kadmind_port);

     if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	  krb5_klog_syslog(LOG_ERR, "Cannot create TCP socket: %s",
			   error_message(errno));
	  fprintf(stderr, "Cannot create TCP socket: %s",
		  error_message(errno));
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);	  
	  exit(1);
     }

     if ((schpw = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	 krb5_klog_syslog(LOG_ERR,
			   "cannot create simple chpw socket: %s",
			   error_message(errno));
	 fprintf(stderr, "Cannot create simple chpw socket: %s",
		 error_message(errno));
	 kadm5_destroy(global_server_handle);
	 krb5_klog_close(context);
	 exit(1);
     }

#ifdef SO_REUSEADDR
     /* the old admin server turned on SO_REUSEADDR for non-default
	port numbers.  this was necessary, on solaris, for the tests
	to work.  jhawk argues that the debug and production modes
	should be the same.  I think I agree, so I'm always going to set
	SO_REUSEADDR.  The other option is to have the unit tests wait
	until the port is useable, or use a different port each time.  
	--marc */

     {
	 int	allowed;

	 allowed = 1;
	 if (setsockopt(s,
			SOL_SOCKET,
			SO_REUSEADDR,
			(char *) &allowed,
			sizeof(allowed)) < 0) {
	     krb5_klog_syslog(LOG_ERR, "Cannot set SO_REUSEADDR: %s",
			      error_message(errno));
	     fprintf(stderr, "Cannot set SO_REUSEADDR: %s",
		     error_message(errno));
	     kadm5_destroy(global_server_handle);
	     krb5_klog_close(context);	  
	     exit(1);
	 }
	 if (setsockopt(schpw, SOL_SOCKET, SO_REUSEADDR,
			(char *) &allowed, sizeof(allowed)) < 0) {
	     krb5_klog_syslog(LOG_ERR, "main",
			      "cannot set SO_REUSEADDR on simple chpw socket: %s", 
			      error_message(errno));
	     fprintf(stderr,
		     "Cannot set SO_REUSEADDR on simple chpw socket: %s",
 		     error_message(errno));
 	     kadm5_destroy(global_server_handle);
 	     krb5_klog_close(context);
	 }

     }
#endif /* SO_REUSEADDR */
     memset(&addr, 0, sizeof(addr));
     addr.sin_family = AF_INET;
     addr.sin_addr.s_addr = INADDR_ANY;
     addr.sin_port = htons(params.kadmind_port);

     if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
	  int oerrno = errno;
	  fprintf(stderr, "%s: Cannot bind socket.\n", whoami);
	  fprintf(stderr, "bind: %s\n", error_message(oerrno));
	  errno = oerrno;
	  krb5_klog_syslog(LOG_ERR, "Cannot bind socket: %s",
			   error_message(errno));
	  if(oerrno == EADDRINUSE) {
	       char *w = strrchr(whoami, '/');
	       if (w) {
		    w++;
	       }
	       else {
		    w = whoami;
	       }
	       fprintf(stderr,
"This probably means that another %s process is already\n"
"running, or that another program is using the server port (number %d)\n"
"after being assigned it by the RPC portmap daemon.  If another\n"
"%s is already running, you should kill it before\n"
"restarting the server.  If, on the other hand, another program is\n"
"using the server port, you should kill it before running\n"
"%s, and ensure that the conflict does not occur in the\n"
"future by making sure that %s is started on reboot\n"
		       "before portmap.\n", w, ntohs(addr.sin_port), w, w, w);
	       krb5_klog_syslog(LOG_ERR, "Check for already-running %s or for "
		      "another process using port %d", w,
		      htons(addr.sin_port));
	  }
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);
	  exit(1);
     }
     memset(&addr, 0, sizeof(addr));
     addr.sin_family = AF_INET;
     addr.sin_addr.s_addr = INADDR_ANY;
     /* XXX */
     addr.sin_port = htons(params.kpasswd_port);

     if (bind(schpw, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
	  char portbuf[32];
	  int oerrno = errno;
	  fprintf(stderr, "%s: Cannot bind socket.\n", whoami);
	  fprintf(stderr, "bind: %s\n", error_message(oerrno));
	  errno = oerrno;
	  sprintf(portbuf, "%d", ntohs(addr.sin_port));
	  krb5_klog_syslog(LOG_ERR, "cannot bind simple chpw socket: %s",
			   error_message(oerrno));
	  if(oerrno == EADDRINUSE) {
	       char *w = strrchr(whoami, '/');
	       if (w) {
		    w++;
	       }
	       else {
		    w = whoami;
	       }
	       fprintf(stderr,
"This probably means that another %s process is already\n"
"running, or that another program is using the server port (number %d).\n"
"If another %s is already running, you should kill it before\n"
"restarting the server.\n",
		       w, ntohs(addr.sin_port), w);
 	  }
 	  kadm5_destroy(global_server_handle);
 	  krb5_klog_close(context);
	  exit(1);
     }
     
     transp = svctcp_create(s, 0, 0);
     if(transp == NULL) {
	  fprintf(stderr, "%s: Cannot create RPC service.\n", whoami);
	  krb5_klog_syslog(LOG_ERR, "Cannot create RPC service: %m");
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);	  
	  exit(1);
     }
     if(!svc_register(transp, KADM, KADMVERS, kadm_1, 0)) {
	  fprintf(stderr, "%s: Cannot register RPC service.\n", whoami);
	  krb5_klog_syslog(LOG_ERR, "Cannot register RPC service, failing.");
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);	  
	  exit(1);
     }

     names[0].name = build_princ_name(KADM5_ADMIN_SERVICE, params.realm);
     names[1].name = build_princ_name(KADM5_CHANGEPW_SERVICE, params.realm);
     names[2].name = build_princ_name(OVSEC_KADM_ADMIN_SERVICE, params.realm);
     names[3].name = build_princ_name(OVSEC_KADM_CHANGEPW_SERVICE,
				      params.realm); 
     if (names[0].name == NULL || names[1].name == NULL ||
	 names[2].name == NULL || names[3].name == NULL) {
	  krb5_klog_syslog(LOG_ERR,
			   "Cannot build GSS-API authentication names, "
			   "failing.");
	  fprintf(stderr, "%s: Cannot build GSS-API authentication names.\n",
		  whoami);
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);	  
	  exit(1);
     }

     /* XXX krb5_overridekeyname is an internal library global and should
        go away.  This is an awful hack. */

     krb5_overridekeyname = params.admin_keytab;

     /*
      * Try to acquire creds for the old OV services as well as the
      * new names, but if that fails just fall back on the new names.
      */
     if (_svcauth_gssapi_set_names(names, 4) == TRUE)
	  oldnames++;
     if (!oldnames && _svcauth_gssapi_set_names(names, 2) == FALSE) {
	  krb5_klog_syslog(LOG_ERR,
			   "Cannot set GSS-API authentication names (keytab not present?), "
			   "failing.");
	  fprintf(stderr, "%s: Cannot set GSS-API authentication names.\n",
		  whoami);
	  _svcauth_gssapi_unset_names();
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);	  
	  exit(1);
     }

     /* if set_names succeeded, this will too */
     in_buf.value = names[1].name;
     in_buf.length = strlen(names[1].name) + 1;
     (void) gss_import_name(&OMret, &in_buf, nt_krb5_name_oid,
			    &gss_changepw_name);
     if (oldnames) {
	  in_buf.value = names[3].name;
	  in_buf.length = strlen(names[3].name) + 1;
	  (void) gss_import_name(&OMret, &in_buf, nt_krb5_name_oid,
				 &gss_oldchangepw_name);
     }

     _svcauth_gssapi_set_log_badauth_func(log_badauth, NULL);
     _svcauth_gssapi_set_log_badverf_func(log_badverf, NULL);
     _svcauth_gssapi_set_log_miscerr_func(log_miscerr, NULL);
     
     if ((ret = acl_init(context, 0, params.acl_file))) {
	  krb5_klog_syslog(LOG_ERR, "Cannot initialize acl file: %s",
		 error_message(ret));
	  fprintf(stderr, "%s: Cannot initialize acl file: %s\n",
		  whoami, error_message(ret));
	  _svcauth_gssapi_unset_names();
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);
	  exit(1);
     }

     if (!nofork && (ret = daemon(0, 0))) {
	  ret = errno;
	  krb5_klog_syslog(LOG_ERR, "Cannot detach from tty: %s", error_message(ret));
	  fprintf(stderr, "%s: Cannot detach from tty: %s\n",
		  whoami, error_message(ret));
	  _svcauth_gssapi_unset_names();
	  kadm5_destroy(global_server_handle);
	  krb5_klog_close(context);
	  exit(1);
     }
     
     setup_signal_handlers();
     krb5_klog_syslog(LOG_INFO, "starting");
     kadm_svc_run(&params);
     krb5_klog_syslog(LOG_INFO, "finished, exiting");

     /* Clean up memory, etc */
     _svcauth_gssapi_unset_names();
     kadm5_destroy(global_server_handle);
     close(s);
     acl_finish(context, 0);
     if(gss_changepw_name) {
          (void) gss_release_name(&OMret, &gss_changepw_name);
     }
     if(gss_oldchangepw_name) {
          (void) gss_release_name(&OMret, &gss_oldchangepw_name);
     }
     for(s = 0 ; s < 4; s++) {
          if (names[s].name) {
	        free(names[s].name);
	  }
     }

     krb5_klog_close(context);
     krb5_free_context(context);
     exit(2);
}

/*
 * Function: setup_signal_handlers
 *
 * Purpose: Setup signal handling functions using POSIX's sigaction()
 * if possible, otherwise with System V's signal().
 */

void setup_signal_handlers(void) {
#ifdef POSIX_SIGNALS
     (void) sigemptyset(&s_action.sa_mask);
     s_action.sa_handler = request_exit;
     (void) sigaction(SIGINT, &s_action, (struct sigaction *) NULL);
     (void) sigaction(SIGTERM, &s_action, (struct sigaction *) NULL);
     (void) sigaction(SIGQUIT, &s_action, (struct sigaction *) NULL);
     s_action.sa_handler = request_hup;
     (void) sigaction(SIGHUP, &s_action, (struct sigaction *) NULL);
     s_action.sa_handler = sig_pipe;
     (void) sigaction(SIGPIPE, &s_action, (struct sigaction *) NULL);
#ifdef PURIFY
     s_action.sa_handler = request_pure_report;
     (void) sigaction(SIGUSR1, &s_action, (struct sigaction *) NULL);
     s_action.sa_handler = request_pure_clear;
     (void) sigaction(SIGUSR2, &s_action, (struct sigaction *) NULL);
#endif /* PURIFY */
#else /* POSIX_SIGNALS */
     signal(SIGINT, request_exit);
     signal(SIGTERM, request_exit);
     signal(SIGQUIT, request_exit);
     signal(SIGHUP, request_hup);
     signal(SIGPIPE, sig_pipe);
#ifdef PURIFY
     signal(SIGUSR1, request_pure_report);
     signal(SIGUSR2, request_pure_clear);
#endif /* PURIFY */
#endif /* POSIX_SIGNALS */
}

/*
 * Function: kadm_svc_run
 * 
 * Purpose: modified version of sunrpc svc_run.
 *	    which closes the database every TIMEOUT seconds.
 *
 * Arguments:
 * Requires:
 * Effects:
 * Modifies:
 */

void kadm_svc_run(params)
kadm5_config_params *params;
{
     fd_set	rfd;
     int	sz = _gssrpc_rpc_dtablesize();
     struct	timeval	    timeout;
     
     while(signal_request_exit == 0) {
	  if (signal_request_hup) {
	      reset_db();
	      krb5_klog_reopen(context);
	      signal_request_hup = 0;
	  }
#ifdef PURIFY
	  if (signal_pure_report)	/* check to see if a report */
					/* should be dumped... */
	    {
	      purify_new_reports();
	      signal_pure_report = 0;
	    }
	  if (signal_pure_clear)	/* ...before checking whether */
					/* the info should be cleared. */
	    {
	      purify_clear_new_reports();
	      signal_pure_clear = 0;
	    }
#endif /* PURIFY */
	  timeout.tv_sec = TIMEOUT;
	  timeout.tv_usec = 0;
	  rfd = svc_fdset;
	  FD_SET(schpw, &rfd);
	  switch(select(sz, (fd_set *) &rfd, NULL, NULL, &timeout)) {
	  case -1:
	       if(errno == EINTR)
		    continue;
	       perror("select");
	       return;
	  case 0:
	       reset_db();
	       break;
	  default:
	      if (FD_ISSET(schpw, &rfd))
		  do_schpw(schpw, params);
	      else
		  svc_getreqset(&rfd);
	  }
     }
}

#ifdef PURIFY
/*
 * Function: request_pure_report
 * 
 * Purpose: sets flag saying the server got a signal and that it should
 *		dump a purify report when convenient.
 *
 * Arguments:
 * Requires:
 * Effects:
 * Modifies:
 *	sets signal_pure_report to one
 */

void request_pure_report(int signum)
{
     krb5_klog_syslog(LOG_DEBUG, "Got signal to request a Purify report");
     signal_pure_report = 1;
     return;
}

/*
 * Function: request_pure_clear
 * 
 * Purpose: sets flag saying the server got a signal and that it should
 *		dump a purify report when convenient, then clear the
 *		purify tables.
 *
 * Arguments:
 * Requires:
 * Effects:
 * Modifies:
 *	sets signal_pure_report to one
 *	sets signal_pure_clear to one
 */

void request_pure_clear(int signum)
{
     krb5_klog_syslog(LOG_DEBUG, "Got signal to request a Purify report and clear the old Purify info");
     signal_pure_report = 1;
     signal_pure_clear = 1;
     return;
}
#endif /* PURIFY */

/*
 * Function: request_hup
 * 
 * Purpose: sets flag saying the server got a signal and that it should
 *		reset the database files when convenient.
 *
 * Arguments:
 * Requires:
 * Effects:
 * Modifies:
 *	sets signal_request_hup to one
 */

void request_hup(int signum)
{
     signal_request_hup = 1;
     return;
}

/*
 * Function: reset_db
 * 
 * Purpose: flushes the currently opened database files to disk.
 *
 * Arguments:
 * Requires:
 * Effects:
 * 
 * Currently, just sets signal_request_reset to 0.  The kdb and adb
 * libraries used to be sufficiently broken that it was prudent to
 * close and reopen the databases periodically.  They are no longer
 * that broken, so this function is not necessary.
 */
void reset_db(void)
{
#ifdef notdef
     kadm5_ret_t ret;
     
     if (ret = kadm5_flush(global_server_handle)) {
	  krb5_klog_syslog(LOG_ERR, "FATAL ERROR!  %s while flushing databases.  "
		 "Databases may be corrupt!  Aborting.",
		 error_message(ret));
	  krb5_klog_close(context);
	  exit(3);
     }
#endif

     return;
}

/*
 * Function: request_exit
 * 
 * Purpose: sets flags saying the server got a signal and that it
 *	    should exit when convient.
 *
 * Arguments:
 * Requires:
 * Effects:
 *	modifies signal_request_exit which ideally makes the server exit
 *	at some point.
 *
 * Modifies:
 *	signal_request_exit
 */

void request_exit(int signum)
{
     krb5_klog_syslog(LOG_DEBUG, "Got signal to request exit");
     signal_request_exit = 1;
     return;
}

/*
 * Function: sig_pipe
 *
 * Purpose: SIGPIPE handler
 *
 * Effects: krb5_klog_syslogs a message that a SIGPIPE occurred and returns,
 * thus causing the read() or write() to fail and, presumable, the RPC
 * to recover.  Otherwise, the process aborts.
 */
void sig_pipe(int unused)
{
     krb5_klog_syslog(LOG_NOTICE, "Warning: Received a SIGPIPE; probably a "
	    "client aborted.  Continuing.");
     return;
}

/*
 * Function: build_princ_name
 * 
 * Purpose: takes a name and a realm and builds a string that can be
 *	    consumed by krb5_parse_name.
 *
 * Arguments:
 *	name		    (input) name to be part of principal
 *	realm		    (input) realm part of principal
 * 	<return value>	    char * pointing to "name@realm"
 *
 * Requires:
 *	name be non-null.
 * 
 * Effects:
 * Modifies:
 */

char *build_princ_name(char *name, char *realm)
{
     char *fullname;

     fullname = (char *) malloc(strlen(name) + 1 +
				(realm ? strlen(realm) + 1 : 0));
     if (fullname == NULL)
	  return NULL;
     if (realm)
	  sprintf(fullname, "%s@%s", name, realm);
     else
	  strcpy(fullname, name);
     return fullname;
}

/*
 * Function: log_badverf
 *
 * Purpose: Call from GSS-API Sun RPC for garbled/forged/replayed/etc
 * messages.
 *
 * Argiments:
 * 	client_name	(r) GSS-API client name
 * 	server_name	(r) GSS-API server name
 * 	rqst		(r) RPC service request
 * 	msg		(r) RPC message
 * 	data		(r) arbitrary data (NULL), not used
 *
 * Effects:
 *
 * Logs the invalid request via krb5_klog_syslog(); see functional spec for
 * format.
 */
void log_badverf(gss_name_t client_name, gss_name_t server_name,
		 struct svc_req *rqst, struct rpc_msg *msg, char
		 *data)
{
     struct procnames {
	  rpc_u_int32 proc;
	  const char *proc_name;
     };
     static const struct procnames proc_names[] = {
	  {1, "CREATE_PRINCIPAL"},
	  {2, "DELETE_PRINCIPAL"},
	  {3, "MODIFY_PRINCIPAL"},
	  {4, "RENAME_PRINCIPAL"},
	  {5, "GET_PRINCIPAL"},
	  {6, "CHPASS_PRINCIPAL"},
	  {7, "CHRAND_PRINCIPAL"},
	  {8, "CREATE_POLICY"},
	  {9, "DELETE_POLICY"},
	  {10, "MODIFY_POLICY"},
	  {11, "GET_POLICY"},
	  {12, "GET_PRIVS"},
	  {13, "INIT"},
	  {14, "GET_PRINCS"},
	  {15, "GET_POLS"},
	  {16, "SETKEY_PRINCIPAL"},
	  {17, "SETV4KEY_PRINCIPAL"},
	  {18, "CREATE_PRINCIPAL3"},
	  {19, "CHPASS_PRINCIPAL3"},
	  {20, "CHRAND_PRINCIPAL3"},
	  {21, "SETKEY_PRINCIPAL3"}
     };
#define NPROCNAMES (sizeof (proc_names) / sizeof (struct procnames))
     OM_uint32 minor;
     gss_buffer_desc client, server;
     gss_OID gss_type;
     char *a;
     rpc_u_int32 proc;
     int i;
     const char *procname;

     (void) gss_display_name(&minor, client_name, &client, &gss_type);
     (void) gss_display_name(&minor, server_name, &server, &gss_type);
     a = inet_ntoa(rqst->rq_xprt->xp_raddr.sin_addr);

     proc = msg->rm_call.cb_proc;
     procname = NULL;
     for (i = 0; i < NPROCNAMES; i++) {
	  if (proc_names[i].proc == proc) {
	       procname = proc_names[i].proc_name;
	       break;
	  }
     }
     if (procname != NULL)
	  krb5_klog_syslog(LOG_NOTICE, "WARNING! Forged/garbled request: %s, "
			   "claimed client = %s, server = %s, addr = %s",
			   procname, client.value,
			   server.value, a);
     else
	  krb5_klog_syslog(LOG_NOTICE, "WARNING! Forged/garbled request: %d, "
			   "claimed client = %s, server = %s, addr = %s",
			   proc, client.value,
			   server.value, a);

     (void) gss_release_buffer(&minor, &client);
     (void) gss_release_buffer(&minor, &server);
}

/*
 * Function: log_miscerr
 *
 * Purpose: Callback from GSS-API Sun RPC for miscellaneous errors
 *
 * Arguments:
 * 	rqst		(r) RPC service request
 * 	msg		(r) RPC message
 *	error		(r) error message from RPC
 * 	data		(r) arbitrary data (NULL), not used
 *
 * Effects:
 *
 * Logs the error via krb5_klog_syslog(); see functional spec for
 * format.
 */
void log_miscerr(struct svc_req *rqst, struct rpc_msg *msg,
		 char *error, char *data)
{
     char *a;
     
     a = inet_ntoa(rqst->rq_xprt->xp_raddr.sin_addr);
     krb5_klog_syslog(LOG_NOTICE, "Miscellaneous RPC error: %s, %s", a, error);
}



/*
 * Function: log_badauth
 *
 * Purpose: Callback from GSS-API Sun RPC for authentication
 * failures/errors.
 *
 * Arguments:
 * 	major 		(r) GSS-API major status
 * 	minor		(r) GSS-API minor status
 * 	addr		(r) originating address
 * 	data		(r) arbitrary data (NULL), not used
 *
 * Effects:
 *
 * Logs the GSS-API error via krb5_klog_syslog(); see functional spec for
 * format.
 */
void log_badauth(OM_uint32 major, OM_uint32 minor,
		 struct sockaddr_in *addr, char *data)
{
     char *a;
     
     /* Authentication attempt failed: <IP address>, <GSS-API error */
     /* strings> */

     a = inet_ntoa(addr->sin_addr);

     krb5_klog_syslog(LOG_NOTICE, "Authentication attempt failed: %s, GSS-API "
	    "error strings are:", a);
     log_badauth_display_status("   ", major, minor);
     krb5_klog_syslog(LOG_NOTICE, "   GSS-API error strings complete.");
}

void log_badauth_display_status(char *msg, OM_uint32 major, OM_uint32 minor)
{
     log_badauth_display_status_1(msg, major, GSS_C_GSS_CODE, 0);
     log_badauth_display_status_1(msg, minor, GSS_C_MECH_CODE, 0);
}

void log_badauth_display_status_1(char *m, OM_uint32 code, int type,
				  int rec)
{
     OM_uint32 gssstat, minor_stat;
     gss_buffer_desc msg;
     OM_uint32 msg_ctx;

     msg_ctx = 0;
     while (1) {
	  gssstat = gss_display_status(&minor_stat, code,
				       type, GSS_C_NULL_OID,
				       &msg_ctx, &msg);
	  if (gssstat != GSS_S_COMPLETE) {
 	       if (!rec) {
		    log_badauth_display_status_1(m,gssstat,GSS_C_GSS_CODE,1); 
		    log_badauth_display_status_1(m, minor_stat,
						 GSS_C_MECH_CODE, 1);
	       } else
		    krb5_klog_syslog(LOG_ERR, "GSS-API authentication error %s: "
			   "recursive failure!", msg);
	       return;
	  }

	  krb5_klog_syslog(LOG_NOTICE, "%s %s", m, (char *)msg.value); 
	  (void) gss_release_buffer(&minor_stat, &msg);
	  
	  if (!msg_ctx)
	       break;
     }
}

void do_schpw(int s1, kadm5_config_params *params)
{
    krb5_error_code ret;
    /* XXX buffer = ethernet mtu */
    char req[1500];
    int len;
    struct sockaddr_in from;
    socklen_t fromlen;
    krb5_keytab kt;
    krb5_data reqdata, repdata;
    int s2;

    fromlen = sizeof(from);
    if ((len = recvfrom(s1, req, sizeof(req), 0, (struct sockaddr *)&from,
			&fromlen)) < 0) {
	krb5_klog_syslog(LOG_ERR, "chpw: Couldn't receive request: %s",
			 error_message(errno));
	return;
    }

    if ((ret = krb5_kt_resolve(context, params->admin_keytab, &kt))) {
	krb5_klog_syslog(LOG_ERR, "chpw: Couldn't open admin keytab %s",
			 error_message(ret));
	return;
    }

    reqdata.length = len;
    reqdata.data = req;

    /* this is really obscure.  s1 is used for all communications.  it
       is left unconnected in case the server is multihomed and routes
       are asymmetric.  s2 is connected to resolve routes and get
       addresses.  this is the *only* way to get proper addresses for
       multihomed hosts if routing is asymmetric.  

       A related problem in the server, but not the client, is that
       many os's have no way to disconnect a connected udp socket, so
       the s2 socket needs to be closed and recreated for each
       request.  The s1 socket must not be closed, or else queued
       requests will be lost.

       A "naive" client implementation (one socket, no connect,
       hostname resolution to get the local ip addr) will work and
       interoperate if the client is single-homed. */

    if ((s2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
	krb5_klog_syslog(LOG_ERR, "cannot create connecting socket: %s",
			 error_message(errno));
	fprintf(stderr, "Cannot create connecting socket: %s",
		error_message(errno));
	_svcauth_gssapi_unset_names();
	kadm5_destroy(global_server_handle);
	krb5_klog_close(context);	  
	exit(1);
    }

    if (connect(s2, (struct sockaddr *) &from, sizeof(from)) < 0) {
	krb5_klog_syslog(LOG_ERR, "chpw: Couldn't connect to client: %s",
			 error_message(errno));
	goto cleanup;
    }

    if ((ret = process_chpw_request(context, global_server_handle,
				    params->realm, s2, kt, &from,
				    &reqdata, &repdata))) {
	krb5_klog_syslog(LOG_ERR, "chpw: Error processing request: %s", 
			 error_message(ret));
    }

    close(s2);

    if (repdata.length == 0) {
	/* just return.  This means something really bad happened */
        goto cleanup;
    }

    len = sendto(s1, repdata.data, (int) repdata.length, 0,
		 (struct sockaddr *) &from, sizeof(from));

    if (len < (int) repdata.length) {
	krb5_xfree(repdata.data);

	krb5_klog_syslog(LOG_ERR, "chpw: Error sending reply: %s", 
			 error_message(errno));
	goto cleanup;
    }

    krb5_xfree(repdata.data);

cleanup:
    krb5_kt_close(context, kt);

    return;
}