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