Cleanup of Get_Pwnam(). Adds debugging, cleans up the allow_change
[gd/samba-autobuild/.git] / source3 / lib / username.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    Username handling
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23 extern int DEBUGLEVEL;
24
25 /* internal functions */
26 static struct passwd *uname_string_combinations(char *s, struct passwd * (*fn) (char *), int N);
27 static struct passwd *uname_string_combinations2(char *s, int offset, struct passwd * (*fn) (char *), int N);
28
29 /****************************************************************************
30  Get a users home directory.
31 ****************************************************************************/
32
33 char *get_user_home_dir(char *user)
34 {
35   static struct passwd *pass;
36
37   pass = Get_Pwnam(user, False);
38
39   if (!pass) return(NULL);
40   return(pass->pw_dir);      
41 }
42
43
44 /*******************************************************************
45  Map a username from a dos name to a unix name by looking in the username
46  map. Note that this modifies the name in place.
47  This is the main function that should be called *once* on
48  any incoming or new username - in order to canonicalize the name.
49  This is being done to de-couple the case conversions from the user mapping
50  function. Previously, the map_username was being called
51  every time Get_Pwnam was called.
52  Returns True if username was changed, false otherwise.
53 ********************************************************************/
54
55 BOOL map_username(char *user)
56 {
57   static BOOL initialised=False;
58   static fstring last_from,last_to;
59   FILE *f;
60   char *mapfile = lp_username_map();
61   char *s;
62   pstring buf;
63   BOOL mapped_user = False;
64
65   if (!*user)
66     return False;
67
68   if (!*mapfile)
69     return False;
70
71   if (!initialised) {
72     *last_from = *last_to = 0;
73     initialised = True;
74   }
75
76   if (strequal(user,last_to))
77     return False;
78
79   if (strequal(user,last_from)) {
80     DEBUG(3,("Mapped user %s to %s\n",user,last_to));
81     fstrcpy(user,last_to);
82     return True;
83   }
84   
85   f = sys_fopen(mapfile,"r");
86   if (!f) {
87     DEBUG(0,("can't open username map %s\n",mapfile));
88     return False;
89   }
90
91   DEBUG(4,("Scanning username map %s\n",mapfile));
92
93   while((s=fgets_slash(buf,sizeof(buf),f))!=NULL) {
94     char *unixname = s;
95     char *dosname = strchr(unixname,'=');
96     BOOL return_if_mapped = False;
97
98     if (!dosname)
99       continue;
100
101     *dosname++ = 0;
102
103     while (isspace(*unixname))
104       unixname++;
105     if ('!' == *unixname) {
106       return_if_mapped = True;
107       unixname++;
108       while (*unixname && isspace(*unixname))
109         unixname++;
110     }
111     
112     if (!*unixname || strchr("#;",*unixname))
113       continue;
114
115     {
116       int l = strlen(unixname);
117       while (l && isspace(unixname[l-1])) {
118         unixname[l-1] = 0;
119         l--;
120       }
121     }
122
123     if (strchr(dosname,'*') || user_in_list(user,dosname)) {
124       DEBUG(3,("Mapped user %s to %s\n",user,unixname));
125       mapped_user = True;
126       fstrcpy(last_from,user);
127       sscanf(unixname,"%s",user);
128       fstrcpy(last_to,user);
129       if(return_if_mapped) { 
130         fclose(f);
131         return True;
132       }
133     }
134   }
135
136   fclose(f);
137
138   /*
139    * Setup the last_from and last_to as an optimization so 
140    * that we don't scan the file again for the same user.
141    */
142   fstrcpy(last_from,user);
143   fstrcpy(last_to,user);
144
145   return mapped_user;
146 }
147
148 /****************************************************************************
149  Get_Pwnam wrapper
150 ****************************************************************************/
151
152 static struct passwd *_Get_Pwnam(char *s)
153 {
154   struct passwd *ret;
155
156   ret = sys_getpwnam(s);
157   if (ret) {
158 #ifdef HAVE_GETPWANAM
159     struct passwd_adjunct *pwret;
160     pwret = getpwanam(s);
161     if (pwret && pwret->pwa_passwd) {
162       pstrcpy(ret->pw_passwd,pwret->pwa_passwd);
163     }
164 #endif
165   }
166
167   return(ret);
168 }
169
170
171 /*
172  * A wrapper for getpwnam().  The following variations are tried:
173  *   - as transmitted
174  *   - in all lower case if this differs from transmitted
175  *   - in all upper case if this differs from transmitted
176  *   - using lp_usernamelevel() for permutations.
177  * NOTE: This can potentially modify 'user' depending on value of
178  *       allow_change!
179  */
180 struct passwd *Get_Pwnam(char *user,BOOL allow_change)
181 {
182         fstring user2;
183         struct passwd *ret = NULL;
184
185         if (!user || !(*user))
186                 return(NULL);
187
188         fstrcpy(user2, user);
189
190         /* Try in all lower case first as this is the most 
191            common case on UNIX systems */
192         strlower(user2);
193         DEBUG(5,("Trying _Get_Pwnam(), username as lowercase is %s\n",user2));
194         ret = _Get_Pwnam(user2);
195         if(ret)
196                 goto done;
197
198         /* Try as given, if username wasn't originally lowercase */
199         if(strcmp(user,user2) != 0) {
200                 DEBUG(5,("Trying _Get_Pwnam(), username as given is %s\n",user2));
201                 ret = _Get_Pwnam(user2);
202                 if(ret)
203                         goto done;
204         }       
205
206         /* Try as uppercase, if username wasn't originally uppercase */
207         strupper(user2);
208         if(strcmp(user,user2) != 0) {
209                 DEBUG(5,("Trying _Get_Pwnam(), username as uppercase is %s\n",user2));
210                 ret = _Get_Pwnam(user2);
211                 if(ret)
212                         goto done;
213         }
214
215         /* Try all combinations up to usernamelevel */
216         strlower(user2);
217         DEBUG(5,("Checking combinations of %d uppercase letters in %s\n",lp_usernamelevel(),user2));
218         ret = uname_string_combinations(user2, _Get_Pwnam, lp_usernamelevel());
219
220 done:
221         DEBUG(5,("Get_Pwnam %s find a valid username!\n",ret ? "did":"didn't"));
222         /* If caller wants the modified username, ensure they get it  */
223         if(allow_change)
224                 fstrcpy(user,user2);
225
226         /* We can safely assume ret is NULL if none of the above succeed */
227         return(ret);  
228 }
229
230 /****************************************************************************
231  Check if a user is in a netgroup user list.
232 ****************************************************************************/
233
234 static BOOL user_in_netgroup_list(char *user,char *ngname)
235 {
236 #ifdef HAVE_NETGROUP
237   static char *mydomain = NULL;
238   if (mydomain == NULL)
239     yp_get_default_domain(&mydomain);
240
241   if(mydomain == NULL) {
242     DEBUG(5,("Unable to get default yp domain\n"));
243   } else {
244     DEBUG(5,("looking for user %s of domain %s in netgroup %s\n",
245           user, mydomain, ngname));
246     DEBUG(5,("innetgr is %s\n",
247           innetgr(ngname, NULL, user, mydomain)
248           ? "TRUE" : "FALSE"));
249
250     if (innetgr(ngname, NULL, user, mydomain))
251       return (True);
252   }
253 #endif /* HAVE_NETGROUP */
254   return False;
255 }
256
257 /****************************************************************************
258  Check if a user is in a winbind group.
259 ****************************************************************************/
260   
261 static BOOL user_in_winbind_group_list(char *user,char *gname, BOOL *winbind_answered)
262 {
263         int num_groups;
264         int i;
265         gid_t *groups = NULL;
266         gid_t gid;
267         BOOL ret = False;
268  
269         *winbind_answered = False;
270  
271         /*
272          * Get the gid's that this user belongs to.
273          */
274  
275         if ((num_groups = winbind_getgroups(user, 0, NULL)) == -1)
276                 return False;
277  
278         if (num_groups == 0) {
279                 *winbind_answered = True;
280                 return False;
281         }
282  
283         if ((groups = (gid_t *)malloc(sizeof(gid_t) * num_groups )) == NULL) {
284                 DEBUG(0,("user_in_winbind_group_list: malloc fail.\n"));
285                 goto err;
286         }
287  
288         if ((num_groups = winbind_getgroups(user, num_groups, groups)) == -1) {
289                 DEBUG(0,("user_in_winbind_group_list: second winbind_getgroups call \
290 failed with error %s\n", strerror(errno) ));
291                 goto err;
292         }
293  
294         /*
295          * Now we have the gid list for this user - convert the gname
296          * to a gid_t via either winbind or the local UNIX lookup and do the comparison.
297          */
298  
299         if ((gid = nametogid(gname)) == (gid_t)-1) {
300                 DEBUG(0,("user_in_winbind_group_list: winbind_lookup_name for group %s failed.\n",
301                         gname ));
302                 goto err;
303         }
304  
305         for (i = 0; i < num_groups; i++) {
306                 if (gid == groups[i]) {
307                         ret = True;
308                         break;
309                 }
310         }
311  
312         *winbind_answered = True;
313         safe_free(groups);
314         return ret;
315  
316    err:
317  
318         *winbind_answered = False;
319         safe_free(groups);
320         return False;
321 }             
322  
323 /****************************************************************************
324  Check if a user is in a UNIX group.
325 ****************************************************************************/
326
327 static BOOL user_in_unix_group_list(char *user,char *gname)
328 {
329         struct group *gptr;
330         char **member;  
331         struct passwd *pass = Get_Pwnam(user,False);
332
333         DEBUG(10,("user_in_unix_group_list: checking user %s in group %s\n", user, gname));
334
335         /*
336          * We need to check the users primary group as this
337          * group is implicit and often not listed in the group database.
338          */
339  
340         if (pass) {
341                 gptr = getgrgid(pass->pw_gid);
342                 if (gptr && strequal(gptr->gr_name,gname)) {
343                         DEBUG(10,("user_in_unix_group_list: group %s is primary group.\n", gname ));
344                         return True;
345                 }
346         }
347  
348         if ((gptr = (struct group *)getgrnam(gname)) == NULL) {
349                 DEBUG(10,("user_in_unix_group_list: no such group %s\n", gname ));
350                 return False;
351         }
352  
353         member = gptr->gr_mem;
354         while (member && *member) {
355                 DEBUG(10,("user_in_unix_group_list: checking user %s against member %s\n", user, *member ));
356                 if (strequal(*member,user)) {
357                         return(True);
358                 }
359                 member++;
360         }
361
362         return False;
363 }             
364
365 /****************************************************************************
366  Check if a user is in a group list. Ask winbind first, then use UNIX.
367 ****************************************************************************/
368
369 BOOL user_in_group_list(char *user,char *gname)
370 {
371         BOOL winbind_answered = False;
372         BOOL ret = user_in_winbind_group_list(user, gname, &winbind_answered);
373
374         if (winbind_answered)
375                 return ret;
376
377         return user_in_unix_group_list(user, gname);    
378 }
379
380 /****************************************************************************
381  Check if a user is in a user list - can check combinations of UNIX
382  and netgroup lists.
383 ****************************************************************************/
384
385 BOOL user_in_list(char *user,char *list)
386 {
387   pstring tok;
388   char *p=list;
389
390   DEBUG(10,("user_in_list: checking user %s in list %s\n", user, list));
391
392   while (next_token(&p,tok,LIST_SEP, sizeof(tok))) {
393     /*
394      * Check raw username.
395      */
396     if (strequal(user,tok))
397       return(True);
398
399     /*
400      * Now check to see if any combination
401      * of UNIX and netgroups has been specified.
402      */
403
404     if(*tok == '@') {
405       /*
406        * Old behaviour. Check netgroup list
407        * followed by UNIX list.
408        */
409       if(user_in_netgroup_list(user,&tok[1]))
410         return True;
411       if(user_in_group_list(user,&tok[1]))
412         return True;
413     } else if (*tok == '+') {
414
415       if(tok[1] == '&') {
416         /*
417          * Search UNIX list followed by netgroup.
418          */
419         if(user_in_group_list(user,&tok[2]))
420           return True;
421         if(user_in_netgroup_list(user,&tok[2]))
422           return True;
423
424       } else {
425
426         /*
427          * Just search UNIX list.
428          */
429
430         if(user_in_group_list(user,&tok[1]))
431           return True;
432       }
433
434     } else if (*tok == '&') {
435
436       if(tok[1] == '+') {
437         /*
438          * Search netgroup list followed by UNIX list.
439          */
440         if(user_in_netgroup_list(user,&tok[2]))
441           return True;
442         if(user_in_group_list(user,&tok[2]))
443           return True;
444       } else {
445         /*
446          * Just search netgroup list.
447          */
448         if(user_in_netgroup_list(user,&tok[1]))
449           return True;
450       }
451     }
452   }
453   return(False);
454 }
455
456 /* The functions below have been taken from password.c and slightly modified */
457 /****************************************************************************
458  Apply a function to upper/lower case combinations
459  of a string and return true if one of them returns true.
460  Try all combinations with N uppercase letters.
461  offset is the first char to try and change (start with 0)
462  it assumes the string starts lowercased
463 ****************************************************************************/
464
465 static struct passwd *uname_string_combinations2(char *s,int offset,struct passwd *(*fn)(char *),int N)
466 {
467   ssize_t len = (ssize_t)strlen(s);
468   int i;
469   struct passwd *ret;
470
471 #ifdef PASSWORD_LENGTH
472   len = MIN(len,PASSWORD_LENGTH);
473 #endif
474
475   if (N <= 0 || offset >= len)
476     return(fn(s));
477
478   for (i=offset;i<(len-(N-1));i++) {
479     char c = s[i];
480     if (!islower(c))
481       continue;
482     s[i] = toupper(c);
483     ret = uname_string_combinations2(s,i+1,fn,N-1);
484     if(ret)
485       return(ret);
486     s[i] = c;
487   }
488   return(NULL);
489 }
490
491 /****************************************************************************
492  Apply a function to upper/lower case combinations
493  of a string and return true if one of them returns true.
494  Try all combinations with up to N uppercase letters.
495  offset is the first char to try and change (start with 0)
496  it assumes the string starts lowercased
497 ****************************************************************************/
498
499 static struct passwd * uname_string_combinations(char *s,struct passwd * (*fn)(char *),int N)
500 {
501   int n;
502   struct passwd *ret;
503
504   for (n=1;n<=N;n++) {
505     ret = uname_string_combinations2(s,0,fn,n);
506     if(ret)
507       return(ret);
508   }
509   return(NULL);
510 }
511
512
513 /****************************************************************************
514 these wrappers allow appliance mode to work. In appliance mode the username
515 takes the form DOMAIN/user
516 ****************************************************************************/
517 struct passwd *smb_getpwnam(char *user, BOOL allow_change)
518 {
519         struct passwd *pw;
520         char *p;
521         char *sep;
522         extern pstring global_myname;
523
524         pw = Get_Pwnam(user, allow_change);
525         if (pw) return pw;
526
527         /* if it is a domain qualified name and it isn't in our password
528            database but the domain portion matches our local machine name then
529            lookup just the username portion locally */
530         sep = lp_winbind_separator();
531         if (!sep || !*sep) sep = "\\";
532         p = strchr(user,*sep);
533         if (p && 
534             strncasecmp(global_myname, user, strlen(global_myname))==0) {
535                 return Get_Pwnam(p+1, allow_change);
536         }
537
538         return NULL;
539 }