openafs-string-header-cleanup-20071030
[openafs.git] / src / uss / uss_kauth.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 /*
11  *      Implementation of basic procedures for the AFS user account
12  *      facility.
13  */
14
15 /*
16  * --------------------- Required definitions ---------------------
17  */
18 #include <afsconfig.h>
19 #include <afs/param.h>
20
21 RCSID
22     ("$Header$");
23
24 #include "uss_kauth.h"          /*Module interface */
25 #include "uss_common.h"         /*Common defs & operations */
26 #include <errno.h>
27 #include <pwd.h>
28
29 #include <string.h>
30
31 #include <afs/com_err.h>
32 #include <afs/kautils.h> /*MAXKTCREALMLEN*/
33 #include <afs/kaport.h>         /* pack_long */
34 #define uss_kauth_MAX_SIZE      2048
35 #undef USS_KAUTH_DB
36 /*
37  * ---------------------- Exported variables ----------------------
38  */
39 struct ubik_client *uconn_kauthP;       /*Ubik connections
40                                          * to AuthServers */
41
42 /*
43  * ------------------------ Private globals -----------------------
44  */
45 static int initDone = 0;        /*Module initialized? */
46 static char CreatorInstance[MAXKTCNAMELEN];     /*Instance string */
47 static char UserPrincipal[MAXKTCNAMELEN];       /*Parsed user principal */
48 static char UserInstance[MAXKTCNAMELEN];        /*Parsed user instance */
49 static char UserCell[MAXKTCREALMLEN];   /*Parsed user cell */
50 int doUnlog = 0;
51
52 /*-----------------------------------------------------------------------
53  * EXPORTED uss_kauth_InitAccountCreator
54  *
55  * Environment:
56  *      The command line must have been parsed.
57  *
58  * Side Effects:
59  *      As advertised.
60  *-----------------------------------------------------------------------*/
61
62 afs_int32
63 uss_kauth_InitAccountCreator()
64 {                               /*uss_kauth_InitAccountCreator */
65
66     char *name;
67     struct passwd *pw;
68     int dotPosition;
69
70     /*
71      * Set up the identity of the principal performing the account
72      * creation (uss_AccountCreator).  It's either the administrator
73      * name provided at the call or the identity of the caller as
74      * gleaned from the password info.
75      */
76     if (uss_Administrator[0] != '\0') {
77         name = uss_Administrator;
78     } else {                    /* Administrator name not passed in */
79         pw = getpwuid(getuid());
80         if (pw == 0) {
81             fprintf(stderr,
82                     "%s: Can't figure out your name from your user id.\n",
83                     uss_whoami);
84             return (1);
85         }
86         name = pw->pw_name;
87     }
88
89     /* Break the *name into principal and instance */
90     dotPosition = strcspn(name, ".");
91     if (dotPosition >= MAXKTCNAMELEN) {
92         fprintf(stderr, "Admin principal name too long.\n");
93         return (1);
94     }
95     strncpy(uss_AccountCreator, name, dotPosition);
96     uss_AccountCreator[dotPosition] = '\0';
97
98     name += dotPosition;
99     if (name[0] == '.') {
100         name++;
101         if (strlen(name) >= MAXKTCNAMELEN) {
102             fprintf(stderr, "Admin instance name too long.\n");
103             return (1);
104         }
105         strcpy(CreatorInstance, name);
106     } else {
107         CreatorInstance[0] = '\0';
108     }
109
110 #ifdef USS_KAUTH_DB_INSTANCE
111     fprintf(stderr, "%s: Starting CreatorInstance is '%s', %d bytes\n",
112             uss_whoami, CreatorInstance, strlen(CreatorInstance));
113 #endif /* USS_KAUTH_DB_INSTANCE */
114
115     return (0);
116 }
117
118 /*-----------------------------------------------------------------------
119  * static InitThisModule
120  *
121  * Description:
122  *      Set up this module, namely set up all the client state for
123  *      dealing with the Volume Location Server(s), including
124  *      network connections.
125  *
126  * Arguments:
127  *      a_noAuthFlag : Do we need authentication?
128  *      a_confDir    : Configuration directory to use.
129  *      a_cellName   : Cell we want to talk to.
130  *
131  * Returns:
132  *      0 if everything went fine, or
133  *      lower-level error code otherwise.
134  *
135  * Environment:
136  *      This routine will only be called once.
137  *
138  * Side Effects:
139  *      As advertised.
140  *------------------------------------------------------------------------*/
141
142 int Pipe = 0;
143 static char *
144 getpipepass()
145 {
146     static char gpbuf[BUFSIZ];
147     /* read a password from stdin, stop on \n or eof */
148     register int i, tc;
149     memset(gpbuf, 0, sizeof(gpbuf));
150     for (i = 0; i < (sizeof(gpbuf) - 1); i++) {
151         tc = fgetc(stdin);
152         if (tc == '\n' || tc == EOF)
153             break;
154         gpbuf[i] = tc;
155     }
156     return gpbuf;
157 }
158
159
160 afs_int32
161 InitThisModule()
162 {                               /*InitThisModule */
163
164     static char rn[] = "uss_kauth:InitThisModule";
165     register afs_int32 code;
166     char *name, prompt[2 * MAXKTCNAMELEN + 20];
167     char *reasonString, longPassBuff[1024], shortPassBuff[9];
168     struct ktc_encryptionKey key;
169     struct ktc_token token, tok;
170     struct ktc_principal Name;
171
172     /*
173      * Only call this routine once.
174      */
175     if (initDone)
176         return (0);
177
178
179     /*
180      * Pull out the caller's administrator token if they have one.
181      */
182     code =
183         ka_GetAdminToken(0, 0, uss_Cell, 0, 10 * 60 * 60, &token,
184                          0 /*new */ );
185     if (code) {
186         if (Pipe) {
187             strncpy(longPassBuff, getpipepass(), sizeof(longPassBuff));
188         } else {
189             /*
190              * Nope, no admin tokens available.  Get the key based on the
191              * full password and try again.
192              */
193             sprintf(prompt, "Password for '%s", uss_AccountCreator);
194             if (CreatorInstance[0])
195                 sprintf(prompt + strlen(prompt), ".%s", CreatorInstance);
196             strcat(prompt, "': ");
197             code = ka_UserReadPassword(prompt,  /*Prompt to use */
198                                        longPassBuff,    /*Long pwd buffer */
199                                        sizeof(longPassBuff),    /*Size of above */
200                                        &reasonString);
201             if (code) {
202                 afs_com_err(uss_whoami, code, "while getting password ");
203 #ifdef USS_KAUTH_DB
204                 printf("%s: Error code from ka_UserReadPassword(): %d\n", rn,
205                        code);
206 #endif /* USS_KAUTH_DB */
207                 return (code);
208             }
209         }
210         ka_StringToKey(longPassBuff, uss_Cell, &key);
211         code =
212             ka_GetAdminToken(uss_AccountCreator, CreatorInstance, uss_Cell,
213                              &key, 24 * 60 * 60, &token, 0 /*new */ );
214         if (code) {
215             if ((code == KABADREQUEST) && (strlen(longPassBuff) > 8)) {
216                 /*
217                  * The key we provided just doesn't work, yet we
218                  * suspect that since the password is greater than 8
219                  * chars, it might be the case that we really need
220                  * to truncate the password to generate the appropriate
221                  * key.
222                  */
223                 afs_com_err(uss_whoami, code,
224                         "while getting administrator token (trying shortened password next...)");
225 #ifdef USS_KAUTH_DB
226                 printf("%s: Error code from ka_GetAdminToken: %d\n", rn,
227                        code);
228 #endif /* USS_KAUTH_DB */
229                 strncpy(shortPassBuff, longPassBuff, 8);
230                 shortPassBuff[8] = 0;
231                 ka_StringToKey(shortPassBuff, uss_Cell, &key);
232                 code =
233                     ka_GetAdminToken(uss_AccountCreator, CreatorInstance,
234                                      uss_Cell, &key, 24 * 60 * 60, &token,
235                                      0 /*new */ );
236                 if (code) {
237                     afs_com_err(uss_whoami, code,
238                             "while getting administrator token (possibly wrong password, or not an administrative account)");
239 #ifdef USS_KAUTH_DB
240                     printf("%s: Error code from ka_GetAdminToken: %d\n", rn,
241                            code);
242 #endif /* USS_KAUTH_DB */
243                     return (code);
244                 } else {
245                     /*
246                      * The silly administrator has a long password!  Tell
247                      * him or her off in a polite way.
248                      */
249                     printf
250                         ("%s: Shortened password accepted by the Authentication Server\n",
251                          uss_whoami);
252                 }
253             } /*Try a shorter password */
254             else {
255                 /*
256                  * We failed to get an admin token, but the password is
257                  * of a reasonable length, so we're just hosed.
258                  */
259                 afs_com_err(uss_whoami, code,
260                         "while getting administrator token (possibly wrong password, or not an administrative account)");
261 #ifdef USS_KAUTH_DB
262                 printf("%s: Error code from ka_GetAdminToken: %d\n", rn,
263                        code);
264 #endif /* USS_KAUTH_DB */
265                 return (code);
266             }                   /*Even the shorter password didn't work */
267         }                       /*Key from given password didn't work */
268     }
269
270     /*First attempt to get admin token failed */
271     /*
272      * At this point, we have acquired an administrator token.  Let's
273      * proceed to set up a connection to the AuthServer.
274      */
275 #ifdef USS_KAUTH_DB_INSTANCE
276     fprintf(stderr,
277             "%s: CreatorInstance after ka_GetAdminToken(): '%s', %d bytes\n",
278             rn, CreatorInstance, strlen(CreatorInstance));
279 #endif /* USS_KAUTH_DB_INSTANCE */
280
281     /*
282      * Set up the connection to the AuthServer read/write site.
283      */
284     code =
285         ka_AuthServerConn(uss_Cell, KA_MAINTENANCE_SERVICE, &token,
286                           &uconn_kauthP);
287     if (code) {
288         afs_com_err(uss_whoami, code,
289                 "while establishing Authentication Server connection");
290 #ifdef USS_KAUTH_DB
291         printf("%s: Error code from ka_AuthServerConn: %d\n", rn, code);
292 #endif /* USS_KAUTH_DB */
293         return (code);
294     }
295
296     if (uss_Administrator[0]) {
297         /*
298          * We must check to see if we have local tokens for admin since he'll may do
299          * various pioctl or calls to protection server that require tokens. Remember
300          * to remove this tokens at the end of the program...
301          */
302         strcpy(Name.name, "afs");
303         Name.instance[0] = '\0';
304         strncpy(Name.cell, uss_Cell, sizeof(Name.cell));
305         if (code =
306             ktc_GetToken(&Name, &token, sizeof(struct ktc_token), &tok)) {
307             code =
308                 ka_UserAuthenticateLife(0, uss_AccountCreator,
309                                         CreatorInstance, uss_Cell,
310                                         longPassBuff, 10 * 60 * 60,
311                                         &reasonString);
312             if (!code)
313                 doUnlog = 1;
314         }
315     }
316
317     /*
318      * Declare our success.
319      */
320     initDone = 1;
321     return (0);
322
323 }                               /*InitThisModule */
324
325
326 /*-----------------------------------------------------------------------
327  * EXPORTED uss_kauth_AddUser
328  *
329  * Environment:
330  *      The uconn_kauthP variable may already be set to an AuthServer
331  *      connection.
332  *
333  * Side Effects:
334  *      As advertised.
335  *------------------------------------------------------------------------*/
336
337 afs_int32
338 uss_kauth_AddUser(a_user, a_passwd)
339      char *a_user;
340      char *a_passwd;
341
342 {                               /*uss_kauth_AddUser */
343
344     static char rn[] = "uss_kauth_AddUser";     /*Routine name */
345     struct ktc_encryptionKey key;
346     afs_int32 code;
347
348     if (uss_SkipKaserver) {
349         /*
350          * Don't talk to the kaserver; assume calls succeded and simply return.
351          * Amasingly people want to update it (most likely kerberos) themselves...
352          */
353         if (uss_verbose)
354             printf
355                 ("[Skip Kaserver option - Adding of user %s in Authentication DB not done]\n",
356                  a_user);
357         return 0;
358     }
359
360
361     /*
362      * Make sure the module has been initialized before we start trying
363      * to talk to AuthServers.
364      */
365     if (!initDone) {
366         code = InitThisModule();
367         if (code)
368             exit(code);
369     }
370
371     /*
372      * Given the (unencrypted) password and cell, generate a key to
373      * pass to the AuthServer.
374      */
375     ka_StringToKey(a_passwd, uss_Cell, &key);
376
377     if (!uss_DryRun) {
378         if (uss_verbose)
379             fprintf(stderr, "Adding user '%s' to the Authentication DB\n",
380                     a_user);
381
382 #ifdef USS_KAUTH_DB_INSTANCE
383         fprintf(stderr,
384                 "%s: KAM_CreateUser: user='%s', CreatorInstance='%s', %d bytes\n",
385                 rn, a_user, CreatorInstance, strlen(CreatorInstance));
386 #endif /* USS_KAUTH_DB_INSTANCE */
387         code = ubik_Call(KAM_CreateUser, uconn_kauthP, 0, a_user, UserInstance, /*set by CheckUsername() */
388                          key);
389         if (code) {
390             if (code == KAEXIST) {
391                 if (uss_verbose)
392                     fprintf(stderr,
393                             "%s: Warning: User '%s' already in Authentication DB\n",
394                             uss_whoami, a_user);
395             } else {
396                 afs_com_err(uss_whoami, code,
397                         "while adding user '%s' to Authentication DB",
398                         a_user);
399 #ifdef USS_KAUTH_DB
400                 printf("%s: Error code from KAM_CreateUser: %d\n", rn, code);
401 #endif /* USS_KAUTH_DB */
402                 return (code);
403             }
404         }                       /*KAM_CreateUser failed */
405     } /*Not a dry run */
406     else
407         fprintf(stderr,
408                 "\t[Dry run - user '%s' NOT added to Authentication DB]\n",
409                 a_user);
410
411     return (0);
412
413 }                               /*uss_kauth_AddUser */
414
415
416 /*-----------------------------------------------------------------------
417  * EXPORTED uss_kauth_DelUser
418  *
419  * Environment:
420  *      The uconn_kauthP variable may already be set to an AuthServer
421  *      connection.
422  *
423  * Side Effects:
424  *      As advertised.
425  *------------------------------------------------------------------------*/
426
427 afs_int32
428 uss_kauth_DelUser(a_user)
429      char *a_user;
430
431 {                               /*uss_kauth_DelUser */
432
433     static char rn[] = "uss_kauth_DelUser";     /*Routine name */
434     register afs_int32 code;    /*Return code */
435
436     if (uss_SkipKaserver) {
437         /*
438          * Don't talk to the kaserver; assume calls succeded and simply return.
439          * Amasingly people want to update it (most likely kerberos) themselves...
440          */
441         if (uss_verbose)
442             printf
443                 ("[Skip Kaserver option - Deleting of user %s in Authentication DB not done]\n",
444                  a_user);
445         return 0;
446     }
447
448     /*
449      * Make sure the module has been initialized before we start trying
450      * to talk to AuthServers.
451      */
452     if (!initDone) {
453         code = InitThisModule();
454         if (code)
455             exit(code);
456     }
457
458     if (!uss_DryRun) {
459 #ifdef USS_KAUTH_DB_INSTANCE
460         printf("%s: KAM_DeleteUser: user='%s', CreatorInstance='%s'\n",
461                uss_whoami, a_user, CreatorInstance);
462 #endif /* USS_KAUTH_DB_INSTANCE */
463         if (uss_verbose)
464             printf("Deleting user '%s' from Authentication DB\n", a_user);
465         code = ubik_Call(KAM_DeleteUser,        /*Procedure to call */
466                          uconn_kauthP,  /*Ubik client connection struct */
467                          0,     /*Flags */
468                          a_user,        /*User name to delete */
469                          UserInstance); /*set in CheckUserName() */
470         if (code) {
471             if (code == KANOENT) {
472                 if (uss_verbose)
473                     printf
474                         ("%s: No entry for user '%s' in Authentication DB\n",
475                          uss_whoami, a_user);
476                 return (0);
477             } else {
478                 afs_com_err(uss_whoami, code,
479                         "while deleting entry in Authentication DB\n");
480 #ifdef USS_KAUTH_DB
481                 printf("%s: Error code from KAM_DeleteUser: %d\n", rn, code);
482 #endif /* USS_KAUTH_DB */
483                 return (code);
484             }
485         }                       /*KAM_DeleteUser failed */
486     } /*Not a dry run */
487     else
488         printf("\t[Dry run - user '%s' NOT deleted from Authentication DB]\n",
489                a_user);
490
491     return (0);
492
493 }                               /*uss_kauth_DelUser */
494
495
496 /*-----------------------------------------------------------------------
497  * EXPORTED uss_kauth_CheckUserName
498  *
499  * Environment:
500  *      The user name has already been parsed and placed into
501  *      uss_User.
502  *
503  * Side Effects:
504  *      As advertised.
505  *------------------------------------------------------------------------*/
506
507 afs_int32
508 uss_kauth_CheckUserName()
509 {                               /*uss_kauth_CheckUserName */
510
511     static char rn[] = "uss_kauth_CheckUserName";       /*Routine name */
512     register afs_int32 code;    /*Return code */
513
514     if (uss_SkipKaserver) {
515         /*
516          * Don't talk to the kaserver; assume calls succeded and simply return.
517          * Amasingly people want to update it (most likely kerberos) themselves...
518          */
519         if (uss_verbose)
520             printf
521                 ("[Skip Kaserver option - Checking of user name in Authentication DB not done]\n");
522         return 0;
523     }
524
525     /*
526      * Make sure the module has been initialized before we start trying
527      * to talk to AuthServers.
528      */
529     if (!initDone) {
530         code = InitThisModule();
531         if (code)
532             exit(code);
533     }
534
535     /*
536      * Use the AuthServer's own routine to decide if the parsed user name
537      * is legal.  Specifically, it can't have any weird characters or
538      * embedded instance or cell names. 
539      */
540     code = ka_ParseLoginName(uss_User, UserPrincipal, UserInstance, UserCell);
541     if (strlen(UserInstance) > 0) {
542         fprintf(stderr,
543                 "%s: User name can't have an instance string ('%s')\n",
544                 uss_whoami, UserInstance);
545         return (-1);
546     }
547     if (strlen(UserCell) > 0) {
548         fprintf(stderr, "%s: User name can't have a cell string ('%s')\n",
549                 uss_whoami, UserCell);
550         return (-1);
551     }
552     if (strchr(UserPrincipal, ':') != NULL) {
553         fprintf(stderr, "%s: User name '%s' can't have a colon\n", uss_whoami,
554                 UserPrincipal);
555         return (-1);
556     }
557     if (strlen(UserPrincipal) > 8) {
558         fprintf(stderr,
559                 "%s: User name '%s' must have 8 or fewer characters\n",
560                 uss_whoami, UserPrincipal);
561         return (-1);
562     }
563
564     /*
565      * The name's OK in my book.  Replace the user name with the parsed
566      * value.
567      */
568     strcpy(uss_User, UserPrincipal);
569     return (0);
570
571 }                               /*uss_kauth_CheckUserName */
572
573
574 /*
575  * EXPORTED uss_kauth_SetFields
576  *
577  * Environment:
578  *      The uconn_kauthP variable may already be set to an AuthServer
579  *      connection.
580  *
581  * Side Effects:
582  *      As advertised.
583  */
584
585 afs_int32
586 uss_kauth_SetFields(username, expirestring, reuse, failures, lockout)
587      char *reuse;
588      char *username;
589      char *expirestring;
590      char *failures;
591      char *lockout;
592 {
593     static char rn[] = "uss_kauth_SetFields";
594     afs_int32 code;
595     char misc_auth_bytes[4];
596     int i;
597     afs_int32 flags = 0;
598     Date expiration = 0;
599     afs_int32 lifetime = 0;
600     afs_int32 maxAssociates = -1;
601     afs_int32 was_spare = 0;
602     char instance = '\0';
603     int pwexpiry;
604     int nfailures, locktime, hrs, mins;
605
606     if (strlen(username) > uss_UserLen) {
607         fprintf(stderr,
608                 "%s: * User field in add cmd too long (max is %d chars; truncated value is '%s')\n",
609                 uss_whoami, uss_UserLen, uss_User);
610         return (-1);
611     }
612
613     strcpy(uss_User, username);
614     code = uss_kauth_CheckUserName();
615     if (code)
616         return (code);
617
618     /*  no point in doing this any sooner than necessary */
619     for (i = 0; i < 4; misc_auth_bytes[i++] = 0);
620
621     pwexpiry = atoi(expirestring);
622     if (pwexpiry < 0 || pwexpiry > 254) {
623         fprintf(stderr, "Password lifetime range must be [0..254] days.\n");
624         fprintf(stderr, "Zero represents an unlimited lifetime.\n");
625         fprintf(stderr,
626                 "Continuing with default lifetime == 0 for user %s.\n",
627                 username);
628         pwexpiry = 0;
629     }
630     misc_auth_bytes[0] = pwexpiry + 1;
631
632     if (!strcmp(reuse, "noreuse")) {
633         misc_auth_bytes[1] = KA_NOREUSEPW;
634     } else {
635         misc_auth_bytes[1] = KA_REUSEPW;
636         if (strcmp(reuse, "reuse"))
637           fprintf(stderr, "must specify \"reuse\" or \"noreuse\": \"reuse\" assumed\n");
638     }
639
640     nfailures = atoi(failures);
641     if (nfailures < 0 || nfailures > 254) {
642         fprintf(stderr, "Failure limit must be in [0..254].\n");
643         fprintf(stderr, "Zero represents unlimited login attempts.\n");
644         fprintf(stderr, "Continuing with limit == 254 for user %s.\n",
645                 username);
646         misc_auth_bytes[2] = 255;
647     } else
648         misc_auth_bytes[2] = nfailures + 1;
649
650     hrs = 0;
651     if (strchr(lockout, ':'))
652         sscanf(lockout, "%d:%d", &hrs, &mins);
653     else
654         sscanf(lockout, "%d", &mins);
655
656     locktime = hrs*60 + mins;
657     if (hrs < 0 || hrs > 36 || mins < 0) {
658         fprintf(stderr,"Lockout times must be either minutes or hh:mm.\n");
659         fprintf(stderr,"Lockout times must be less than 36 hours.\n");
660         return KABADCMD;
661     } else if (locktime > 36*60) {
662         fprintf(stderr, "Lockout times must be either minutes or hh:mm.\n");
663         fprintf(stderr, "Lockout times must be less than 36 hours.\n");
664         fprintf(stderr, "Continuing with lock time == forever for user %s.\n",
665                 username);
666         misc_auth_bytes[3] = 1;
667     } else {
668         locktime = (locktime * 60 + 511) >> 9;  /* ceil(l*60/512) */
669         misc_auth_bytes[3] = locktime + 1;
670     }
671
672     if (uss_SkipKaserver) {
673         if (uss_verbose)
674             printf("[Skipping Kaserver as requested]\n");
675         return 0;
676     }
677
678     /*
679      * Make sure the module has been initialized before we start trying
680      * to talk to AuthServers.
681      */
682     if (!initDone) {
683         code = InitThisModule();
684         if (code)
685             exit(code);
686     }
687
688     if (!uss_DryRun) {
689         if (uss_verbose)
690             fprintf(stderr, "Setting options for '%s' in database.\n",
691                     username);
692
693         was_spare = pack_long(misc_auth_bytes);
694
695         if (was_spare || flags || expiration || lifetime
696             || (maxAssociates >= 0)) {
697
698             if (!expiration)
699                 expiration = uss_Expires;
700             code =
701                 ubik_Call(KAM_SetFields, uconn_kauthP, 0, username, &instance,
702                           flags, expiration, lifetime, maxAssociates,
703                           was_spare, /* spare */ 0);
704         } else
705             fprintf(stderr,
706                     "Must specify one of the optional parameters. Continuing...\n");
707
708         if (code) {
709             afs_com_err(uss_whoami, code, "calling KAM_SetFields for %s.%s",
710                     username, instance);
711
712             return (code);
713         }
714     } /*Not a dry run */
715     else
716         fprintf(stderr, "\t[Dry run - user '%s' NOT changed.]\n", username);
717
718     return (0);
719
720 }                               /*uss_kauth_SetFields */