Removed 'extern int DEBUGLEVEL' as it is now in the smb.h header.
[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) (char *), int N);
26 static struct passwd *uname_string_combinations2(char *s, int offset, struct passwd * (*fn) (char *), int N);
27
28 /****************************************************************************
29  Get a users home directory.
30 ****************************************************************************/
31
32 char *get_user_home_dir(char *user)
33 {
34   static struct passwd *pass;
35
36   pass = Get_Pwnam(user, False);
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(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  * NOTE: This can potentially modify 'user' depending on value of
187  *       allow_change!
188  */
189 struct passwd *Get_Pwnam(char *user,BOOL allow_change)
190 {
191         fstring user2;
192         struct passwd *ret = NULL;
193
194         if (!user || !(*user))
195                 return(NULL);
196
197         fstrcpy(user2, user);
198
199         /* Try in all lower case first as this is the most 
200            common case on UNIX systems */
201         strlower(user2);
202         DEBUG(5,("Trying _Get_Pwnam(), username as lowercase is %s\n",user2));
203         ret = _Get_Pwnam(user2);
204         if(ret)
205                 goto done;
206
207         /* Try as given, if username wasn't originally lowercase */
208         if(strcmp(user,user2) != 0) {
209                 DEBUG(5,("Trying _Get_Pwnam(), username as given is %s\n",user));
210                 ret = _Get_Pwnam(user);
211                 if(ret)
212                         goto done;
213         }       
214
215         /* Try as uppercase, if username wasn't originally uppercase */
216         strupper(user2);
217         if(strcmp(user,user2) != 0) {
218                 DEBUG(5,("Trying _Get_Pwnam(), username as uppercase is %s\n",user2));
219                 ret = _Get_Pwnam(user2);
220                 if(ret)
221                         goto done;
222         }
223
224         /* Try all combinations up to usernamelevel */
225         strlower(user2);
226         DEBUG(5,("Checking combinations of %d uppercase letters in %s\n",lp_usernamelevel(),user2));
227         ret = uname_string_combinations(user2, _Get_Pwnam, lp_usernamelevel());
228
229 done:
230         DEBUG(5,("Get_Pwnam %s find a valid username!\n",ret ? "did":"didn't"));
231         /* If caller wants the modified username, ensure they get it  */
232         if(allow_change)
233                 fstrcpy(user,user2);
234
235         /* We can safely assume ret is NULL if none of the above succeed */
236         return(ret);  
237 }
238
239 /****************************************************************************
240  Check if a user is in a netgroup user list.
241 ****************************************************************************/
242
243 static BOOL user_in_netgroup_list(char *user,char *ngname)
244 {
245 #ifdef HAVE_NETGROUP
246   static char *mydomain = NULL;
247   if (mydomain == NULL)
248     yp_get_default_domain(&mydomain);
249
250   if(mydomain == NULL) {
251     DEBUG(5,("Unable to get default yp domain\n"));
252   } else {
253     DEBUG(5,("looking for user %s of domain %s in netgroup %s\n",
254           user, mydomain, ngname));
255     DEBUG(5,("innetgr is %s\n",
256           innetgr(ngname, NULL, user, mydomain)
257           ? "TRUE" : "FALSE"));
258
259     if (innetgr(ngname, NULL, user, mydomain))
260       return (True);
261   }
262 #endif /* HAVE_NETGROUP */
263   return False;
264 }
265
266 /****************************************************************************
267  Check if a user is in a winbind group.
268 ****************************************************************************/
269   
270 static BOOL user_in_winbind_group_list(char *user,char *gname, BOOL *winbind_answered)
271 {
272         int num_groups;
273         int i;
274         gid_t *groups = NULL;
275         gid_t gid;
276         BOOL ret = False;
277  
278         *winbind_answered = False;
279  
280         /*
281          * Get the gid's that this user belongs to.
282          */
283  
284         if ((num_groups = winbind_getgroups(user, 0, NULL)) == -1)
285                 return False;
286  
287         if (num_groups == 0) {
288                 *winbind_answered = True;
289                 return False;
290         }
291  
292         if ((groups = (gid_t *)malloc(sizeof(gid_t) * num_groups )) == NULL) {
293                 DEBUG(0,("user_in_winbind_group_list: malloc fail.\n"));
294                 goto err;
295         }
296  
297         if ((num_groups = winbind_getgroups(user, num_groups, groups)) == -1) {
298                 DEBUG(0,("user_in_winbind_group_list: second winbind_getgroups call \
299 failed with error %s\n", strerror(errno) ));
300                 goto err;
301         }
302  
303         /*
304          * Now we have the gid list for this user - convert the gname
305          * to a gid_t via either winbind or the local UNIX lookup and do the comparison.
306          */
307  
308         if ((gid = nametogid(gname)) == (gid_t)-1) {
309                 DEBUG(0,("user_in_winbind_group_list: winbind_lookup_name for group %s failed.\n",
310                         gname ));
311                 goto err;
312         }
313  
314         for (i = 0; i < num_groups; i++) {
315                 if (gid == groups[i]) {
316                         ret = True;
317                         break;
318                 }
319         }
320  
321         *winbind_answered = True;
322         SAFE_FREE(groups);
323         return ret;
324  
325    err:
326  
327         *winbind_answered = False;
328         SAFE_FREE(groups);
329         return False;
330 }             
331  
332 /****************************************************************************
333  Check if a user is in a UNIX group.
334 ****************************************************************************/
335
336 static BOOL user_in_unix_group_list(char *user,char *gname)
337 {
338         struct group *gptr;
339         char **member;  
340         struct passwd *pass = Get_Pwnam(user,False);
341
342         DEBUG(10,("user_in_unix_group_list: checking user %s in group %s\n", user, gname));
343
344         /*
345          * We need to check the users primary group as this
346          * group is implicit and often not listed in the group database.
347          */
348  
349         if (pass) {
350                 gptr = getgrgid(pass->pw_gid);
351                 if (gptr && strequal(gptr->gr_name,gname)) {
352                         DEBUG(10,("user_in_unix_group_list: group %s is primary group.\n", gname ));
353                         return True;
354                 }
355         }
356  
357         if ((gptr = (struct group *)getgrnam(gname)) == NULL) {
358                 DEBUG(10,("user_in_unix_group_list: no such group %s\n", gname ));
359                 return False;
360         }
361  
362         member = gptr->gr_mem;
363         while (member && *member) {
364                 DEBUG(10,("user_in_unix_group_list: checking user %s against member %s\n", user, *member ));
365                 if (strequal(*member,user)) {
366                         return(True);
367                 }
368                 member++;
369         }
370
371         return False;
372 }             
373
374 /****************************************************************************
375  Check if a user is in a group list. Ask winbind first, then use UNIX.
376 ****************************************************************************/
377
378 BOOL user_in_group_list(char *user,char *gname)
379 {
380         BOOL winbind_answered = False;
381         BOOL ret = user_in_winbind_group_list(user, gname, &winbind_answered);
382
383         if (winbind_answered)
384                 return ret;
385
386         return user_in_unix_group_list(user, gname);    
387 }
388
389 /****************************************************************************
390  Check if a user is in a user list - can check combinations of UNIX
391  and netgroup lists.
392 ****************************************************************************/
393
394 BOOL user_in_list(char *user,char **list)
395 {
396
397   if (!list || !*list) return False;
398
399   DEBUG(10,("user_in_list: checking user %s in list\n", user));
400
401   while (*list) {
402     /*
403      * Check raw username.
404      */
405     if (strequal(user, *list))
406       return(True);
407
408     /*
409      * Now check to see if any combination
410      * of UNIX and netgroups has been specified.
411      */
412
413     if(**list == '@') {
414       /*
415        * Old behaviour. Check netgroup list
416        * followed by UNIX list.
417        */
418       if(user_in_netgroup_list(user, *list +1))
419         return True;
420       if(user_in_group_list(user, *list +1))
421         return True;
422     } else if (**list == '+') {
423
424       if((*(*list +1)) == '&') {
425         /*
426          * Search UNIX list followed by netgroup.
427          */
428         if(user_in_group_list(user, *list +2))
429           return True;
430         if(user_in_netgroup_list(user, *list +2))
431           return True;
432
433       } else {
434
435         /*
436          * Just search UNIX list.
437          */
438
439         if(user_in_group_list(user, *list +1))
440           return True;
441       }
442
443     } else if (**list == '&') {
444
445       if(*(*list +1) == '+') {
446         /*
447          * Search netgroup list followed by UNIX list.
448          */
449         if(user_in_netgroup_list(user, *list +2))
450           return True;
451         if(user_in_group_list(user, *list +2))
452           return True;
453       } else {
454         /*
455          * Just search netgroup list.
456          */
457         if(user_in_netgroup_list(user, *list +1))
458           return True;
459       }
460     }
461     
462     list++;
463   }
464   return(False);
465 }
466
467 /* The functions below have been taken from password.c and slightly modified */
468 /****************************************************************************
469  Apply a function to upper/lower case combinations
470  of a string and return true if one of them returns true.
471  Try all combinations with N uppercase letters.
472  offset is the first char to try and change (start with 0)
473  it assumes the string starts lowercased
474 ****************************************************************************/
475
476 static struct passwd *uname_string_combinations2(char *s,int offset,struct passwd *(*fn)(char *),int N)
477 {
478   ssize_t len = (ssize_t)strlen(s);
479   int i;
480   struct passwd *ret;
481
482 #ifdef PASSWORD_LENGTH
483   len = MIN(len,PASSWORD_LENGTH);
484 #endif
485
486   if (N <= 0 || offset >= len)
487     return(fn(s));
488
489   for (i=offset;i<(len-(N-1));i++) {
490     char c = s[i];
491     if (!islower(c))
492       continue;
493     s[i] = toupper(c);
494     ret = uname_string_combinations2(s,i+1,fn,N-1);
495     if(ret)
496       return(ret);
497     s[i] = c;
498   }
499   return(NULL);
500 }
501
502 /****************************************************************************
503  Apply a function to upper/lower case combinations
504  of a string and return true if one of them returns true.
505  Try all combinations with up to N uppercase letters.
506  offset is the first char to try and change (start with 0)
507  it assumes the string starts lowercased
508 ****************************************************************************/
509
510 static struct passwd * uname_string_combinations(char *s,struct passwd * (*fn)(char *),int N)
511 {
512   int n;
513   struct passwd *ret;
514
515   for (n=1;n<=N;n++) {
516     ret = uname_string_combinations2(s,0,fn,n);
517     if(ret)
518       return(ret);
519   }
520   return(NULL);
521 }
522
523
524 /****************************************************************************
525 these wrappers allow appliance mode to work. In appliance mode the username
526 takes the form DOMAIN/user
527 ****************************************************************************/
528 struct passwd *smb_getpwnam(char *user, BOOL allow_change)
529 {
530         struct passwd *pw;
531         char *p;
532         char *sep;
533         extern pstring global_myname;
534
535         pw = Get_Pwnam(user, allow_change);
536         if (pw) return pw;
537
538         /* if it is a domain qualified name and it isn't in our password
539            database but the domain portion matches our local machine name then
540            lookup just the username portion locally */
541         sep = lp_winbind_separator();
542         if (!sep || !*sep) sep = "\\";
543         p = strchr_m(user,*sep);
544         if (p && 
545             strncasecmp(global_myname, user, strlen(global_myname))==0) {
546                 return Get_Pwnam(p+1, allow_change);
547         }
548
549         return NULL;
550 }