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