convert-from-bsd-to-posix-string-and-memory-functions-20010807
[openafs.git] / src / kauth / kaprocs.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID("$Header$");
14
15 #include <afs/stds.h>
16 #include <errno.h>
17 #include "kauth.h"
18 #include <sys/types.h>
19 #include <time.h>
20 #ifdef AFS_NT40_ENV
21 #include <afs/afsutil.h>
22 #else
23 #include <sys/resource.h>
24 #include <sys/file.h>
25 #endif
26 #include <stdio.h>
27 #include <lock.h>
28 #include <ubik.h>
29 #include <lwp.h>
30 #include <rx/xdr.h>
31 #include <rx/rx.h>
32 #include <rx/rxkad.h>
33 #ifdef AFS_NT40_ENV
34 #include <winsock2.h>
35 #else
36 #include <netinet/in.h>
37 #endif
38 #include <string.h>
39 #include <des.h>
40 #include <afs/cellconfig.h>
41 #include <afs/auth.h>
42 #include "kautils.h"
43 #include "kaserver.h"
44 #include "kalog.h"
45 #include "kaport.h"
46 #include "afs/audit.h"
47
48 extern struct ubik_dbase *KA_dbase;
49 struct kaheader cheader;
50 Date            cheaderReadTime;        /* time cheader last read in */
51 extern struct afsconf_dir *KA_conf;     /* for getting cell info */
52
53 afs_int32 kamCreateUser(), ChangePassWord(), kamSetPassword(), kamSetFields(), kamDeleteUser();
54 afs_int32 kamGetEntry(), kamListEntry(), kamGetStats(), kamGetPassword(), kamGetRandomKey(), kamDebug();
55 char lrealm[MAXKTCREALMLEN];
56
57 #ifndef EXPIREPW                        /* password expiration default yes */
58 #define EXPIREPW
59 #endif
60
61 #ifndef AUTOCPWINTERVAL
62 #define AUTOCPWINTERVAL (24*3600)
63 #endif
64 #ifndef AUTOCPWUPDATES
65 #define AUTOCPWUPDATES 128
66 #endif
67
68 extern int npwSums;
69
70 static afs_int32 autoCPWInterval;
71 static afs_int32 autoCPWUpdates;
72
73 static afs_int32 set_password ();               /* forward */
74 extern afs_int32 InitAuthServ ();               /* forward */
75 static afs_int32 impose_reuse_limits(); /* forward */
76 static int create_user();               /* forward */
77                 
78 /* This routine is called whenever an RPC interface needs the time.  It uses
79    the current time to randomize a 128 bit value that is used to change the
80    AuthServer Admin and TGS keys automatically. */
81
82 static Date nextAutoCPWTime = 0;
83 static afs_int32 totalUpdates = 0;
84
85 /* This routine is ostensibly to get the current time, but basically its job is
86    to periodically update a random number.  It also periodically updates the
87    keys for the builtin servers.  This is why it needs a transaction pointer
88    and returns an error code.  If the caller is in a read transaction, the tt
89    ptr should be zero and the return code need not be checked. */
90
91 static afs_int32 get_time (timeP, tt, admin)
92   Date *timeP;
93   struct ubik_trans *tt;                /* tt != 0: a write transaction */
94   int admin;                            /* the caller is an admin user */
95 {
96     /* random value used to change Admin & TGS keys, this is at risk during
97        multi-threaded operation, but I think the consequences are fairly
98        harmless. */
99     static afs_uint32 random_value[4];
100
101     struct timeval time;
102     unsigned int bit, nbit;
103     int   i;
104     afs_int32  to;
105
106     gettimeofday (&time, 0);
107     bit = (random_value[3] >> 31) & 1;  /* get high bit of high word */
108     for (i=0; i<4; i++) {
109         nbit = random_value[i] >> 31;
110         random_value[i] = (random_value[i] << 1) + bit;
111         bit = nbit & 1;
112     }
113     /* get 60ths from usec.  This is all the real randomness there is. */
114     random_value[0] += time.tv_usec / 16667;
115
116     if (nextAutoCPWTime == 0) { /* initialize things */
117         nextAutoCPWTime = time.tv_sec + autoCPWInterval;
118         memcpy(&random_value[0], &time, 8);
119         memcpy(&random_value[2], &time, 8);
120     }
121         
122     if ((++totalUpdates >= autoCPWUpdates) &&
123         tt &&                           /* a write transaction */
124         ((admin && (time.tv_sec >= nextAutoCPWTime)) ||
125          (time.tv_sec >= nextAutoCPWTime + autoCPWInterval))) {
126         struct ktc_encryptionKey key;
127         char  buf[4*sizeof(key)+1];
128         struct kaentry tentry;
129         afs_int32   code;
130         char bob[KA_TIMESTR_LEN];
131
132         ka_timestr(time.tv_sec,bob,KA_TIMESTR_LEN);
133         es_Report ("Auto CPW at %s\n", bob);
134         if (!admin) es_Report (" ... even though no ADMIN user\n");
135
136         code = FindBlock (tt, KA_ADMIN_NAME, KA_ADMIN_INST, &to, &tentry);
137         if (code) return code;
138         if (to) {                       /* check if auto cpw is disabled */
139             if (!(ntohl(tentry.flags) & KAFNOCPW)) {
140                 memcpy(&key, &random_value[0], sizeof(key));
141                 des_fixup_key_parity (&key);
142                 code = set_password (tt, KA_ADMIN_NAME, KA_ADMIN_INST,
143                                      &key, 0, 0);
144                 if (code == 0) {
145                     des_init_random_number_generator (&key);
146                     ka_ConvertBytes (buf, sizeof(buf), (char *)&key, 
147                                      sizeof(key));
148                     es_Report ("New Admin key is %s\n", buf);
149                 } else {
150                     es_Report ("in get_time: set_password failed because: %d\n", code);
151                     return code;
152                 }
153             }
154         }
155
156         code = FindBlock(tt, KA_TGS_NAME, lrealm, &to, &tentry);
157         if (code) return code;
158         if (to) {                       /* check if auto cpw is disabled */
159             if (!(ntohl(tentry.flags) & KAFNOCPW)) {
160                 memcpy(&key, &random_value[2], sizeof(key));
161                 des_fixup_key_parity (&key);
162                 code = set_password (tt, KA_TGS_NAME, lrealm, &key, 0, 0);
163                 if (code == 0) {
164                     ka_ConvertBytes (buf, sizeof(buf), (char *)&key, 
165                                      sizeof(key));
166                     es_Report ("New TGS key is %s\n", buf);
167                 } else {
168                     es_Report ("in get_time: set_password failed because: %s\n", error_message (code));
169                     return code;
170                 }
171             }
172         }
173         code = ka_FillKeyCache (tt);    /* ensure in-core copy is uptodate */
174         if (code) return code;
175
176         nextAutoCPWTime = time.tv_sec + autoCPWInterval;
177         totalUpdates = 0;
178     }
179     if (timeP) *timeP = time.tv_sec;
180     return 0;
181 }
182
183 static int noAuthenticationRequired;    /* global state */
184 static int recheckNoAuth;               /* global state */
185
186 /* kaprocsInited is sort of a lock: during a transaction only one process runs
187    while kaprocsInited is false. */
188
189 static int kaprocsInited = 0;
190
191 /* This variable is protected by the kaprocsInited flag. */
192
193 static int (*rebuildDatabase)();
194
195 /* This is called to initialize the database */
196
197 static int initialize_database (tt)
198   struct ubik_trans *tt;
199 {   struct ktc_encryptionKey key;
200     int           code;
201
202     gettimeofday((struct timeval *)&key, 0);    /* this is just a cheap seed key */
203     des_fixup_key_parity (&key);
204     des_init_random_number_generator (&key);
205     if ((code = des_random_key (&key)) ||
206         (code = create_user (tt, KA_ADMIN_NAME, KA_ADMIN_INST,
207                              &key, 0, KAFNORMAL|KAFNOSEAL|KAFNOTGS)))
208         return code;
209     if ((code = des_random_key (&key)) ||
210         (code = create_user (tt, KA_TGS_NAME, lrealm,
211                              &key, 0, KAFNORMAL|KAFNOSEAL|KAFNOTGS)))
212         return code;
213     return 0;
214 }
215
216 /* This routine handles initialization required by this module.  The initFlags
217    parameter passes some information about the command line arguments. */
218
219 afs_int32 init_kaprocs(lclpath, initFlags)
220   char *lclpath;
221   int   initFlags;
222 {   int                 code;
223     struct ubik_trans  *tt;
224     struct ktc_encryptionKey key;
225     afs_int32           kvno;
226
227     kaprocsInited = 0;
228     if (myHost == 0) return KAINTERNALERROR;
229     if (KA_conf == 0) return KAINTERNALERROR;
230     code = afsconf_GetLocalCell (KA_conf, lrealm, sizeof(lrealm));
231     if (code) {
232         printf("** Can't determine local cell name!\n");
233         return KANOCELLS;
234     }
235     ucstring (lrealm, lrealm, sizeof(lrealm));
236
237     recheckNoAuth = 1;
238     if (initFlags & 1) noAuthenticationRequired = 1;
239     if (initFlags & 2) recheckNoAuth = 0;
240     if (recheckNoAuth)
241         noAuthenticationRequired = afsconf_GetNoAuthFlag(KA_conf);
242     if (noAuthenticationRequired)
243         printf ("Running server with security disabled\n");
244
245     if (initFlags & 4) {
246         autoCPWInterval = 10;
247         autoCPWUpdates = 10;
248     } else {
249         autoCPWInterval = AUTOCPWINTERVAL;
250         autoCPWUpdates = AUTOCPWUPDATES;
251     }
252
253     init_kadatabase (initFlags);
254     rebuildDatabase = initialize_database;
255
256     if (code = InitAuthServ (&tt, LOCKREAD, 0)) {
257         printf ("init_kaprocs: InitAuthServ failed: code = %d\n", code);
258         return code;
259     }
260     code = ka_LookupKey (tt, KA_ADMIN_NAME, KA_ADMIN_INST, &kvno, &key);
261     if (code) {
262         ubik_AbortTrans(tt);
263         printf ("init_kaprocs: ka_LookupKey (code = %d) DB not initialized properly?\n", code);
264         return code;
265     }
266     des_init_random_number_generator (&key);
267
268     code = ubik_EndTrans(tt);
269     if (code) {
270         printf ("init_kaprocs: ubik_EndTrans failed: code = %d\n", code);
271         return code;
272     }
273
274     kaux_opendb(lclpath);            /* aux database stores failure counters */
275     rebuildDatabase = 0;                /* only do this during init */
276     kaprocsInited = 1;
277     return 0;
278 }
279
280 /* These variable are for returning debugging info about the state of the
281    server.  If they get trashed during multi-threaded operation it doesn't
282    matter. */
283
284 /* this is global so COUNT_REQ in krb_udp.c can refer to it. */
285 char *lastOperation = 0;                        /* name of last operation */
286 static Date  lastTrans;                 /* time of last transaction */
287
288 static char adminPrincipal[256];
289 static char authPrincipal[256];
290 static char tgsPrincipal[256];
291 static char tgsServerPrincipal[256];
292
293 void save_principal (p, n, i, c)
294   char *p, *n, *i, *c;
295 {   int s = 255;
296     int l;
297
298     l = strlen (n);
299     if (l > s) return;
300     strcpy (p, n);
301     s -= l;
302     if (i && strlen (i)) {
303         if (s-- <= 0) return;
304         strcat (p, ".");
305         l = strlen (i);
306         if (l > s) return;
307         strcat (p, i);
308         s -= l;
309     }
310     if (c && strlen(c)) {
311         if (s-- <= 0) return;
312         strcat (p, "@");
313         l = strlen (c);
314         if (l > s) return;
315         strcat (p, c);
316     }
317 }
318
319 static afs_int32 check_auth (call, at, admin, acaller_id)
320   struct rx_call      *call;
321   struct ubik_trans   *at;
322   int                  admin;           /* require caller to be ADMIN */
323   afs_int32                   *acaller_id;
324 {   rxkad_level     level;
325     char            name[MAXKTCNAMELEN];
326     char            instance[MAXKTCNAMELEN];
327     char            cell[MAXKTCREALMLEN];
328     afs_int32       kvno;
329     Date            expiration;         /* checked by Security Module */
330     struct kaentry  tentry;
331     int             code;
332     int             si;
333
334     *acaller_id = 0;
335
336     if (recheckNoAuth)
337         noAuthenticationRequired = afsconf_GetNoAuthFlag(KA_conf);
338
339     si = rx_SecurityClassOf(rx_ConnectionOf(call));
340     if (si == RX_SCINDEX_VAB) {
341         printf ("No support for VAB security module yet.\n");
342         return -1;
343     } else if (si == RX_SCINDEX_NULL) {
344         code = KANOAUTH;
345         goto no_auth;
346     } else if (si != RX_SCINDEX_KAD) {
347         es_Report ("Unknown security index %d\n", si);
348         return -1;
349     }
350
351     code = rxkad_GetServerInfo (rx_ConnectionOf(call), &level, &expiration,
352                                 name, instance, cell, &kvno);
353     if (code) {
354       goto no_auth;
355     }
356     if (level != rxkad_crypt) {
357         es_Report ("Incorrect security level = %d\n", level);
358         code = KANOAUTH;
359         goto no_auth;
360     }
361
362     if (!name_instance_legal (name, instance)) return KABADNAME;
363     if (strlen (cell)) {
364         ka_PrintUserID ("Authorization rejected because we don't understand intercell stuff yet: ",
365                       name, instance, "");
366         printf ("@%s\n", cell);
367         return KANOAUTH;
368     }
369
370     code = FindBlock(at, name, instance, acaller_id, &tentry);
371     if (code) return code;
372     if (*acaller_id == 0) {
373         ka_PrintUserID ("User ", name, instance, " unknown.\n");
374         return KANOENT;
375     }
376     save_principal (adminPrincipal, name, instance, 0);
377
378     if (admin) {
379       if (!(ntohl(tentry.flags) & KAFADMIN)) {
380          if (noAuthenticationRequired) {
381             ka_PrintUserID ("Authorization approved for ", name, instance,
382                           " because there is no authentication required\n");
383             osi_auditU (call, UnAuthEvent, code, AUD_STR, name, AUD_STR, instance, AUD_STR, cell, AUD_END);
384             return 0;
385         }
386         ka_PrintUserID ("User ", name, instance, " is not ADMIN.\n");
387         return KANOAUTH;
388        }
389       osi_auditU (call, UseOfPrivilegeEvent, code, AUD_STR,name, AUD_STR,instance, AUD_STR,cell, AUD_END);
390     }
391     return 0;
392
393 no_auth:
394     if (noAuthenticationRequired) {
395       es_Report ("Caller w/o authorization approved no authentication required\n");
396       osi_auditU (call, UnAuthEvent, code, AUD_STR, name, AUD_STR, instance, AUD_STR, cell, AUD_END);
397       return 0;
398     }
399     return code;                /* no auth info */
400 }
401
402 afs_int32 AwaitInitialization ()
403 {   afs_int32 start = 0;
404     while (!kaprocsInited) {
405         if (!start) start = time(0);
406         else if (time(0)-start > 5) return UNOQUORUM;
407         IOMGR_Sleep (1);
408     }
409     return 0;
410 }
411
412 /* This is called by every RPC interface to create a Ubik transaction and read
413    the database header into core */
414
415 afs_int32 InitAuthServ (tt, lock, this_op)
416   struct ubik_trans **tt;
417   int                 lock;             /* indicate read/write transaction */
418   int                *this_op;          /* opcode of RPC proc, for COUNT_ABO */
419 {   int   code;
420     afs_int32  start = 0;                       /* time started waiting for quorum */
421     float wait = 0.91;                  /* start waiting for 1 second */
422
423     /* Wait for server initialization to finish if not during init_kaprocs */
424     if (this_op) if (code = AwaitInitialization()) return code;
425
426     for (code = UNOQUORUM; code == UNOQUORUM; ) {
427         if (lock == LOCKREAD)
428             code = ubik_BeginTransReadAny (KA_dbase, UBIK_READTRANS, tt);
429         else code = ubik_BeginTrans (KA_dbase, UBIK_WRITETRANS, tt);
430         if (code == UNOQUORUM) {        /* no quorum elected */
431             if (!start) start = time(0);
432             else {
433                 int delay = time(0) - start;
434                 if (this_op) {          /* punt quickly, if RPC call */
435                     if (delay > 5) return code;
436                 } else {                /* more patient during init. */
437                     if (delay > 500) return code;
438                 }
439             }
440             printf ("Waiting for quorum election.\n");
441             if (wait < 15.0) wait *= 1.1;
442             IOMGR_Sleep ((int)wait);
443         }
444     }
445     if (code) return code;
446     if (code = ubik_SetLock (*tt, 1, 1, lock)) {
447         if (this_op) COUNT_ABO;
448         ubik_AbortTrans (*tt);
449         return code;
450     }
451     /* check that dbase is initialized and setup cheader */
452     if (lock == LOCKREAD) {
453         /* init but don't fix because this is read only */
454         code = CheckInit(*tt, 0);
455         if (code) {
456             ubik_AbortTrans (*tt);      /* abort, since probably I/O error */
457             /* we did the check under a ReadAny transaction, but now, after
458              * getting a write transaction (and thus some real guarantees
459              * about what databases are really out there), we will check again
460              * in CheckInit before nuking the database.  Since this may now get
461              * a UNOQUORUM we'll just do this from the top.
462              */
463             if (code = InitAuthServ (tt, LOCKWRITE, this_op)) return code;
464             if (code = ubik_EndTrans(*tt)) return code;
465
466             /* now open the read transaction that was originally requested. */
467             return InitAuthServ (tt, lock, this_op);
468         }
469     }
470     else {
471         if (code = CheckInit(*tt, rebuildDatabase)) {
472             if (this_op) COUNT_ABO;
473             ubik_AbortTrans(*tt);
474             return code;
475         }
476     }
477     lastTrans = time(0);
478     ka_FillKeyCache (*tt);              /* ensure in-core copy is uptodate */
479     return 0;
480 }
481
482 /* returns true if name is specially known by AuthServer */
483
484 static int special_name (name, instance)
485   char *name;
486   char *instance;
487 {
488     return ((!strcmp (name, KA_TGS_NAME) && !strcmp(instance, lrealm)) ||
489             (strcmp (name, KA_ADMIN_NAME) == 0));
490 }
491
492 static int create_user (tt, name, instance, key, caller, flags)
493   struct ubik_trans *tt;
494   char              *name;
495   char              *instance;
496   EncryptionKey     *key;
497   afs_int32                  caller;
498   afs_int32                  flags;
499 {   register int       code;
500     afs_int32          to;
501     struct kaentry     tentry;
502     afs_int32          maxLifetime;
503   
504     code = FindBlock(tt, name, instance, &to, &tentry);
505     if (code) return code;
506     if (to) return KAEXIST;             /* name already exists, we fail */
507     
508     to = AllocBlock(tt, &tentry);
509     if (to == 0) return KACREATEFAIL;
510
511     /* otherwise we have a block */
512     strncpy(tentry.userID.name, name, sizeof(tentry.userID.name));
513     strncpy(tentry.userID.instance, instance, sizeof(tentry.userID.instance));
514     tentry.flags = htonl(flags);
515     if (special_name (name, instance)) { /* this overrides key & version */
516         tentry.flags = htonl (ntohl(tentry.flags) | KAFSPECIAL);
517         tentry.key_version = htonl(-1); /* don't save this key */
518         if (code = ka_NewKey (tt, to, &tentry, key)) return code;
519     }
520     else {
521         memcpy(&tentry.key, key, sizeof(tentry.key));
522         tentry.key_version = htonl(0);
523     }
524     tentry.user_expiration = htonl(NEVERDATE);
525     code = get_time (&tentry.modification_time, tt, 1);
526     if (code) return code;
527
528     /* time and addr of entry for guy changing this entry */
529     tentry.modification_time = htonl(tentry.modification_time);
530     tentry.modification_id = htonl(caller);
531     tentry.change_password_time = tentry.modification_time;
532
533     if (strcmp (name, KA_TGS_NAME) == 0) maxLifetime = MAXKTCTICKETLIFETIME;
534     else if (strcmp (name, KA_ADMIN_NAME) == 0) maxLifetime = 10*3600;
535     else if (strcmp (name, AUTH_SUPERUSER) == 0) maxLifetime = 100*3600;
536     else maxLifetime = 25*3600;         /* regular users */
537     tentry.max_ticket_lifetime = htonl(maxLifetime);
538
539     code = ThreadBlock (tt, to, &tentry);
540     return code;
541 }
542
543 /* Put actual stub routines here */
544
545 afs_int32 KAM_CreateUser (call, aname, ainstance, ainitpw)
546   struct rx_call *call;
547   char           *aname;
548   char           *ainstance;
549   EncryptionKey   ainitpw;
550 {
551   afs_int32   code;
552
553   code = kamCreateUser (call, aname, ainstance, ainitpw);
554   osi_auditU (call, AFS_KAM_CrUserEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
555   return code;
556 }
557
558
559 afs_int32 kamCreateUser (call, aname, ainstance, ainitpw)
560   struct rx_call *call;
561   char           *aname;
562   char           *ainstance;
563   EncryptionKey   ainitpw;
564 {   register int       code;
565     struct ubik_trans *tt;
566     afs_int32          caller;          /* Disk offset of caller's entry */
567
568     COUNT_REQ (CreateUser);
569     if (!des_check_key_parity (&ainitpw) ||
570         des_is_weak_key (&ainitpw)) return KABADKEY;
571     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
572     if (code = InitAuthServ( &tt, LOCKWRITE, this_op)) return code;
573     code = check_auth (call, tt, 1, &caller);
574     if (code) {
575         COUNT_ABO;
576         ubik_AbortTrans(tt);
577         return code;
578     }
579     code = create_user (tt, aname, ainstance, &ainitpw, caller, KAFNORMAL);
580     if (code) {
581         COUNT_ABO;
582         ubik_AbortTrans(tt);
583         return code;
584     }
585     code = ubik_EndTrans(tt);
586     KALOG(aname, ainstance, NULL, NULL, NULL, call->conn->peer->host, LOG_CRUSER);
587     return code;
588 }
589
590 afs_int32 KAA_ChangePassword (call, aname, ainstance, arequest, oanswer)
591   struct rx_call      *call;
592   char                *aname;
593   char                *ainstance;
594   ka_CBS              *arequest;
595   ka_BBS              *oanswer;
596 {
597   afs_int32 code;
598
599   code = ChangePassWord (call, aname, ainstance, arequest, oanswer);
600   osi_auditU(call, AFS_KAA_ChPswdEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
601   return code;
602 }
603
604 afs_int32 ChangePassWord (call, aname, ainstance, arequest, oanswer)
605   struct rx_call      *call;
606   char                *aname;
607   char                *ainstance;
608   ka_CBS              *arequest;
609   ka_BBS              *oanswer;
610 {   register int       code;
611     struct ubik_trans *tt;
612     afs_int32          to;              /* offset of block */
613     struct kaentry     tentry;
614     struct ka_cpwRequest request;       /* request after decryption */
615     char              *answer;          /* where answer is to be put */
616     int                answer_len;      /* length of answer packet */
617     afs_int32          kvno;            /* requested key version number */
618     des_key_schedule   user_schedule;   /* key schedule for user's key */
619     Date               request_time;    /* time request originated */
620
621     COUNT_REQ (ChangePassword);
622     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
623     if (strcmp (ainstance, KA_ADMIN_NAME) == 0) return KABADNAME;
624     if (code = InitAuthServ (&tt, LOCKWRITE, this_op)) return code;
625
626     code = FindBlock (tt, aname, ainstance, &to, &tentry);
627     if (code) {
628       goto abort;
629     }
630     if (to == 0) {                      /* no such user */
631         code = KANOENT;
632         goto abort;
633     }
634     if (ntohl(tentry.flags) & KAFNOCPW)
635         { code = KABADCPW; goto abort; }
636
637     /* decrypt request w/ user password */
638     if (code = des_key_sched (&tentry.key, user_schedule))
639         es_Report ("In KAChangePassword: key_sched returned %d\n", code);
640     des_pcbc_encrypt (arequest->SeqBody, &request,
641                       min (arequest->SeqLen, sizeof(request)),
642                       user_schedule, &tentry.key, DECRYPT);
643
644     /* validate the request */
645     request_time = ntohl (request.time); /* reorder date */
646     kvno = ntohl(request.kvno);
647     if ((abs (request_time - time(0)) > KTC_TIME_UNCERTAINTY) ||
648         strncmp (request.label, KA_CPW_REQ_LABEL, sizeof(request.label)) ||
649         (request.spare) ||
650         (kvno > MAXKAKVNO)) {                   /* these are reseved */
651         code = KABADREQUEST;
652         goto abort;
653     }
654
655     /* check to see if the new password was used before, or if there has
656      * not been sufficient time since the last password change
657      */
658     code = impose_reuse_limits(&request.newpw, &tentry);
659     if (code) {
660         goto abort;
661     }
662
663     /* Create the Answer Packet */
664     answer_len = sizeof(Date) + KA_LABELSIZE;
665     if (oanswer->MaxSeqLen < answer_len) {
666         code = KAANSWERTOOLONG;
667         goto abort;
668     }
669     oanswer->SeqLen = answer_len;
670     answer = oanswer->SeqBody;
671     request.time = htonl (request_time+1);
672     memcpy(answer, (char *)&request.time, sizeof(Date));
673     answer += sizeof(Date);
674     memcpy(answer, KA_CPW_ANS_LABEL, KA_LABELSIZE);
675
676     des_pcbc_encrypt (oanswer->SeqBody, oanswer->SeqBody, answer_len,
677                       user_schedule, &tentry.key, ENCRYPT);
678
679     code = set_password (tt, aname, ainstance, &request.newpw, kvno, 0);
680     if (code) {
681         code = KAIO;
682         goto abort;
683     }
684
685     cheader.stats.cpws = htonl(ntohl(cheader.stats.cpws)+1);
686     code = kawrite(tt, DOFFSET(0, &cheader, &cheader.stats.cpws),
687                        (char *) &cheader.stats.cpws, sizeof(afs_int32));
688     if (code) {
689         code = KAIO;
690         goto abort;
691     }
692
693     code = ubik_EndTrans(tt);
694     return code;
695
696 abort:
697         COUNT_ABO;
698         ubik_AbortTrans (tt);
699         return code;
700 }
701
702 static afs_int32
703 impose_reuse_limits ( password, tentry )
704      EncryptionKey          *password;
705      struct kaentry *tentry;
706 {
707   int code;
708   Date now;
709   int i;
710   int reuse_p;
711   extern int MinHours;
712   afs_uint32 newsum;
713
714   if (!tentry->pwsums[0] && npwSums > 1 && !tentry->pwsums[1]) 
715     return 0;  /* password reuse limits not in effect */
716
717   code = get_time (&now,0,0);
718   if (code) return code;
719
720   if ((now - ntohl(tentry->change_password_time)) < MinHours*60*60) 
721     return KATOOSOON;
722
723   if (!memcmp(password, &(tentry->key), sizeof(EncryptionKey)))
724       return KAREUSED;
725
726   code = ka_KeyCheckSum ((char *)password, &newsum);
727   if (code)
728      return code;
729
730   newsum = newsum & 0x000000ff;
731   for (i=0; i<npwSums; i++) {
732       if (newsum == tentry->pwsums[i])
733          return KAREUSED;
734   }
735     
736 return 0;
737 }
738
739
740 static afs_int32
741 set_password (tt, name, instance, password, kvno, caller)
742   struct ubik_trans *tt;
743   char              *name;
744   char              *instance;
745   EncryptionKey     *password;
746   afs_int32                  kvno;
747   afs_int32                  caller;
748 {   afs_int32   code;
749     afs_int32      to;                  /* offset of block */
750     struct kaentry tentry;
751     Date  now;
752     int i;
753     extern int npwSums;
754     afs_uint32 newsum;
755
756     code = FindBlock (tt, name, instance, &to, &tentry);
757     if (code) return code;
758     if (to == 0) return KANOENT;        /* no such user */
759
760     /* if password reuse limits in effect, set the checksums, the hard way */
761     if (!tentry.pwsums[0] && npwSums > 1 && !tentry.pwsums[1]) {
762       /* do nothing, no limits */ ;
763     }
764     else {
765      code = ka_KeyCheckSum ((char *)&(tentry.key), &newsum);
766      if (code)
767        return code;
768      for (i=npwSums-1; i ; i--) 
769        tentry.pwsums[i] = tentry.pwsums[i-1];
770      tentry.pwsums[0] = newsum & 0x000000ff;
771     }
772     
773
774     if (special_name (name, instance)) { /* set key over rides key_version */
775         tentry.flags = htonl (ntohl(tentry.flags) | KAFSPECIAL);
776         if (code = ka_NewKey (tt, to, &tentry, password)) return(code);
777     }
778     else {
779         memcpy(&tentry.key, password, sizeof(tentry.key));
780         if (!kvno) {
781             kvno = ntohl(tentry.key_version);
782             if ((kvno < 1) || (kvno >= MAXKAKVNO))
783                 kvno = 1;
784             else
785                 kvno++;
786         }
787         tentry.key_version = htonl((afs_int32)kvno); /* requested key version */
788     }
789
790     
791
792     /* no-write prevents recursive call to set_password by AuthCPW code. */
793     code = get_time (&now,0,0);
794     if (code) return code;
795     if (caller) {
796         tentry.modification_time = htonl(now);
797         tentry.modification_id = htonl(caller);
798     }
799     
800     tentry.change_password_time = htonl(now);
801
802     if (code = kawrite (tt, to, &tentry, sizeof(tentry))) return(KAIO);
803     return(0);
804 }
805
806 afs_int32 KAM_SetPassword (call, aname, ainstance, akvno, apassword)
807   struct rx_call      *call;
808   char                *aname;
809   char                *ainstance;
810   afs_int32                    akvno;
811   EncryptionKey        apassword;
812 {
813   afs_int32   code;
814
815   code = kamSetPassword (call, aname, ainstance, akvno, apassword);
816   osi_auditU (call, AFS_KAM_SetPswdEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
817   return code;
818 }
819
820 afs_int32 kamSetPassword (call, aname, ainstance, akvno, apassword)
821   struct rx_call      *call;
822   char                *aname;
823   char                *ainstance;
824   afs_int32                    akvno;
825   EncryptionKey        apassword;
826 {   register int       code;
827     struct ubik_trans *tt;
828     afs_int32          caller;          /* Disk offset of caller's entry */
829     struct kaentry     tentry;
830
831     COUNT_REQ (SetPassword);
832     if (akvno > MAXKAKVNO) return KABADARGUMENT;
833     if (!des_check_key_parity (&apassword) ||
834         des_is_weak_key (&apassword)) return KABADKEY;
835
836     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
837     if (code = InitAuthServ (&tt, LOCKWRITE, this_op)) return code;
838     code = check_auth (call, tt, 0, &caller);
839     if (code) {
840         goto abort;
841     }
842     if (code = karead (tt, caller, &tentry, sizeof(tentry))) {
843         code = KAIO;
844         goto abort;
845     }
846     /* if the user is changing his own password or ADMIN then go ahead. */
847     if ((strcmp (tentry.userID.name, aname) == 0) &&
848         (strcmp (tentry.userID.instance, ainstance) == 0)) {
849         if (ntohl(tentry.flags) & KAFNOCPW) 
850           code = KABADCPW;
851         else {
852           code = impose_reuse_limits(&apassword, &tentry);
853           if (!code)
854             code = set_password (tt, aname, ainstance, &apassword, akvno, 0);
855         }
856     } else if (ntohl(tentry.flags) & KAFADMIN) {
857         code = set_password (tt, aname, ainstance, &apassword, akvno, caller);
858       }
859     else code = KANOAUTH;
860     if (code) goto abort;
861
862     code = ubik_EndTrans(tt);
863     KALOG(aname, ainstance, NULL, NULL, NULL, call->conn->peer->host, LOG_CHPASSWD);
864     return code;
865
866 abort:
867         COUNT_ABO;
868         ubik_AbortTrans(tt);
869         return code;
870 }
871
872 static Date CoerseLifetime (start, end)
873   Date start, end;
874 {
875     unsigned char kerberosV4Life;
876     kerberosV4Life = time_to_life (start, end);
877     end = life_to_time (start, kerberosV4Life);
878     return end;
879 }
880
881 static afs_int32 GetEndTime (start, reqEnd, expiration, caller, server, endP)
882   IN Date start;                        /* start time of ticket */
883   IN Date reqEnd;                       /* requested end time */
884   IN Date expiration;                   /* authorizing ticket's expiration */
885   IN struct kaentry *caller;
886   IN struct kaentry *server;
887   OUT Date *endP;                       /* actual end time */
888 {
889     Date cExp, sExp;
890     Date cLife, sLife;
891     Date end;
892
893     if (ntohl(caller->flags) & KAFNOTGS)
894         return KABADUSER;               /* no new tickets for this user */
895     if (expiration && (ntohl(server->flags) & KAFNOSEAL))
896         return KABADSERVER;             /* can't be target of GetTicket req */
897     if (!expiration) expiration = NEVERDATE;
898
899     cExp = ntohl(caller->user_expiration);
900     sExp = ntohl(server->user_expiration);
901     if (cExp < start) return KAPWEXPIRED;
902     if (sExp < start) return KABADSERVER;
903     cLife = start + ntohl(caller->max_ticket_lifetime);
904     sLife = start + ntohl(server->max_ticket_lifetime);
905     end = umin (umin (reqEnd, expiration),
906                 umin (umin (cLife,sLife),
907                       umin (cExp, sExp)));
908     end = CoerseLifetime (start, end);
909     *endP = end;
910     return 0;
911 }
912
913 static afs_int32 
914 PrepareTicketAnswer
915     (oanswer, challenge, ticket, ticketLen, sessionKey,
916      start, end, caller, server, cell, label)
917   ka_BBS *oanswer;
918   afs_int32 challenge;  
919   char *ticket;
920   afs_int32  ticketLen;
921   struct ktc_encryptionKey *sessionKey;
922   Date  start, end;
923   struct kaentry *caller, *server;
924   char *cell;
925   char *label;
926 {
927     afs_int32 code;
928     struct ka_ticketAnswer *answer;
929     afs_int32 cksum;
930
931     code = KAANSWERTOOLONG;
932     if (oanswer->MaxSeqLen < sizeof(struct ka_ticketAnswer) - 5*MAXKTCNAMELEN)
933         return code;
934
935     answer = (struct ka_ticketAnswer *)oanswer->SeqBody;
936     answer->challenge = htonl(challenge);
937     memcpy(&answer->sessionKey, sessionKey, sizeof(struct ktc_encryptionKey));
938     answer->startTime = htonl(start);
939     answer->endTime = htonl(end);
940     answer->kvno = server->key_version;
941     answer->ticketLen = htonl(ticketLen);
942
943     {   char *ans = answer->name;       /* pointer to variable part */
944         int   rem;                      /* space remaining */
945         int   len;                      /* macro temp. */
946
947         rem = oanswer->MaxSeqLen - (ans - oanswer->SeqBody);
948 #undef putstr
949 #define putstr(str) len = strlen (str)+1;\
950                     if (rem < len) return code;\
951                     strcpy (ans, str);\
952                     ans += len; rem -= len
953         putstr (caller->userID.name);
954         putstr (caller->userID.instance);
955         putstr (cell);
956         putstr (server->userID.name);
957         putstr (server->userID.instance);
958         if (rem < ticketLen+KA_LABELSIZE) return code;
959         memcpy(ans, ticket, ticketLen);
960         ans += ticketLen;
961         if (label) memcpy(ans, label, KA_LABELSIZE);
962         else memset(ans, 0, KA_LABELSIZE);
963         ans += KA_LABELSIZE;
964         oanswer->SeqLen = (ans - oanswer->SeqBody);
965     }
966     cksum = 0;
967     answer->cksum = htonl(cksum);
968     oanswer->SeqLen = round_up_to_ebs(oanswer->SeqLen);
969     if (oanswer->SeqLen > oanswer->MaxSeqLen) return code;
970     return 0;
971 }
972
973 /* This is used to get a ticket granting ticket or an admininstration ticket.
974    These two specific, built-in servers are special cases, which require the
975    client's key as an additional security precaution.  The GetTicket operation
976    is normally disabled for these two principals. */
977
978 static afs_int32 Authenticate (version, call, aname, ainstance, start, end,
979                           arequest, oanswer)
980   int   version;
981   struct rx_call *call;
982   char *aname;
983   char *ainstance;
984   Date  start, end;
985   ka_CBS *arequest;
986   ka_BBS *oanswer;
987 {   int                code;
988     struct ubik_trans *tt;
989     afs_int32          to;              /* offset of block */
990     kaentry            tentry;
991     struct kaentry     server;          /* entry for desired server */
992     struct ka_gettgtRequest request;    /* request after decryption */
993     int                tgt, adm;        /* type of request */
994     char              *sname;           /* principal of server */
995     char              *sinst;
996     char               ticket[MAXKTCTICKETLEN]; /* our copy of the ticket */
997     int                ticketLen;
998     struct ktc_encryptionKey sessionKey; /* we have to invent a session key */
999     char              *answer;          /* where answer is to be put */
1000     int                answer_len;      /* length of answer packet */
1001     Date               answer_time;     /* 1+ request time in network order */
1002     afs_int32          temp;            /* for htonl conversions */
1003     des_key_schedule   user_schedule;   /* key schedule for user's key */
1004     afs_int32          tgskvno;         /* key version of service key */
1005     struct ktc_encryptionKey tgskey;    /* service key for encrypting ticket */
1006     Date               now;
1007     afs_uint32            pwexpires;
1008     afs_uint32            lasttime;
1009
1010     COUNT_REQ (Authenticate);
1011     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
1012     if (code = InitAuthServ (&tt, LOCKREAD, this_op)) return code;
1013     get_time(&now, 0, 0);
1014
1015     sname = sinst = NULL;
1016
1017     code = FindBlock (tt, aname, ainstance, &to, &tentry);
1018     if (code) {
1019         goto abort;
1020     }
1021     if (to == 0) {                      /* no such user */
1022         code = KANOENT;
1023         goto abort;
1024     }
1025
1026 #ifdef LOCKPW
1027     /* have to check for locked before verifying the password, otherwise all
1028      * KALOCKED means is "yup, you guessed the password all right, now wait a 
1029      * few minutes and we'll let you in"
1030      */
1031     if (kaux_islocked(to, (u_int) tentry.misc_auth_bytes[ATTEMPTS], 
1032                       (afs_uint32) tentry.misc_auth_bytes[LOCKTIME] << 9)) {
1033       code = KALOCKED;  
1034       goto abort;
1035     }
1036 #endif /* LOCKPW */
1037
1038     save_principal (authPrincipal, aname, ainstance, 0);
1039
1040     /* decrypt request w/ user password */
1041     if (code = des_key_sched (&tentry.key, user_schedule))
1042         es_Report ("In KAAuthenticate: key_sched returned %d\n", code);
1043     des_pcbc_encrypt (arequest->SeqBody, &request,
1044                       min (arequest->SeqLen, sizeof(request)),
1045                       user_schedule, &tentry.key, DECRYPT);
1046
1047     request.time = ntohl (request.time); /* reorder date */
1048     tgt = !strncmp (request.label, KA_GETTGT_REQ_LABEL, sizeof(request.label));
1049     adm = !strncmp (request.label, KA_GETADM_REQ_LABEL, sizeof(request.label));
1050     if (!(tgt || adm)) {
1051         kaux_inc(to,((unsigned char) tentry.misc_auth_bytes[LOCKTIME]) << 9); 
1052         code = KABADREQUEST;
1053         goto abort;
1054     }
1055     else kaux_write(to, 0, 0);   /* reset counters */
1056
1057 #ifdef EXPIREPW
1058     if (! tentry.misc_auth_bytes[EXPIRES]) {
1059       /* 0 in the database means never, but 0 on the network means today */
1060       /* 255 on the network means "long time, maybe never" */
1061       pwexpires = 255;
1062     }
1063     else {
1064       pwexpires = tentry.misc_auth_bytes[EXPIRES];
1065       
1066       pwexpires = ntohl(tentry.change_password_time) + 24*60*60*pwexpires;
1067       if (adm) {             /* provide a little slack for admin ticket */
1068         pwexpires += 30*24*60*60;       /*  30 days */
1069       }
1070       if ( pwexpires < now ) {
1071         code = KAPWEXPIRED;
1072         goto abort;
1073       }
1074       else {
1075         pwexpires = (pwexpires - now)/ (24*60*60); 
1076         if (pwexpires > 255)
1077           pwexpires = 255; 
1078       }
1079     }
1080 #endif /* EXPIREPW */
1081
1082     if (abs (request.time - now) > KTC_TIME_UNCERTAINTY) {
1083 #if 0
1084         if (oanswer->MaxSeqLen < sizeof(afs_int32)) code = KAANSWERTOOLONG;
1085         else {                          /* return our time if possible */
1086             oanswer->SeqLen = sizeof(afs_int32);
1087             request.time = htonl(now);
1088             memcpy(oanswer->SeqBody, &request.time, sizeof(afs_int32));
1089         }
1090 #endif
1091         code = KACLOCKSKEW;
1092         goto abort;
1093     }
1094     sname = (tgt ? KA_TGS_NAME : KA_ADMIN_NAME);
1095     sinst = (tgt ? lrealm : KA_ADMIN_INST);
1096     code = FindBlock (tt, sname, sinst, &to, &server);
1097     if (code) goto abort;
1098     if (to == 0) {code = KANOENT; goto abort; }
1099
1100     tgskvno = ntohl(server.key_version);
1101     memcpy(&tgskey, &server.key, sizeof(tgskey));
1102
1103     code = des_random_key (&sessionKey);
1104     if (code) {
1105         code = KANOKEYS;
1106         goto abort;
1107     }
1108
1109     code = GetEndTime (start, end, 0/*!GetTicket*/, &tentry, &server, &end);
1110     if (code) goto abort;
1111
1112     code = tkt_MakeTicket (ticket, &ticketLen, &tgskey,
1113                            aname, ainstance, "", start, end, &sessionKey,
1114                            rx_HostOf(rx_PeerOf(rx_ConnectionOf(call))),
1115                            sname, sinst);
1116     if (code) goto abort;
1117
1118     switch (version) {
1119       case 0:
1120         answer_len = ticketLen + sizeof(Date) +
1121             sizeof(struct ktc_encryptionKey) + 2*sizeof(afs_int32) + KA_LABELSIZE;
1122         answer_len = round_up_to_ebs(answer_len);
1123         if (answer_len > oanswer->MaxSeqLen) {
1124             code = KAANSWERTOOLONG;
1125             goto abort;
1126         }
1127         oanswer->SeqLen = answer_len;
1128         answer = oanswer->SeqBody;
1129         answer_time = htonl(request.time+1);
1130         memcpy(answer, (char *)&answer_time, sizeof(Date));
1131         answer += sizeof(Date);
1132         memcpy(answer, (char *)&sessionKey, sizeof(struct ktc_encryptionKey));
1133         answer += sizeof(struct ktc_encryptionKey);
1134         temp = htonl(tgskvno);
1135         memcpy(answer, (char *)&temp, sizeof(afs_int32));
1136         answer += sizeof(afs_int32);
1137         temp = htonl(ticketLen);
1138         memcpy(answer, (char *)&temp, sizeof(afs_int32));
1139         answer += sizeof(afs_int32);
1140         memcpy(answer, ticket, ticketLen);
1141         answer += ticketLen;
1142         memcpy(answer, (tgt ? KA_GETTGT_ANS_LABEL : KA_GETADM_ANS_LABEL), KA_LABELSIZE);
1143         break;
1144       case 1:
1145       case 2:
1146         code = PrepareTicketAnswer
1147             (oanswer, request.time+1, ticket, ticketLen, &sessionKey,
1148              start, end, &tentry, &server, "",
1149              (tgt ? KA_GETTGT_ANS_LABEL : KA_GETADM_ANS_LABEL));
1150         if (code) goto abort;
1151 #ifdef EXPIREPW
1152         if ((version == 2) && oanswer->SeqLen < oanswer->MaxSeqLen + sizeof(afs_int32)) {
1153            temp = pwexpires << 24;    /* move it into the high byte */
1154            pwexpires = htonl(temp);
1155
1156            memcpy((char * )oanswer->SeqBody + oanswer->SeqLen, &pwexpires, sizeof(afs_int32));
1157            oanswer->SeqLen += sizeof(afs_int32);
1158            oanswer->SeqLen = round_up_to_ebs(oanswer->SeqLen);
1159            if (oanswer->SeqLen > oanswer->MaxSeqLen) {
1160              code = KAANSWERTOOLONG;
1161              goto abort;
1162            }
1163         }
1164 #endif /* EXPIREPW */
1165         break;
1166
1167       default:
1168         code = KAINTERNALERROR;
1169         goto abort;
1170     }
1171     des_pcbc_encrypt (oanswer->SeqBody, oanswer->SeqBody, oanswer->SeqLen,
1172                       user_schedule, &tentry.key, ENCRYPT);
1173     code = ubik_EndTrans(tt);
1174     KALOG(aname, ainstance, sname, sinst, NULL, call->conn->peer->host, LOG_AUTHENTICATE);
1175     return code;
1176
1177 abort:               
1178         COUNT_ABO;
1179         ubik_AbortTrans (tt);
1180         KALOG(aname, ainstance, sname, sinst, NULL, call->conn->peer->host, LOG_AUTHFAILED);
1181         return code;
1182 }
1183
1184 afs_int32 KAA_Authenticate_old (call, aname, ainstance, start, end,
1185                            arequest, oanswer)
1186   struct rx_call      *call;
1187   char                *aname;
1188   char                *ainstance;
1189   Date                 start, end;
1190   ka_CBS              *arequest;
1191   ka_BBS              *oanswer;
1192 {
1193   int code;
1194
1195   IOMGR_Sleep (1);  /* discourage use of this mechanism */
1196   code = Authenticate (0, call, aname, ainstance, start, end,
1197                          arequest, oanswer);
1198   osi_auditU(call, AFS_KAA_AuthOEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
1199
1200   return code;
1201 }
1202
1203 afs_int32 KAA_Authenticate (call, aname, ainstance, start, end, arequest, oanswer)
1204   struct rx_call      *call;
1205   char                *aname;
1206   char                *ainstance;
1207   Date                 start, end;
1208   ka_CBS              *arequest;
1209   ka_BBS              *oanswer;
1210 {
1211   int code;
1212
1213   code = Authenticate (1, call, aname, ainstance, start, end,
1214                          arequest, oanswer);
1215   osi_auditU(call, AFS_KAA_AuthEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
1216
1217   return code;
1218 }
1219
1220 afs_int32 KAA_AuthenticateV2 (call, aname, ainstance, start, end, arequest, oanswer)
1221   struct rx_call      *call;
1222   char                *aname;
1223   char                *ainstance;
1224   Date                 start, end;
1225   ka_CBS              *arequest;
1226   ka_BBS              *oanswer;
1227 {
1228   int code;
1229
1230   code = Authenticate (2, call, aname, ainstance, start, end,
1231                          arequest, oanswer);
1232   osi_auditU(call, AFS_KAA_AuthEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
1233
1234   return code;
1235 }
1236
1237 afs_int32 KAM_SetFields (call, aname, ainstance, aflags,
1238                     aexpiration, alifetime, amaxAssociates, misc_auth_bytes, spare2)
1239   struct rx_call      *call;
1240   char                *aname;
1241   char                *ainstance;
1242   afs_int32                    aflags;
1243   Date                 aexpiration;
1244   afs_int32                    alifetime;
1245   afs_int32                    amaxAssociates;
1246   afs_uint32        misc_auth_bytes;  /* 4 bytes, each 0 means unspecified*/
1247   afs_int32 spare2;
1248 {
1249   afs_int32   code;
1250
1251   code = kamSetFields (call, aname, ainstance, aflags,
1252                        aexpiration, alifetime, amaxAssociates, misc_auth_bytes, spare2);
1253   osi_auditU (call, AFS_KAM_SetFldEvent, code, AUD_STR,  aname,
1254                                                AUD_STR,  ainstance,
1255                                                AUD_LONG, aflags,
1256                                                AUD_DATE, aexpiration,
1257                                                AUD_LONG, alifetime,
1258                                                AUD_LONG, amaxAssociates, 
1259                                                AUD_END);
1260   return code;
1261 }
1262
1263 afs_int32 kamSetFields (call, aname, ainstance, aflags,
1264                     aexpiration, alifetime, amaxAssociates, misc_auth_bytes, spare2)
1265   struct rx_call      *call;
1266   char                *aname;
1267   char                *ainstance;
1268   afs_int32                    aflags;
1269   Date                 aexpiration;
1270   afs_int32                    alifetime;
1271   afs_int32                    amaxAssociates;
1272   afs_uint32        misc_auth_bytes;  /* 4 bytes, each 0 means unspecified*/
1273   afs_int32 spare2;
1274 {   afs_int32  code;
1275     Date  now;
1276     struct ubik_trans *tt;
1277     afs_int32  caller;
1278     afs_int32  tentry_offset;           /* offset of entry */
1279     struct kaentry tentry;
1280     unsigned char newvals[4], oldvals[4];
1281     int i;
1282
1283     COUNT_REQ (SetFields);
1284
1285     if (spare2)
1286       return KABADARGUMENT; /* not supported yet... */
1287
1288     /* make sure we're supposed to do something */
1289     if (!(aflags || aexpiration || alifetime || (amaxAssociates >= 0) ||
1290           misc_auth_bytes ) ||
1291         ((aflags & ~KAFNORMAL) & ~KAF_SETTABLE_FLAGS))
1292         return KABADARGUMENT;           /* arguments no good */
1293     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
1294     if (code = InitAuthServ (&tt, LOCKWRITE, this_op)) return code;
1295     code = check_auth (call, tt, 1, &caller);
1296     if (code) {
1297       goto abort;
1298     }
1299
1300     code = FindBlock (tt, aname, ainstance, &tentry_offset, &tentry);
1301     if (code) goto abort;
1302     if (tentry_offset == 0) {                   /* no such user */
1303         code = KANOENT;
1304         goto abort;
1305     }
1306     if ((ntohl(tentry.flags) & KAFNORMAL) == 0) return KAINTERNALERROR;
1307     if (aflags) {
1308         /* Keep track of the total number of admin accounts.  This way we can
1309            update database without any admin privilege initially */
1310         if ((aflags & KAFADMIN) != (ntohl(tentry.flags) & KAFADMIN)) {
1311             /* if admin state is changing */
1312             int delta;
1313             if (ntohl(tentry.flags) & KAFADMIN) delta = -1;
1314             else delta = 1;
1315             if (code = update_admin_count (tt, delta)) goto abort;
1316         }
1317         tentry.flags =
1318             htonl((ntohl(tentry.flags) & ~KAF_SETTABLE_FLAGS) | aflags);
1319     }
1320     if (code = get_time (&now, tt, 1)) goto abort;
1321     if (aexpiration) {
1322       tentry.user_expiration = htonl(aexpiration);
1323       if (!ntohl(tentry.change_password_time)) {
1324         tentry.change_password_time = htonl(now);
1325       }
1326     }
1327     if (alifetime) tentry.max_ticket_lifetime = htonl(alifetime);
1328
1329 #ifndef NOPWCONTROLS
1330     /* 
1331      * We've packed a bunch of bytes into a long for backward compatibility.
1332      * These include password expiration time, and some failed login limits
1333      * counters.  Now let's unpack them and stick them into the
1334      * kaentry struct.  All the bytes have values in the range
1335      * 1..255, else they were not specified in the interface, and are
1336      * set to zero. 
1337      * In the case of password expiration times, 1 means password never
1338      * expires (==>0), 2 means password only lives for one day (==>1),
1339      * and so on.
1340      */
1341     if (misc_auth_bytes) {
1342        unpack_long(misc_auth_bytes, newvals);
1343        if (newvals[EXPIRES]) {
1344              tentry.misc_auth_bytes[EXPIRES] = newvals[EXPIRES] - 1;
1345            }
1346
1347        if (newvals[REUSEFLAGS]) {
1348           if (newvals[REUSEFLAGS] & KA_REUSEPW) 
1349             memset(tentry.pwsums, 0, KA_NPWSUMS);
1350           else if ((newvals[REUSEFLAGS] & KA_NOREUSEPW) && !tentry.pwsums[0])
1351              tentry.pwsums[0] = 0xff;
1352        }
1353
1354        if (newvals[ATTEMPTS]) {
1355              tentry.misc_auth_bytes[ATTEMPTS] = newvals[ATTEMPTS] - 1;
1356            }
1357        if (newvals[LOCKTIME]) {
1358              tentry.misc_auth_bytes[LOCKTIME] = newvals[LOCKTIME] - 1;
1359            }
1360 /*
1361        tentry.misc_auth_bytes = htonl(tentry.misc_auth_bytes);
1362 */
1363      }
1364 #endif /* NOPWCONTROLS */
1365
1366     if (amaxAssociates >= 0) {
1367         if ((ntohl(tentry.flags) & KAFASSOC) ||
1368             (ntohl(tentry.flags) & KAFSPECIAL)) return KAASSOCUSER;
1369         if (((ntohl(tentry.flags) & KAFASSOCROOT) == 0) &&
1370             (amaxAssociates > 0))       /* convert normal user to assoc root */
1371             tentry.flags = htonl(ntohl(tentry.flags) | KAFASSOCROOT);
1372         tentry.misc.assocRoot.maxAssociates = htonl(amaxAssociates);
1373     }
1374
1375     tentry.modification_time = htonl(now);
1376     tentry.modification_id = htonl(caller);
1377     code = kawrite (tt, tentry_offset, &tentry, sizeof(tentry));
1378     if (code) goto abort;
1379
1380     code = ubik_EndTrans(tt);
1381     KALOG(aname, ainstance, NULL, NULL, NULL, call->conn->peer->host, LOG_SETFIELDS);
1382     return code;
1383
1384 abort:
1385         COUNT_ABO;
1386         ubik_AbortTrans(tt);
1387         return code;
1388 }
1389
1390 /* delete a user */
1391
1392 afs_int32 KAM_DeleteUser(call, aname, ainstance)
1393   struct rx_call      *call;
1394   char                *aname;
1395   char                *ainstance;
1396 {
1397   afs_int32   code;
1398
1399   code = kamDeleteUser(call, aname, ainstance);
1400   osi_auditU (call, AFS_KAM_DelUserEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
1401   return code;
1402 }
1403
1404 afs_int32 kamDeleteUser(call, aname, ainstance)
1405   struct rx_call      *call;
1406   char                *aname;
1407   char                *ainstance;
1408 {   register int       code;
1409     struct ubik_trans *tt;
1410     afs_int32          caller;
1411     afs_int32          to;
1412     struct kaentry     tentry;
1413     int                nfailures;
1414     afs_uint32      locktime;
1415
1416     COUNT_REQ (DeleteUser);
1417     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
1418     if (code = InitAuthServ (&tt, LOCKWRITE, this_op)) return code;
1419     code = check_auth (call, tt, 1, &caller);
1420     if (code) {
1421       abort:
1422         COUNT_ABO;
1423         ubik_AbortTrans(tt);
1424         return code;
1425     }
1426
1427     code = FindBlock(tt, aname, ainstance, &to, &tentry);
1428     if (code) goto abort;
1429     if (to == 0) {                      /* name not found */
1430         code = KANOENT;
1431         goto abort;
1432     }
1433
1434     kaux_read( to, &nfailures, &locktime );
1435     if (nfailures || locktime)
1436       kaux_write( to, 0, 0 );      /* zero failure counters at this offset */
1437
1438     /* track all AuthServer identities */
1439     if (special_name (aname, ainstance))
1440         if (code = ka_DelKey (tt, to, &tentry)) goto abort;
1441
1442     if (ntohl(tentry.flags) & KAFADMIN) /* keep admin count up-to-date */
1443         if (code = update_admin_count (tt, -1)) goto abort;
1444
1445     if ((code = UnthreadBlock (tt, &tentry)) ||
1446         (code = FreeBlock (tt, to)) ||
1447         (code = get_time (0, tt, 1))    /* update randomness */
1448         ) goto abort;
1449
1450     code = ubik_EndTrans(tt);
1451     KALOG(aname, ainstance, NULL, NULL, NULL, call->conn->peer->host, LOG_DELUSER);
1452     return code;
1453 }
1454
1455 /* we set a bit in here which indicates that the user's limit of
1456  * authentication failures has been exceeded.  If that bit is not set,
1457  * kas can take it on faith that the user ID is not locked.  If that
1458  * bit is set, kas has to check all the servers to find one who will
1459  * report that the ID is not locked, or else to find out when the ID
1460  * will be unlocked.
1461  */
1462 afs_int32 KAM_GetEntry (call, aname, ainstance, aversion, aentry)
1463   struct rx_call      *call;
1464   char                *aname;
1465   char                *ainstance;
1466   afs_int32                    aversion;        /* major version assumed by caller */
1467   kaentryinfo         *aentry;          /* entry data copied here */
1468 {
1469   afs_int32   code;
1470
1471   code = kamGetEntry (call, aname, ainstance, aversion, aentry);
1472   osi_auditU (call, AFS_KAM_GetEntEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
1473   return code;
1474 }
1475
1476 afs_int32 kamGetEntry (call, aname, ainstance, aversion, aentry)
1477   struct rx_call      *call;
1478   char                *aname;
1479   char                *ainstance;
1480   afs_int32                    aversion;        /* major version assumed by caller */
1481   kaentryinfo         *aentry;          /* entry data copied here */
1482 {   register afs_int32      code;
1483     struct ubik_trans *tt;
1484     afs_int32          callerIndex;
1485     struct kaentry     caller;
1486     afs_int32          to;
1487     afs_uint32      temp;
1488     struct kaentry     tentry;
1489     rxkad_level enc_level = rxkad_clear;
1490     int callerIsAdmin = 0;
1491
1492     COUNT_REQ (GetEntry);
1493     if (aversion != KAMAJORVERSION) return KAOLDINTERFACE;
1494     if (!name_instance_legal (aname, ainstance)) return KABADNAME;
1495     if (code = InitAuthServ (&tt, LOCKREAD, this_op)) return code;
1496     code = check_auth (call, tt, 0, &callerIndex);
1497     if (code) {
1498        goto abort;
1499     }
1500     if (noAuthenticationRequired) {
1501     }
1502     else if (!callerIndex) {
1503       code = KANOENT;
1504       goto abort;
1505     }
1506     else {
1507       if (code = karead (tt, callerIndex, &caller, sizeof(caller))) {
1508         code = KAIO;
1509         goto abort;
1510       }
1511       /* if the user is checking his own entry or ADMIN then go ahead. */
1512       callerIsAdmin = (ntohl(caller.flags) & KAFADMIN);
1513
1514       if (strcmp (caller.userID.name, aname) != 0 && !callerIsAdmin) { 
1515           code = KANOAUTH;
1516           goto abort;
1517       }
1518     }
1519
1520     code = FindBlock (tt, aname, ainstance, &to, &tentry);
1521     if (code) goto abort;
1522     if (to == 0) {                      /* entry not found */
1523         code = KANOENT;
1524         goto abort;
1525     }
1526
1527     get_time (0,0,0);                   /* generate random update */
1528
1529     memset(aentry, 0, sizeof(*aentry));
1530     aentry->minor_version = KAMINORVERSION;
1531     aentry->flags = ntohl(tentry.flags);
1532     aentry->user_expiration = ntohl(tentry.user_expiration);
1533     aentry->modification_time = ntohl(tentry.modification_time);
1534     aentry->change_password_time = ntohl(tentry.change_password_time);
1535     aentry->max_ticket_lifetime = ntohl(tentry.max_ticket_lifetime);
1536     aentry->key_version = ntohl(tentry.key_version);
1537
1538     temp = (unsigned char) tentry.misc_auth_bytes[LOCKTIME] ;
1539     temp = temp << 9;
1540     if (kaux_islocked(to, (u_int) tentry.misc_auth_bytes[ATTEMPTS], temp))
1541        tentry.misc_auth_bytes[REUSEFLAGS] |= KA_ISLOCKED;   /* saves an RPC */
1542
1543     temp = pack_long(tentry.misc_auth_bytes);
1544     aentry->misc_auth_bytes = temp;
1545     /* 
1546      * only return user's key if security disabled or if admin and
1547      * we have an encrypted connection to the user
1548      */
1549     rxkad_GetServerInfo(call->conn, &enc_level, 0, 0, 0, 0, 0);
1550     if ((noAuthenticationRequired) ||
1551         (callerIsAdmin && enc_level == rxkad_crypt))
1552         memcpy(&aentry->key, &tentry.key, sizeof(struct ktc_encryptionKey));
1553     else memset(&aentry->key, 0, sizeof(aentry->key));
1554     code = ka_KeyCheckSum ((char *)&tentry.key, &aentry->keyCheckSum);
1555     if (!tentry.pwsums[0] && npwSums > 1 && !tentry.pwsums[1]) {
1556         aentry->reserved3 = 0x12340000;
1557     } else {
1558         aentry->reserved3 = 0x12340001;
1559     }
1560
1561     /* Now get entry of user who last modified this entry */
1562     if (ntohl(tentry.modification_id)) {
1563         temp = ntohl (tentry.modification_id);
1564         code = karead (tt, temp, &tentry, sizeof(tentry));
1565         if (code) {
1566             code = KAIO;
1567             goto abort;
1568         }
1569         aentry->modification_user = tentry.userID;
1570     }
1571     else {
1572         strcpy (aentry->modification_user.name, "<none>");
1573         strcpy (aentry->modification_user.instance, "\0");
1574     }
1575     code = ubik_EndTrans (tt);
1576     return code;
1577
1578 abort:
1579     COUNT_ABO;
1580     ubik_AbortTrans(tt);
1581     return code;
1582 }
1583
1584 afs_int32 KAM_ListEntry (call, previous_index, index, count, name)
1585   struct rx_call      *call;
1586   afs_int32                    previous_index;  /* last entry ret'd or 0 for first */
1587   afs_int32                   *index;           /* index of this entry */
1588   afs_int32                   *count;           /* total entries in database */
1589   kaident             *name;            /* name & instance of this entry */
1590 {
1591   afs_int32   code;
1592
1593   code = kamListEntry (call, previous_index, index, count, name);
1594   osi_auditU (call, AFS_KAM_LstEntEvent, code, AUD_LONG, *index, AUD_END);
1595   return code;
1596 }
1597
1598
1599 afs_int32 kamListEntry (call, previous_index, index, count, name)
1600   struct rx_call      *call;
1601   afs_int32                    previous_index;  /* last entry ret'd or 0 for first */
1602   afs_int32                   *index;           /* index of this entry */
1603   afs_int32                   *count;           /* total entries in database */
1604   kaident             *name;            /* name & instance of this entry */
1605 {   register int       code;
1606     struct ubik_trans *tt;
1607     afs_int32          caller;
1608     struct kaentry     tentry;
1609
1610     COUNT_REQ (ListEntry);
1611     if (code = InitAuthServ (&tt, LOCKREAD, this_op)) return code;
1612     code = check_auth (call, tt, 1, &caller);
1613     if (code) {
1614       goto abort;
1615     }
1616
1617     *index = NextBlock (tt, previous_index, &tentry, count);
1618     if (*count < 0) {
1619         code = KAIO;
1620         goto abort;
1621     }
1622
1623     if (*index) {                       /* return name & inst of this entry */
1624         strncpy (name->name, tentry.userID.name, sizeof(name->name));
1625         strncpy (name->instance, tentry.userID.instance,
1626                  sizeof(name->instance));
1627     }
1628     else {
1629         strcpy (name->name, "\0");
1630         strcpy (name->instance, "\0");
1631     }
1632     code = ubik_EndTrans(tt);
1633     return code;
1634
1635 abort:
1636         COUNT_ABO;
1637         ubik_AbortTrans(tt);
1638         return code;
1639 }
1640
1641 static afs_int32 GetTicket (version, call, kvno, authDomain, aticket,
1642                        sname, sinstance, atimes, oanswer)
1643   int   version;
1644   struct rx_call      *call;
1645   afs_int32                    kvno;
1646   char                *authDomain;
1647   ka_CBS              *aticket;
1648   char                *sname;
1649   char                *sinstance;
1650   ka_CBS              *atimes;          /* encrypted start & end time */
1651   ka_BBS              *oanswer;
1652 {   afs_int32          code;
1653     int                import, export;
1654     struct ubik_trans *tt;
1655     struct ktc_encryptionKey tgskey;
1656     des_key_schedule   schedule;
1657     afs_int32          to;
1658     char               name[MAXKTCNAMELEN];
1659     char               instance[MAXKTCNAMELEN];
1660     char               cell[MAXKTCNAMELEN];
1661     int                celllen;
1662     struct kaentry     caller;
1663     struct kaentry     server;
1664     struct ktc_encryptionKey authSessionKey;
1665     struct ktc_encryptionKey sessionKey;
1666     int                ticketLen;
1667     char               ticket[MAXKTCTICKETLEN];
1668     afs_int32          host;
1669     Date               start;
1670     Date               expiration;
1671     Date               now;
1672     Date               end;
1673     struct ka_getTicketTimes times;
1674     struct ka_getTicketAnswer *answer;
1675
1676     COUNT_REQ (GetTicket);
1677     if (!name_instance_legal (sname, sinstance)) return KABADNAME;
1678     if (atimes->SeqLen != sizeof(times)) return KABADARGUMENT;
1679     if (code = InitAuthServ (&tt, LOCKREAD, this_op)) return code;
1680
1681     export = import = 0;
1682     if ((strcmp (sname, KA_TGS_NAME) == 0) && (strcmp(sinstance, lrealm) != 0))
1683         export = 1;
1684     if ((strlen(authDomain) > 0) && (strcmp (authDomain, lrealm) != 0))
1685         import = 1;
1686
1687     if (strlen(authDomain) == 0) authDomain = lrealm;
1688     code = ka_LookupKvno (tt, KA_TGS_NAME, authDomain, kvno, &tgskey);
1689     if (code) {
1690       goto abort;
1691     }
1692     code = tkt_DecodeTicket (aticket->SeqBody, aticket->SeqLen, &tgskey,
1693                              name, instance, cell,
1694                              &authSessionKey, &host, &start, &expiration);
1695     if (code) {code = KANOAUTH; goto abort;}
1696     save_principal (tgsPrincipal, name, instance, cell);
1697
1698     if (code = get_time (&now, 0, 0)) goto abort;
1699
1700     code = tkt_CheckTimes (start, expiration, now);
1701     if (code <= 0) {
1702         if (code == -1) code = RXKADEXPIRED;
1703         else code = KANOAUTH;
1704         goto abort;
1705     }
1706     code = des_key_sched (&authSessionKey, schedule);
1707     if (code) {code = KANOAUTH; goto abort;}
1708     celllen = strlen (cell);
1709     if (import && (celllen == 0)) {code = KABADTICKET; goto abort;}
1710     if (export && (celllen == 0)) strcpy (cell, lrealm);
1711
1712     des_ecb_encrypt (atimes->SeqBody, &times, schedule, DECRYPT);
1713     times.start = ntohl(times.start);
1714     times.end = ntohl(times.end);
1715     code = tkt_CheckTimes (times.start, times.end, now);
1716     if (code < 0) {code = KABADREQUEST; goto abort;}
1717
1718     if (import) {
1719         strcpy (caller.userID.name, name);
1720         strcpy (caller.userID.instance, instance);
1721         caller.max_ticket_lifetime = htonl(MAXKTCTICKETLIFETIME);
1722         caller.flags = htonl(KAFNORMAL);
1723         caller.user_expiration = htonl(NEVERDATE);
1724     }
1725     else {
1726         code = FindBlock(tt, name, instance, &to, &caller);
1727         if (code) goto abort;
1728         if (to == 0) {
1729             ka_PrintUserID ("GetTicket: User ", name, instance, " unknown.\n");
1730             code = KANOENT;
1731             goto abort;
1732         }
1733     }
1734
1735     /* get server's entry */
1736     code = FindBlock (tt, sname, sinstance, &to, &server);
1737     if (code) goto abort;
1738     if (to == 0) {                      /* entry not found */
1739         ka_PrintUserID ("GetTicket: Server ", sname, sinstance, " unknown.\n");
1740         code = KANOENT;
1741         goto abort;
1742     }
1743     save_principal (tgsServerPrincipal, sname, sinstance, 0);
1744
1745     code = des_random_key (&sessionKey);
1746     if (code) {code = KANOKEYS; goto abort;}
1747
1748     code = GetEndTime (times.start, times.end, expiration, &caller, &server,
1749                        &end);
1750     if (code) goto abort;
1751
1752     code = tkt_MakeTicket (ticket, &ticketLen, &server.key,
1753                            caller.userID.name, caller.userID.instance, cell,
1754                            times.start, end, &sessionKey,
1755                            rx_HostOf(rx_PeerOf(rx_ConnectionOf(call))),
1756                            server.userID.name, server.userID.instance);
1757     if (code) goto abort;
1758
1759     switch (version) {
1760       case 0:
1761         code = KAANSWERTOOLONG;
1762         if (oanswer->MaxSeqLen <
1763             sizeof(struct ka_getTicketAnswer) - 5*MAXKTCNAMELEN) goto abort;
1764         
1765         answer = (struct ka_getTicketAnswer *)oanswer->SeqBody;
1766         memcpy(&answer->sessionKey, &sessionKey, sizeof(struct ktc_encryptionKey));
1767         answer->startTime = htonl(times.start);
1768         answer->endTime = htonl(end);
1769         answer->kvno = server.key_version;
1770         answer->ticketLen = htonl(ticketLen);
1771         
1772         {   char *ans = answer->name;   /* ptr to variable part of answer */
1773             int   rem,len;
1774             
1775             /* space remaining */
1776             rem = oanswer->MaxSeqLen - (ans - oanswer->SeqBody);
1777 #undef putstr
1778 #define putstr(str) len = strlen (str)+1;\
1779             if (rem < len) goto abort;\
1780             strcpy (ans, str);\
1781             ans += len; rem -= len
1782
1783             putstr (name);
1784             putstr (instance);
1785             putstr (cell);
1786             putstr (sname);
1787             putstr (sinstance);
1788             if (rem < ticketLen) goto abort;
1789             memcpy(ans, ticket, ticketLen);
1790             oanswer->SeqLen = (ans - oanswer->SeqBody) + ticketLen;
1791         }
1792         oanswer->SeqLen = round_up_to_ebs(oanswer->SeqLen);
1793         break;
1794       case 1:
1795         code = PrepareTicketAnswer
1796             (oanswer, /*challenge*/0, ticket, ticketLen, &sessionKey,
1797              times.start, end, &caller, &server, cell,
1798              KA_GETTICKET_ANS_LABEL);
1799         if (code) goto abort;
1800         break;
1801       default:
1802         code = KAINTERNALERROR;
1803         goto abort;
1804     }
1805     des_pcbc_encrypt (oanswer->SeqBody, oanswer->SeqBody, oanswer->SeqLen,
1806                       schedule, &authSessionKey, ENCRYPT);
1807     code = ubik_EndTrans (tt);
1808     KALOG(name, instance, sname, sinstance, (import ? authDomain : NULL), call->conn->peer->host, LOG_GETTICKET);
1809     return code;
1810
1811 abort:
1812     COUNT_ABO;
1813     ubik_AbortTrans(tt);
1814     return code;
1815 }
1816
1817 afs_int32 KAT_GetTicket_old (call, kvno, authDomain, aticket,
1818                         sname, sinstance, atimes, oanswer)
1819   struct rx_call      *call;
1820   afs_int32                    kvno;
1821   char                *authDomain;
1822   ka_CBS              *aticket;
1823   char                *sname;
1824   char                *sinstance;
1825   ka_CBS              *atimes;          /* encrypted start & end time */
1826   ka_BBS              *oanswer;
1827 {
1828 int code;
1829
1830     sleep(1); /* strongly discourage this */
1831     code = GetTicket (0, call, kvno, authDomain, aticket,
1832                       sname, sinstance, atimes, oanswer);
1833
1834     osi_auditU( call, AFS_KAT_GetTicketOEvent, code, AUD_STR, sname, AUD_STR, sinstance, AUD_END);
1835     return code;
1836 }
1837
1838 afs_int32 KAT_GetTicket (call, kvno, authDomain, aticket,
1839                     sname, sinstance, atimes, oanswer)
1840   struct rx_call      *call;
1841   afs_int32                    kvno;
1842   char                *authDomain;
1843   ka_CBS              *aticket;
1844   char                *sname;
1845   char                *sinstance;
1846   ka_CBS              *atimes;          /* encrypted start & end time */
1847   ka_BBS              *oanswer;
1848 {
1849 int code;
1850
1851     code =  GetTicket (1, call, kvno, authDomain, aticket,
1852                       sname, sinstance, atimes, oanswer);
1853     osi_auditU( call, AFS_KAT_GetTicketEvent, code, AUD_STR, sname, AUD_STR, sinstance, AUD_END);
1854     return code;
1855 }
1856
1857 afs_int32 KAM_GetStats (call, version, admin_accounts, statics, dynamics)
1858   struct rx_call      *call;
1859   afs_int32                    version;
1860   afs_int32                   *admin_accounts;
1861   kasstats            *statics;
1862   kadstats            *dynamics;
1863 {
1864   afs_int32   code;
1865
1866   code = kamGetStats (call, version, admin_accounts, statics, dynamics);
1867   osi_auditU (call, AFS_KAM_GetStatEvent, code, AUD_END);
1868   return code;
1869 }
1870
1871 afs_int32 kamGetStats (call, version, admin_accounts, statics, dynamics)
1872   struct rx_call      *call;
1873   afs_int32                    version;
1874   afs_int32                   *admin_accounts;
1875   kasstats            *statics;
1876   kadstats            *dynamics;
1877 {   afs_int32          code;
1878     struct ubik_trans *tt;
1879     afs_int32          caller;
1880
1881     COUNT_REQ (GetStats);
1882     if (version != KAMAJORVERSION) return KAOLDINTERFACE;
1883     if (code = InitAuthServ( &tt, LOCKREAD, this_op)) return code;
1884     code = check_auth (call, tt, 1, &caller);
1885     if (code) {
1886         COUNT_ABO;
1887         ubik_AbortTrans(tt);
1888         return code;
1889     }
1890
1891     *admin_accounts = ntohl(cheader.admin_accounts);
1892     /* memcpy((char *)statics, (char *)&cheader.stats, sizeof(kasstats)); */
1893     /* these are stored in network byte order and must be copied */
1894     statics->allocs = ntohl(cheader.stats.allocs);
1895     statics->frees = ntohl(cheader.stats.frees);
1896     statics->cpws = ntohl(cheader.stats.cpws);
1897 #if KADBVERSION != 5
1898     check that the statistics command copies all the fields
1899 #endif
1900
1901     memcpy((char *)dynamics, (char *)&dynamic_statistics, sizeof(kadstats));
1902     statics->minor_version = KAMINORVERSION;
1903     dynamics->minor_version = KAMINORVERSION;
1904
1905     {   int used = 0;
1906         int i;
1907
1908         for (i=0; i<HASHSIZE; i++)
1909             if (cheader.nameHash[i]) used++;
1910         dynamics->hashTableUtilization = (used*10000 + HASHSIZE/2)/HASHSIZE;
1911     }
1912     {   
1913 #if !defined(AFS_AIX_ENV) && !defined(AFS_HPUX_ENV) && !defined(AFS_NT40_ENV)
1914       struct rusage ru;
1915         /* Unfortunately, although aix_22 has a minimal compatibility
1916          * method of getting to some rusage fields (i.e. stime &
1917          * utime), the version that we have doesn't even have the
1918          * related include files needed for the aix vtimes() call; so
1919          * ignore this for aix till v3.1... */
1920         getrusage(RUSAGE_SELF, &ru);
1921 #if (KAMAJORVERSION>5)
1922         memcpy(&dynamics->utime, &ru.ru_utime, sizeof(struct katimeval));
1923         memcpy(&dynamics->stime, &ru.ru_stime, sizeof(struct katimeval));
1924         dynamics->dataSize = ru.ru_idrss;
1925         dynamics->stackSize = ru.ru_isrss;
1926         dynamics->pageFailts = ru.ru_majflt;
1927 #else
1928         dynamics->string_checks =
1929             (afs_int32)(1000.0 *
1930                    ((ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1000000.0) +
1931                     (ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1000000.0)));
1932 #endif
1933 #endif /* AFS_AIX_ENV && AFS_HPUX_ENV && AFS_NT40_ENV */
1934     }
1935
1936     code = ubik_EndTrans (tt);
1937     return code;
1938 }
1939
1940 afs_int32 KAM_GetPassword (call, name, password)
1941   struct rx_call *call;
1942   char           *name;
1943   EncryptionKey  *password;
1944 {
1945   afs_int32   code;
1946
1947   code = kamGetPassword (call, name, password);
1948   osi_auditU (call, AFS_KAM_GetPswdEvent, code, AUD_STR, name, AUD_END);
1949   return code;
1950 }
1951
1952 afs_int32 kamGetPassword (call, name, password)
1953   struct rx_call *call;
1954   char           *name;
1955   EncryptionKey  *password;
1956 {   int  code = KANOAUTH;
1957     afs_int32 to;
1958     struct ubik_trans *tt;
1959     struct kaentry tentry;
1960
1961     COUNT_REQ (GetPassword);
1962 #ifdef GETPASSWORD
1963     if (!name_instance_legal (name, "")) return KABADNAME;
1964     /* only requests from this host work */
1965     if (rx_HostOf(rx_PeerOf(rx_ConnectionOf(call))) != htonl(INADDR_LOOPBACK))
1966         return KANOAUTH;
1967     if (code = InitAuthServ (&tt, LOCKREAD, this_op)) return code;
1968
1969     /* this isn't likely to be used because of string to key problems, so since
1970        this is a temporary thing anyway, we'll use it here. */
1971     {   extern char udpAuthPrincipal[256];
1972         save_principal (udpAuthPrincipal, name, 0, 0);
1973     }
1974     get_time (0,0,0);                   /* update random value */
1975     code = FindBlock(tt, name, "", &to, &tentry);
1976     if (code) goto abort;
1977     if (to == 0) {
1978         code = KANOENT;
1979       abort:
1980         COUNT_ABO;
1981         ubik_AbortTrans(tt);
1982         return code;
1983     }
1984
1985     memcpy(password, &tentry.key, sizeof (*password));
1986     code = ubik_EndTrans (tt);
1987 #endif
1988     return code;
1989 }
1990
1991 afs_int32 KAM_GetRandomKey (call, key)
1992   struct rx_call *call;
1993   EncryptionKey  *key;
1994 {
1995   afs_int32   code;
1996
1997   code = kamGetRandomKey (call, key);
1998   osi_auditU (call, AFS_KAM_GetRndKeyEvent, code, AUD_END);
1999   return code;
2000 }
2001
2002 afs_int32 kamGetRandomKey (call, key)
2003   struct rx_call *call;
2004   EncryptionKey  *key;
2005 {   int  code;
2006
2007     COUNT_REQ (GetRandomKey);
2008     if (code = AwaitInitialization()) return code;
2009     code = des_random_key (key);
2010     if (code) return KANOKEYS;
2011     return 0;
2012 }
2013
2014 afs_int32 KAM_Debug (call, version, checkDB, info)
2015   struct rx_call      *call;
2016   afs_int32                    version;
2017   int                  checkDB;         /* start a transaction to examine DB */
2018   struct ka_debugInfo *info;
2019 {
2020   afs_int32   code;
2021
2022   code = kamDebug (call, version, checkDB, info);
2023   osi_auditU (call, AFS_KAM_DbgEvent, code, AUD_END);
2024   return code;
2025 }
2026
2027 afs_int32 kamDebug (call, version, checkDB, info)
2028   struct rx_call      *call;
2029   afs_int32                    version;
2030   int                  checkDB;         /* start a transaction to examine DB */
2031   struct ka_debugInfo *info;
2032 {
2033 /*  COUNT_REQ (Debug); */
2034     if (sizeof(struct kaentry) != sizeof(struct kaOldKeys))
2035         return KAINTERNALERROR;
2036     if (sizeof(struct ka_cpwRequest) % 8) return KAINTERNALERROR;
2037     if (version != KAMAJORVERSION) return KAOLDINTERFACE;
2038
2039     memset(info, 0, sizeof(*info));
2040
2041     info->minorVersion = KAMINORVERSION;
2042     info->host = dynamic_statistics.host;
2043     info->startTime = dynamic_statistics.start_time;
2044     info->
2045 #if (KAMAJORVERSION>5)
2046         now
2047 #else
2048         reserved1
2049 #endif
2050             = time(0);
2051     info->noAuth = noAuthenticationRequired;
2052
2053     info->dbVersion = ntohl(cheader.version);
2054     info->dbFreePtr = ntohl(cheader.freePtr);
2055     info->dbEofPtr = ntohl(cheader.eofPtr);
2056     info->dbKvnoPtr = ntohl(cheader.kvnoPtr);
2057     info->dbSpecialKeysVersion = ntohl(cheader.specialKeysVersion);
2058
2059     info->dbHeaderRead = cheaderReadTime;
2060     info->lastTrans = lastTrans;
2061     if (!lastOperation)
2062         lastOperation = "(Not Available)";
2063     strncpy (info->lastOperation, lastOperation, sizeof(info->lastOperation));
2064     strncpy (info->lastAuth, authPrincipal, sizeof(info->lastAuth));
2065     strncpy (info->lastTGS, tgsPrincipal, sizeof(info->lastTGS));
2066     strncpy (info->lastAdmin, adminPrincipal, sizeof(info->lastAdmin));
2067     strncpy (info->lastTGSServer, tgsServerPrincipal,
2068              sizeof(info->lastTGSServer));
2069     {   extern char udpAuthPrincipal[256];
2070         extern char udptgsPrincipal[256];
2071         extern char udptgsServerPrincipal[256];
2072
2073         strncpy (info->lastUAuth, udpAuthPrincipal, sizeof(info->lastUAuth));
2074         strncpy (info->lastUTGS, udptgsPrincipal, sizeof(info->lastUTGS));
2075         strncpy (info->lastUTGSServer, udptgsServerPrincipal,
2076                  sizeof(info->lastUTGSServer));
2077     }
2078     info->nextAutoCPW = nextAutoCPWTime;
2079     info->updatesRemaining = autoCPWUpdates - totalUpdates;
2080     ka_debugKeyCache (info);
2081     return 0;
2082 }
2083
2084 /* these are auxiliary routines. They don't do any Ubik stuff.  They use 
2085  * a tacked-on-the-side data file.
2086  * prob'ly ought to check the noauth flag.
2087  */
2088 #define ABORTIF(A) {if(code= A){goto abort;}}
2089 afs_int32 KAM_Unlock (call, aname, ainstance, spare1, spare2, spare3, spare4)
2090   struct rx_call      *call;
2091   char                *aname;
2092   char                *ainstance;
2093   afs_int32                spare1, spare2, spare3, spare4;
2094 {
2095   register int code;
2096   struct ubik_trans *tt;
2097   afs_int32            caller;
2098   afs_int32            to;
2099   struct kaentry     tentry;
2100
2101   COUNT_REQ (Unlock);
2102   if (!name_instance_legal (aname, ainstance)) {
2103      code = KABADNAME;
2104      goto exit;
2105    }
2106   if (code = InitAuthServ (&tt, LOCKREAD, this_op)) 
2107     goto exit;
2108
2109   ABORTIF( check_auth (call, tt, 1, &caller) );
2110   ABORTIF( FindBlock(tt, aname, ainstance, &to, &tentry) );
2111   ABORTIF( (to == 0 ? KANOENT : 0) );
2112
2113   kaux_write( to, 0, 0 );         /* zero failure counters at this offset */
2114
2115   code = ubik_EndTrans(tt);
2116   KALOG(aname, ainstance, NULL, NULL, NULL, call->conn->peer->host, LOG_UNLOCK);
2117   goto exit;
2118
2119 abort:
2120   COUNT_ABO;
2121   ubik_AbortTrans(tt); 
2122
2123 exit:
2124   osi_auditU(call, UnlockEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
2125   return code;
2126 }
2127
2128 afs_int32 KAM_LockStatus (call, aname, ainstance, lockeduntil, spare1, spare2, spare3, spare4)
2129   struct rx_call      *call;
2130   char                *aname;
2131   char                *ainstance;
2132   afs_int32                *lockeduntil;
2133   afs_int32                spare1, spare2, spare3, spare4;
2134 {
2135   register int code;
2136   struct ubik_trans *tt;
2137   afs_int32            callerIndex;
2138   afs_int32            to;
2139   struct kaentry     caller;
2140   struct kaentry     tentry;
2141   afs_uint32 temp;
2142
2143   COUNT_REQ (LockStatus);
2144  
2145   if (!name_instance_legal (aname, ainstance)) {
2146      code = KABADNAME;
2147      goto exit;
2148    }
2149   if (code = InitAuthServ (&tt, LOCKREAD, this_op)) 
2150      goto exit;
2151
2152   if (code = check_auth (call, tt, 0, &callerIndex) )
2153     goto abort;
2154
2155   if (!noAuthenticationRequired && callerIndex) {
2156     if (karead (tt, callerIndex, &caller, sizeof(caller))) {
2157       code = KAIO; 
2158       goto abort;
2159     }
2160     /* if the user is checking his own entry or ADMIN then go ahead. */
2161     if ((strcmp (caller.userID.name, aname) != 0) &&
2162         !(ntohl(caller.flags) & KAFADMIN)) {
2163       code = KANOAUTH;
2164       goto abort;
2165     }
2166   }
2167   
2168   if (code = FindBlock(tt, aname, ainstance, &to, &tentry) )
2169      goto abort;
2170
2171   if (to == 0) {
2172     code = KANOENT;
2173     goto abort;
2174   }
2175
2176   temp = (unsigned char) tentry.misc_auth_bytes[LOCKTIME] ;
2177   temp = temp << 9;
2178   *lockeduntil = kaux_islocked(to, (u_int) tentry.misc_auth_bytes[ATTEMPTS], 
2179                      temp);
2180
2181   code = ubik_EndTrans(tt);
2182   goto exit;
2183
2184  abort:
2185     COUNT_ABO;
2186     ubik_AbortTrans(tt); 
2187     osi_auditU(call, LockStatusEvent, code, AUD_STR, aname, AUD_STR, ainstance, AUD_END);
2188
2189  exit:
2190     return code;
2191 }
2192
2193