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