r17669: Remove RID algorithm support from unmapped users and groups
[ira/wip.git] / source3 / passdb / pdb_interface.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Bartlett                        2002
5    Copyright (C) Jelmer Vernooij                        2002
6    Copyright (C) Simo Sorce                             2003
7    Copyright (C) Volker Lendecke                        2006
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 #undef DBGC_CLASS
27 #define DBGC_CLASS DBGC_PASSDB
28
29 /* Cache of latest SAM lookup query */
30
31 static struct samu *csamuser = NULL;
32
33 static_decl_pdb;
34
35 static struct pdb_init_function_entry *backends = NULL;
36
37 static void lazy_initialize_passdb(void)
38 {
39         static BOOL initialized = False;
40         if(initialized) {
41                 return;
42         }
43         static_init_pdb;
44         initialized = True;
45 }
46
47 static BOOL lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32 rid,
48                                   const char **name,
49                                   enum SID_NAME_USE *psid_name_use,
50                                   union unid_t *unix_id);
51 /*******************************************************************
52  Clean up uninitialised passwords.  The only way to tell 
53  that these values are not 'real' is that they do not
54  have a valid last set time.  Instead, the value is fixed at 0. 
55  Therefore we use that as the key for 'is this a valid password'.
56  However, it is perfectly valid to have a 'default' last change
57  time, such LDAP with a missing attribute would produce.
58 ********************************************************************/
59
60 static void pdb_force_pw_initialization(struct samu *pass) 
61 {
62         const uint8 *lm_pwd, *nt_pwd;
63         
64         /* only reset a password if the last set time has been 
65            explicitly been set to zero.  A default last set time 
66            is ignored */
67
68         if ( (pdb_get_init_flags(pass, PDB_PASSLASTSET) != PDB_DEFAULT) 
69                 && (pdb_get_pass_last_set_time(pass) == 0) ) 
70         {
71                 
72                 if (pdb_get_init_flags(pass, PDB_LMPASSWD) != PDB_DEFAULT) 
73                 {
74                         lm_pwd = pdb_get_lanman_passwd(pass);
75                         if (lm_pwd) 
76                                 pdb_set_lanman_passwd(pass, NULL, PDB_CHANGED);
77                 }
78                 if (pdb_get_init_flags(pass, PDB_NTPASSWD) != PDB_DEFAULT) 
79                 {
80                         nt_pwd = pdb_get_nt_passwd(pass);
81                         if (nt_pwd) 
82                                 pdb_set_nt_passwd(pass, NULL, PDB_CHANGED);
83                 }
84         }
85
86         return;
87 }
88
89 NTSTATUS smb_register_passdb(int version, const char *name, pdb_init_function init) 
90 {
91         struct pdb_init_function_entry *entry = backends;
92
93         if(version != PASSDB_INTERFACE_VERSION) {
94                 DEBUG(0,("Can't register passdb backend!\n"
95                          "You tried to register a passdb module with PASSDB_INTERFACE_VERSION %d, "
96                          "while this version of samba uses version %d\n", 
97                          version,PASSDB_INTERFACE_VERSION));
98                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
99         }
100
101         if (!name || !init) {
102                 return NT_STATUS_INVALID_PARAMETER;
103         }
104
105         DEBUG(5,("Attempting to register passdb backend %s\n", name));
106
107         /* Check for duplicates */
108         if (pdb_find_backend_entry(name)) {
109                 DEBUG(0,("There already is a passdb backend registered with the name %s!\n", name));
110                 return NT_STATUS_OBJECT_NAME_COLLISION;
111         }
112
113         entry = SMB_XMALLOC_P(struct pdb_init_function_entry);
114         entry->name = smb_xstrdup(name);
115         entry->init = init;
116
117         DLIST_ADD(backends, entry);
118         DEBUG(5,("Successfully added passdb backend '%s'\n", name));
119         return NT_STATUS_OK;
120 }
121
122 struct pdb_init_function_entry *pdb_find_backend_entry(const char *name)
123 {
124         struct pdb_init_function_entry *entry = backends;
125
126         while(entry) {
127                 if (strcmp(entry->name, name)==0) return entry;
128                 entry = entry->next;
129         }
130
131         return NULL;
132 }
133
134 /******************************************************************
135   Make a pdb_methods from scratch
136  *******************************************************************/
137
138 NTSTATUS make_pdb_method_name(struct pdb_methods **methods, const char *selected)
139 {
140         char *module_name = smb_xstrdup(selected);
141         char *module_location = NULL, *p;
142         struct pdb_init_function_entry *entry;
143         NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
144
145         lazy_initialize_passdb();
146
147         p = strchr(module_name, ':');
148
149         if (p) {
150                 *p = 0;
151                 module_location = p+1;
152                 trim_char(module_location, ' ', ' ');
153         }
154
155         trim_char(module_name, ' ', ' ');
156
157
158         DEBUG(5,("Attempting to find an passdb backend to match %s (%s)\n", selected, module_name));
159
160         entry = pdb_find_backend_entry(module_name);
161         
162         /* Try to find a module that contains this module */
163         if (!entry) { 
164                 DEBUG(2,("No builtin backend found, trying to load plugin\n"));
165                 if(NT_STATUS_IS_OK(smb_probe_module("pdb", module_name)) && !(entry = pdb_find_backend_entry(module_name))) {
166                         DEBUG(0,("Plugin is available, but doesn't register passdb backend %s\n", module_name));
167                         SAFE_FREE(module_name);
168                         return NT_STATUS_UNSUCCESSFUL;
169                 }
170         }
171         
172         /* No such backend found */
173         if(!entry) { 
174                 DEBUG(0,("No builtin nor plugin backend for %s found\n", module_name));
175                 SAFE_FREE(module_name);
176                 return NT_STATUS_INVALID_PARAMETER;
177         }
178
179         DEBUG(5,("Found pdb backend %s\n", module_name));
180
181         if ( !NT_STATUS_IS_OK( nt_status = entry->init(methods, module_location) ) ) {
182                 DEBUG(0,("pdb backend %s did not correctly init (error was %s)\n", 
183                         selected, nt_errstr(nt_status)));
184                 SAFE_FREE(module_name);
185                 return nt_status;
186         }
187
188         SAFE_FREE(module_name);
189
190         DEBUG(5,("pdb backend %s has a valid init\n", selected));
191
192         return nt_status;
193 }
194
195 /******************************************************************
196  Return an already initialised pdn_methods structure
197 *******************************************************************/
198
199 static struct pdb_methods *pdb_get_methods_reload( BOOL reload ) 
200 {
201         static struct pdb_methods *pdb = NULL;
202
203         if ( pdb && reload ) {
204                 pdb->free_private_data( &(pdb->private_data) );
205                 if ( !NT_STATUS_IS_OK( make_pdb_method_name( &pdb, lp_passdb_backend() ) ) ) {
206                         pstring msg;
207                         slprintf(msg, sizeof(msg)-1, "pdb_get_methods_reload: failed to get pdb methods for backend %s\n",
208                                 lp_passdb_backend() );
209                         smb_panic(msg);
210                 }
211         }
212
213         if ( !pdb ) {
214                 if ( !NT_STATUS_IS_OK( make_pdb_method_name( &pdb, lp_passdb_backend() ) ) ) {
215                         pstring msg;
216                         slprintf(msg, sizeof(msg)-1, "pdb_get_methods_reload: failed to get pdb methods for backend %s\n",
217                                 lp_passdb_backend() );
218                         smb_panic(msg);
219                 }
220         }
221
222         return pdb;
223 }
224
225 static struct pdb_methods *pdb_get_methods(void)
226 {
227         return pdb_get_methods_reload(False);
228 }
229
230 /******************************************************************
231  Backward compatibility functions for the original passdb interface
232 *******************************************************************/
233
234 BOOL pdb_setsampwent(BOOL update, uint16 acb_mask) 
235 {
236         struct pdb_methods *pdb = pdb_get_methods();
237         return NT_STATUS_IS_OK(pdb->setsampwent(pdb, update, acb_mask));
238 }
239
240 void pdb_endsampwent(void) 
241 {
242         struct pdb_methods *pdb = pdb_get_methods();
243         pdb->endsampwent(pdb);
244 }
245
246 BOOL pdb_getsampwent(struct samu *user) 
247 {
248         struct pdb_methods *pdb = pdb_get_methods();
249
250         if ( !NT_STATUS_IS_OK(pdb->getsampwent(pdb, user) ) ) {
251                 return False;
252         }
253         pdb_force_pw_initialization( user );
254         return True;
255 }
256
257 BOOL pdb_getsampwnam(struct samu *sam_acct, const char *username) 
258 {
259         struct pdb_methods *pdb = pdb_get_methods();
260
261         if (!NT_STATUS_IS_OK(pdb->getsampwnam(pdb, sam_acct, username))) {
262                 return False;
263         }
264
265         if ( csamuser ) {
266                 TALLOC_FREE(csamuser);
267         }
268
269         pdb_force_pw_initialization( sam_acct );
270         
271         csamuser = samu_new( NULL );
272         if (!csamuser) {
273                 return False;
274         }
275
276         if (!pdb_copy_sam_account(csamuser, sam_acct)) {
277                 TALLOC_FREE(csamuser);
278                 return False;
279         }
280
281         return True;
282 }
283
284 /**********************************************************************
285 **********************************************************************/
286
287 BOOL guest_user_info( struct samu *user )
288 {
289         struct passwd *pwd;
290         NTSTATUS result;
291         const char *guestname = lp_guestaccount();
292         
293         if ( !(pwd = getpwnam_alloc( NULL, guestname ) ) ) {
294                 DEBUG(0,("guest_user_info: Unable to locate guest account [%s]!\n", 
295                         guestname));
296                 return False;
297         }
298         
299         result = samu_set_unix(user, pwd );
300
301         TALLOC_FREE( pwd );
302
303         return NT_STATUS_IS_OK( result );
304 }
305
306 /**********************************************************************
307 **********************************************************************/
308
309 BOOL pdb_getsampwsid(struct samu *sam_acct, const DOM_SID *sid) 
310 {
311         struct pdb_methods *pdb = pdb_get_methods();
312         uint32 rid;
313
314         /* hard code the Guest RID of 501 */
315
316         if ( !sid_peek_check_rid( get_global_sam_sid(), sid, &rid ) )
317                 return False;
318
319         if ( rid == DOMAIN_USER_RID_GUEST ) {
320                 DEBUG(6,("pdb_getsampwsid: Building guest account\n"));
321                 return guest_user_info( sam_acct );
322         }
323         
324         /* check the cache first */
325         
326         if ( csamuser && sid_equal(sid, pdb_get_user_sid(csamuser) ) )
327                 return pdb_copy_sam_account(sam_acct, csamuser);
328
329         return NT_STATUS_IS_OK(pdb->getsampwsid(pdb, sam_acct, sid));
330 }
331
332 static NTSTATUS pdb_default_create_user(struct pdb_methods *methods,
333                                         TALLOC_CTX *tmp_ctx, const char *name,
334                                         uint32 acb_info, uint32 *rid)
335 {
336         struct samu *sam_pass;
337         NTSTATUS status;
338         struct passwd *pwd;
339
340         if ((sam_pass = samu_new(tmp_ctx)) == NULL) {
341                 return NT_STATUS_NO_MEMORY;
342         }
343
344         if ( !(pwd = Get_Pwnam_alloc(tmp_ctx, name)) ) {
345                 pstring add_script;
346                 int add_ret;
347                 fstring name2;
348
349                 if ((acb_info & ACB_NORMAL) && name[strlen(name)-1] != '$') {
350                         pstrcpy(add_script, lp_adduser_script());
351                 } else {
352                         pstrcpy(add_script, lp_addmachine_script());
353                 }
354
355                 if (add_script[0] == '\0') {
356                         DEBUG(3, ("Could not find user %s and no add script "
357                                   "defined\n", name));
358                         return NT_STATUS_NO_SUCH_USER;
359                 }
360
361                 /* lowercase the username before creating the Unix account for 
362                    compatibility with previous Samba releases */
363                 fstrcpy( name2, name );
364                 strlower_m( name2 );
365                 all_string_sub(add_script, "%u", name2, sizeof(add_script));
366                 add_ret = smbrun(add_script,NULL);
367                 DEBUG(add_ret ? 0 : 3, ("_samr_create_user: Running the command `%s' gave %d\n",
368                                         add_script, add_ret));
369
370 #ifdef ENABLE_BUILD_FARM_HACKS
371                 if (add_ret != 0) {
372                         DEBUG(1, ("Creating a faked user %s for build farm "
373                                   "purposes", name));
374                         faked_create_user(name);
375                 }
376 #endif
377
378                 flush_pwnam_cache();
379
380                 pwd = Get_Pwnam_alloc(tmp_ctx, name);
381         }
382
383         /* we have a valid SID coming out of this call */
384
385         status = samu_alloc_rid_unix( sam_pass, pwd );
386
387         TALLOC_FREE( pwd );
388
389         if (!NT_STATUS_IS_OK(status)) {
390                 DEBUG(3, ("pdb_default_create_user: failed to create a new user structure: %s\n", nt_errstr(status)));
391                 return status;
392         }
393
394         if (!sid_peek_check_rid(get_global_sam_sid(),
395                                 pdb_get_user_sid(sam_pass), rid)) {
396                 DEBUG(0, ("Could not get RID of fresh user\n"));
397                 return NT_STATUS_INTERNAL_ERROR;
398         }
399
400         /* Use the username case specified in the original request */
401
402         pdb_set_username( sam_pass, name, PDB_SET );
403
404         /* Disable the account on creation, it does not have a reasonable password yet. */
405
406         acb_info |= ACB_DISABLED;
407
408         pdb_set_acct_ctrl(sam_pass, acb_info, PDB_CHANGED);
409
410         status = pdb_add_sam_account(sam_pass);
411
412         TALLOC_FREE(sam_pass);
413
414         return status;
415 }
416
417 NTSTATUS pdb_create_user(TALLOC_CTX *mem_ctx, const char *name, uint32 flags,
418                          uint32 *rid)
419 {
420         struct pdb_methods *pdb = pdb_get_methods();
421         return pdb->create_user(pdb, mem_ctx, name, flags, rid);
422 }
423
424 /****************************************************************************
425  Delete a UNIX user on demand.
426 ****************************************************************************/
427
428 static int smb_delete_user(const char *unix_user)
429 {
430         pstring del_script;
431         int ret;
432
433         /* safety check */
434
435         if ( strequal( unix_user, "root" ) ) {
436                 DEBUG(0,("smb_delete_user: Refusing to delete local system root account!\n"));
437                 return -1;
438         }
439
440         pstrcpy(del_script, lp_deluser_script());
441         if (! *del_script)
442                 return -1;
443         all_string_sub(del_script, "%u", unix_user, sizeof(del_script));
444         ret = smbrun(del_script,NULL);
445         flush_pwnam_cache();
446         DEBUG(ret ? 0 : 3,("smb_delete_user: Running the command `%s' gave %d\n",del_script,ret));
447
448         return ret;
449 }
450
451 static NTSTATUS pdb_default_delete_user(struct pdb_methods *methods,
452                                         TALLOC_CTX *mem_ctx,
453                                         struct samu *sam_acct)
454 {
455         NTSTATUS status;
456         fstring username;
457
458         status = pdb_delete_sam_account(sam_acct);
459         if (!NT_STATUS_IS_OK(status)) {
460                 return status;
461         }
462
463         /*
464          * Now delete the unix side ....
465          * note: we don't check if the delete really happened as the script is
466          * not necessary present and maybe the sysadmin doesn't want to delete
467          * the unix side
468          */
469
470         /* always lower case the username before handing it off to 
471            external scripts */
472
473         fstrcpy( username, pdb_get_username(sam_acct) );
474         strlower_m( username );
475
476         smb_delete_user( username );
477         
478         return status;
479 }
480
481 NTSTATUS pdb_delete_user(TALLOC_CTX *mem_ctx, struct samu *sam_acct)
482 {
483         struct pdb_methods *pdb = pdb_get_methods();
484         uid_t uid = -1;
485
486         /* sanity check to make sure we don't delete root */
487
488         if ( !sid_to_uid( pdb_get_user_sid(sam_acct), &uid ) ) {
489                 return NT_STATUS_NO_SUCH_USER;
490         }
491
492         if ( uid == 0 ) {
493                 return NT_STATUS_ACCESS_DENIED;
494         }
495
496         return pdb->delete_user(pdb, mem_ctx, sam_acct);
497 }
498
499 NTSTATUS pdb_add_sam_account(struct samu *sam_acct) 
500 {
501         struct pdb_methods *pdb = pdb_get_methods();
502         return pdb->add_sam_account(pdb, sam_acct);
503 }
504
505 NTSTATUS pdb_update_sam_account(struct samu *sam_acct) 
506 {
507         struct pdb_methods *pdb = pdb_get_methods();
508
509         if (csamuser != NULL) {
510                 TALLOC_FREE(csamuser);
511                 csamuser = NULL;
512         }
513
514         return pdb->update_sam_account(pdb, sam_acct);
515 }
516
517 NTSTATUS pdb_delete_sam_account(struct samu *sam_acct) 
518 {
519         struct pdb_methods *pdb = pdb_get_methods();
520
521         if (csamuser != NULL) {
522                 TALLOC_FREE(csamuser);
523                 csamuser = NULL;
524         }
525
526         return pdb->delete_sam_account(pdb, sam_acct);
527 }
528
529 NTSTATUS pdb_rename_sam_account(struct samu *oldname, const char *newname)
530 {
531         struct pdb_methods *pdb = pdb_get_methods();
532         uid_t uid;
533         NTSTATUS status;
534
535         if (csamuser != NULL) {
536                 TALLOC_FREE(csamuser);
537                 csamuser = NULL;
538         }
539
540         /* sanity check to make sure we don't rename root */
541
542         if ( !sid_to_uid( pdb_get_user_sid(oldname), &uid ) ) {
543                 return NT_STATUS_NO_SUCH_USER;
544         }
545
546         if ( uid == 0 ) {
547                 return NT_STATUS_ACCESS_DENIED;
548         }
549
550         status = pdb->rename_sam_account(pdb, oldname, newname);
551
552         /* always flush the cache here just to be safe */
553         flush_pwnam_cache();
554
555         return status;
556 }
557
558 NTSTATUS pdb_update_login_attempts(struct samu *sam_acct, BOOL success)
559 {
560         struct pdb_methods *pdb = pdb_get_methods();
561         return pdb->update_login_attempts(pdb, sam_acct, success);
562 }
563
564 BOOL pdb_getgrsid(GROUP_MAP *map, DOM_SID sid)
565 {
566         struct pdb_methods *pdb = pdb_get_methods();
567         return NT_STATUS_IS_OK(pdb->getgrsid(pdb, map, sid));
568 }
569
570 BOOL pdb_getgrgid(GROUP_MAP *map, gid_t gid)
571 {
572         struct pdb_methods *pdb = pdb_get_methods();
573         return NT_STATUS_IS_OK(pdb->getgrgid(pdb, map, gid));
574 }
575
576 BOOL pdb_getgrnam(GROUP_MAP *map, const char *name)
577 {
578         struct pdb_methods *pdb = pdb_get_methods();
579         return NT_STATUS_IS_OK(pdb->getgrnam(pdb, map, name));
580 }
581
582 static NTSTATUS pdb_default_create_dom_group(struct pdb_methods *methods,
583                                              TALLOC_CTX *mem_ctx,
584                                              const char *name,
585                                              uint32 *rid)
586 {
587         DOM_SID group_sid;
588         struct group *grp;
589
590         grp = getgrnam(name);
591
592         if (grp == NULL) {
593                 gid_t gid;
594
595                 if (smb_create_group(name, &gid) != 0) {
596                         return NT_STATUS_ACCESS_DENIED;
597                 }
598
599                 grp = getgrgid(gid);
600         }
601
602         if (grp == NULL) {
603                 return NT_STATUS_ACCESS_DENIED;
604         }
605
606         if (pdb_rid_algorithm()) {
607                 *rid = algorithmic_pdb_gid_to_group_rid( grp->gr_gid );
608         } else {
609                 if (!pdb_new_rid(rid)) {
610                         return NT_STATUS_ACCESS_DENIED;
611                 }
612         }
613
614         sid_compose(&group_sid, get_global_sam_sid(), *rid);
615                 
616         return add_initial_entry(grp->gr_gid, sid_string_static(&group_sid),
617                                  SID_NAME_DOM_GRP, name, NULL);
618 }
619
620 NTSTATUS pdb_create_dom_group(TALLOC_CTX *mem_ctx, const char *name,
621                               uint32 *rid)
622 {
623         struct pdb_methods *pdb = pdb_get_methods();
624         return pdb->create_dom_group(pdb, mem_ctx, name, rid);
625 }
626
627 static NTSTATUS pdb_default_delete_dom_group(struct pdb_methods *methods,
628                                              TALLOC_CTX *mem_ctx,
629                                              uint32 rid)
630 {
631         DOM_SID group_sid;
632         GROUP_MAP map;
633         NTSTATUS status;
634         struct group *grp;
635         const char *grp_name;
636
637         sid_compose(&group_sid, get_global_sam_sid(), rid);
638
639         if (!get_domain_group_from_sid(group_sid, &map)) {
640                 DEBUG(10, ("Could not find group for rid %d\n", rid));
641                 return NT_STATUS_NO_SUCH_GROUP;
642         }
643
644         /* We need the group name for the smb_delete_group later on */
645
646         if (map.gid == (gid_t)-1) {
647                 return NT_STATUS_NO_SUCH_GROUP;
648         }
649
650         grp = getgrgid(map.gid);
651         if (grp == NULL) {
652                 return NT_STATUS_NO_SUCH_GROUP;
653         }
654
655         /* Copy the name, no idea what pdb_delete_group_mapping_entry does.. */
656
657         grp_name = talloc_strdup(mem_ctx, grp->gr_name);
658         if (grp_name == NULL) {
659                 return NT_STATUS_NO_MEMORY;
660         }
661
662         status = pdb_delete_group_mapping_entry(group_sid);
663
664         if (!NT_STATUS_IS_OK(status)) {
665                 return status;
666         }
667
668         /* Don't check the result of smb_delete_group */
669         
670         smb_delete_group(grp_name);
671
672         return NT_STATUS_OK;
673 }
674
675 NTSTATUS pdb_delete_dom_group(TALLOC_CTX *mem_ctx, uint32 rid)
676 {
677         struct pdb_methods *pdb = pdb_get_methods();
678         return pdb->delete_dom_group(pdb, mem_ctx, rid);
679 }
680
681 NTSTATUS pdb_add_group_mapping_entry(GROUP_MAP *map)
682 {
683         struct pdb_methods *pdb = pdb_get_methods();
684         return pdb->add_group_mapping_entry(pdb, map);
685 }
686
687 NTSTATUS pdb_update_group_mapping_entry(GROUP_MAP *map)
688 {
689         struct pdb_methods *pdb = pdb_get_methods();
690         return pdb->update_group_mapping_entry(pdb, map);
691 }
692
693 NTSTATUS pdb_delete_group_mapping_entry(DOM_SID sid)
694 {
695         struct pdb_methods *pdb = pdb_get_methods();
696         return pdb->delete_group_mapping_entry(pdb, sid);
697 }
698
699 BOOL pdb_enum_group_mapping(const DOM_SID *sid, enum SID_NAME_USE sid_name_use, GROUP_MAP **pp_rmap,
700                             size_t *p_num_entries, BOOL unix_only)
701 {
702         struct pdb_methods *pdb = pdb_get_methods();
703         return NT_STATUS_IS_OK(pdb-> enum_group_mapping(pdb, sid, sid_name_use,
704                 pp_rmap, p_num_entries, unix_only));
705 }
706
707 NTSTATUS pdb_enum_group_members(TALLOC_CTX *mem_ctx,
708                                 const DOM_SID *sid,
709                                 uint32 **pp_member_rids,
710                                 size_t *p_num_members)
711 {
712         struct pdb_methods *pdb = pdb_get_methods();
713         NTSTATUS result;
714
715         result = pdb->enum_group_members(pdb, mem_ctx, 
716                         sid, pp_member_rids, p_num_members);
717                 
718         /* special check for rid 513 */
719                 
720         if ( !NT_STATUS_IS_OK( result ) ) {
721                 uint32 rid;
722                 
723                 sid_peek_rid( sid, &rid );
724                 
725                 if ( rid == DOMAIN_GROUP_RID_USERS ) {
726                         *p_num_members = 0;
727                         *pp_member_rids = NULL;
728                         
729                         return NT_STATUS_OK;
730                 }
731         }
732         
733         return result;
734 }
735
736 NTSTATUS pdb_enum_group_memberships(TALLOC_CTX *mem_ctx, struct samu *user,
737                                     DOM_SID **pp_sids, gid_t **pp_gids,
738                                     size_t *p_num_groups)
739 {
740         struct pdb_methods *pdb = pdb_get_methods();
741         return pdb->enum_group_memberships(
742                 pdb, mem_ctx, user,
743                 pp_sids, pp_gids, p_num_groups);
744 }
745
746 static NTSTATUS pdb_default_set_unix_primary_group(struct pdb_methods *methods,
747                                                    TALLOC_CTX *mem_ctx,
748                                                    struct samu *sampass)
749 {
750         struct group *grp;
751         gid_t gid;
752
753         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid) ||
754             (grp = getgrgid(gid)) == NULL) {
755                 return NT_STATUS_INVALID_PRIMARY_GROUP;
756         }
757
758         if (smb_set_primary_group(grp->gr_name,
759                                   pdb_get_username(sampass)) != 0) {
760                 return NT_STATUS_ACCESS_DENIED;
761         }
762
763         return NT_STATUS_OK;
764 }
765
766 NTSTATUS pdb_set_unix_primary_group(TALLOC_CTX *mem_ctx, struct samu *user)
767 {
768         struct pdb_methods *pdb = pdb_get_methods();
769         return pdb->set_unix_primary_group(pdb, mem_ctx, user);
770 }
771
772 /*
773  * Helper function to see whether a user is in a group. We can't use
774  * user_in_group_sid here because this creates dependencies only smbd can
775  * fulfil.
776  */
777
778 static BOOL pdb_user_in_group(TALLOC_CTX *mem_ctx, struct samu *account,
779                               const DOM_SID *group_sid)
780 {
781         DOM_SID *sids;
782         gid_t *gids;
783         size_t i, num_groups;
784
785         if (!NT_STATUS_IS_OK(pdb_enum_group_memberships(mem_ctx, account,
786                                                         &sids, &gids,
787                                                         &num_groups))) {
788                 return False;
789         }
790
791         for (i=0; i<num_groups; i++) {
792                 if (sid_equal(group_sid, &sids[i])) {
793                         return True;
794                 }
795         }
796         return False;
797 }
798
799 static NTSTATUS pdb_default_add_groupmem(struct pdb_methods *methods,
800                                          TALLOC_CTX *mem_ctx,
801                                          uint32 group_rid,
802                                          uint32 member_rid)
803 {
804         DOM_SID group_sid, member_sid;
805         struct samu *account = NULL;
806         GROUP_MAP map;
807         struct group *grp;
808         struct passwd *pwd;
809         const char *group_name;
810         uid_t uid;
811
812         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
813         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
814
815         if (!get_domain_group_from_sid(group_sid, &map) ||
816             (map.gid == (gid_t)-1) ||
817             ((grp = getgrgid(map.gid)) == NULL)) {
818                 return NT_STATUS_NO_SUCH_GROUP;
819         }
820
821         group_name = talloc_strdup(mem_ctx, grp->gr_name);
822         if (group_name == NULL) {
823                 return NT_STATUS_NO_MEMORY;
824         }
825
826         if ( !(account = samu_new( NULL )) ) {
827                 return NT_STATUS_NO_MEMORY;
828         }
829
830         if (!pdb_getsampwsid(account, &member_sid) ||
831             !sid_to_uid(&member_sid, &uid) ||
832             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
833                 return NT_STATUS_NO_SUCH_USER;
834         }
835
836         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
837                 return NT_STATUS_MEMBER_IN_GROUP;
838         }
839
840         /* 
841          * ok, the group exist, the user exist, the user is not in the group,
842          * we can (finally) add it to the group !
843          */
844
845         smb_add_user_group(group_name, pwd->pw_name);
846
847         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
848                 return NT_STATUS_ACCESS_DENIED;
849         }
850
851         return NT_STATUS_OK;
852 }
853
854 NTSTATUS pdb_add_groupmem(TALLOC_CTX *mem_ctx, uint32 group_rid,
855                           uint32 member_rid)
856 {
857         struct pdb_methods *pdb = pdb_get_methods();
858         return pdb->add_groupmem(pdb, mem_ctx, group_rid, member_rid);
859 }
860
861 static NTSTATUS pdb_default_del_groupmem(struct pdb_methods *methods,
862                                          TALLOC_CTX *mem_ctx,
863                                          uint32 group_rid,
864                                          uint32 member_rid)
865 {
866         DOM_SID group_sid, member_sid;
867         struct samu *account = NULL;
868         GROUP_MAP map;
869         struct group *grp;
870         struct passwd *pwd;
871         const char *group_name;
872         uid_t uid;
873
874         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
875         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
876
877         if (!get_domain_group_from_sid(group_sid, &map) ||
878             (map.gid == (gid_t)-1) ||
879             ((grp = getgrgid(map.gid)) == NULL)) {
880                 return NT_STATUS_NO_SUCH_GROUP;
881         }
882
883         group_name = talloc_strdup(mem_ctx, grp->gr_name);
884         if (group_name == NULL) {
885                 return NT_STATUS_NO_MEMORY;
886         }
887
888         if ( !(account = samu_new( NULL )) ) {
889                 return NT_STATUS_NO_MEMORY;
890         }
891
892         if (!pdb_getsampwsid(account, &member_sid) ||
893             !sid_to_uid(&member_sid, &uid) ||
894             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
895                 return NT_STATUS_NO_SUCH_USER;
896         }
897
898         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
899                 return NT_STATUS_MEMBER_NOT_IN_GROUP;
900         }
901
902         /* 
903          * ok, the group exist, the user exist, the user is in the group,
904          * we can (finally) delete it from the group!
905          */
906
907         smb_delete_user_group(group_name, pwd->pw_name);
908
909         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
910                 return NT_STATUS_ACCESS_DENIED;
911         }
912
913         return NT_STATUS_OK;
914 }
915
916 NTSTATUS pdb_del_groupmem(TALLOC_CTX *mem_ctx, uint32 group_rid,
917                           uint32 member_rid)
918 {
919         struct pdb_methods *pdb = pdb_get_methods();
920         return pdb->del_groupmem(pdb, mem_ctx, group_rid, member_rid);
921 }
922
923 BOOL pdb_find_alias(const char *name, DOM_SID *sid)
924 {
925         struct pdb_methods *pdb = pdb_get_methods();
926         return NT_STATUS_IS_OK(pdb->find_alias(pdb, name, sid));
927 }
928
929 NTSTATUS pdb_create_alias(const char *name, uint32 *rid)
930 {
931         struct pdb_methods *pdb = pdb_get_methods();
932         return pdb->create_alias(pdb, name, rid);
933 }
934
935 BOOL pdb_delete_alias(const DOM_SID *sid)
936 {
937         struct pdb_methods *pdb = pdb_get_methods();
938         return NT_STATUS_IS_OK(pdb->delete_alias(pdb, sid));
939                                                             
940 }
941
942 BOOL pdb_get_aliasinfo(const DOM_SID *sid, struct acct_info *info)
943 {
944         struct pdb_methods *pdb = pdb_get_methods();
945         return NT_STATUS_IS_OK(pdb->get_aliasinfo(pdb, sid, info));
946 }
947
948 BOOL pdb_set_aliasinfo(const DOM_SID *sid, struct acct_info *info)
949 {
950         struct pdb_methods *pdb = pdb_get_methods();
951         return NT_STATUS_IS_OK(pdb->set_aliasinfo(pdb, sid, info));
952 }
953
954 NTSTATUS pdb_add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
955 {
956         struct pdb_methods *pdb = pdb_get_methods();
957         return pdb->add_aliasmem(pdb, alias, member);
958 }
959
960 NTSTATUS pdb_del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
961 {
962         struct pdb_methods *pdb = pdb_get_methods();
963         return pdb->del_aliasmem(pdb, alias, member);
964 }
965
966 NTSTATUS pdb_enum_aliasmem(const DOM_SID *alias,
967                            DOM_SID **pp_members, size_t *p_num_members)
968 {
969         struct pdb_methods *pdb = pdb_get_methods();
970         return pdb->enum_aliasmem(pdb, alias, pp_members, p_num_members);
971 }
972
973 NTSTATUS pdb_enum_alias_memberships(TALLOC_CTX *mem_ctx,
974                                     const DOM_SID *domain_sid,
975                                     const DOM_SID *members, size_t num_members,
976                                     uint32 **pp_alias_rids,
977                                     size_t *p_num_alias_rids)
978 {
979         struct pdb_methods *pdb = pdb_get_methods();
980         return pdb->enum_alias_memberships(pdb, mem_ctx,
981                                                        domain_sid,
982                                                        members, num_members,
983                                                        pp_alias_rids,
984                                                        p_num_alias_rids);
985 }
986
987 NTSTATUS pdb_lookup_rids(const DOM_SID *domain_sid,
988                          int num_rids,
989                          uint32 *rids,
990                          const char **names,
991                          enum SID_NAME_USE *attrs)
992 {
993         struct pdb_methods *pdb = pdb_get_methods();
994         return pdb->lookup_rids(pdb, domain_sid, num_rids, rids, names, attrs);
995 }
996
997 NTSTATUS pdb_lookup_names(const DOM_SID *domain_sid,
998                           int num_names,
999                           const char **names,
1000                           uint32 *rids,
1001                           enum SID_NAME_USE *attrs)
1002 {
1003         struct pdb_methods *pdb = pdb_get_methods();
1004         return pdb->lookup_names(pdb, domain_sid, num_names, names, rids, attrs);
1005 }
1006
1007 BOOL pdb_get_account_policy(int policy_index, uint32 *value)
1008 {
1009         struct pdb_methods *pdb = pdb_get_methods();
1010         return NT_STATUS_IS_OK(pdb->get_account_policy(pdb, policy_index, value));
1011 }
1012
1013 BOOL pdb_set_account_policy(int policy_index, uint32 value)
1014 {
1015         struct pdb_methods *pdb = pdb_get_methods();
1016         return NT_STATUS_IS_OK(pdb->set_account_policy(pdb, policy_index, value));
1017 }
1018
1019 BOOL pdb_get_seq_num(time_t *seq_num)
1020 {
1021         struct pdb_methods *pdb = pdb_get_methods();
1022         return NT_STATUS_IS_OK(pdb->get_seq_num(pdb, seq_num));
1023 }
1024
1025 BOOL pdb_uid_to_rid(uid_t uid, uint32 *rid)
1026 {
1027         struct pdb_methods *pdb = pdb_get_methods();
1028         return pdb->uid_to_rid(pdb, uid, rid);
1029 }
1030
1031 BOOL pdb_gid_to_sid(gid_t gid, DOM_SID *sid)
1032 {
1033         struct pdb_methods *pdb = pdb_get_methods();
1034         return pdb->gid_to_sid(pdb, gid, sid);
1035 }
1036
1037 BOOL pdb_sid_to_id(const DOM_SID *sid, union unid_t *id,
1038                    enum SID_NAME_USE *type)
1039 {
1040         struct pdb_methods *pdb = pdb_get_methods();
1041         return pdb->sid_to_id(pdb, sid, id, type);
1042 }
1043
1044 BOOL pdb_rid_algorithm(void)
1045 {
1046         struct pdb_methods *pdb = pdb_get_methods();
1047         return pdb->rid_algorithm(pdb);
1048 }
1049
1050 /********************************************************************
1051  Allocate a new RID from the passdb backend.  Verify that it is free
1052  by calling lookup_global_sam_rid() to verify that the RID is not
1053  in use.  This handles servers that have existing users or groups
1054  with add RIDs (assigned from previous algorithmic mappings)
1055 ********************************************************************/
1056
1057 BOOL pdb_new_rid(uint32 *rid)
1058 {
1059         struct pdb_methods *pdb = pdb_get_methods();
1060         const char *name = NULL;
1061         enum SID_NAME_USE type;
1062         uint32 allocated_rid = 0;
1063         int i;
1064         TALLOC_CTX *ctx;
1065
1066         if (pdb_rid_algorithm()) {
1067                 DEBUG(0, ("Trying to allocate a RID when algorithmic RIDs "
1068                           "are active\n"));
1069                 return False;
1070         }
1071
1072         if (algorithmic_rid_base() != BASE_RID) {
1073                 DEBUG(0, ("'algorithmic rid base' is set but a passdb backend "
1074                           "without algorithmic RIDs is chosen.\n"));
1075                 DEBUGADD(0, ("Please map all used groups using 'net groupmap "
1076                              "add', set the maximum used RID using\n"));
1077                 DEBUGADD(0, ("'net setmaxrid' and remove the parameter\n"));
1078                 return False;
1079         }
1080
1081         if ( (ctx = talloc_init("pdb_new_rid")) == NULL ) {
1082                 DEBUG(0,("pdb_new_rid: Talloc initialization failure\n"));
1083                 return False;
1084         }
1085
1086         /* Attempt to get an unused RID (max tires is 250...yes that it is 
1087            and arbitrary number I pulkled out of my head).   -- jerry */
1088
1089         for ( i=0; allocated_rid==0 && i<250; i++ ) {
1090                 /* get a new RID */
1091
1092                 if ( !pdb->new_rid(pdb, &allocated_rid) ) {
1093                         return False;
1094                 }
1095
1096                 /* validate that the RID is not in use */
1097
1098                 if ( lookup_global_sam_rid( ctx, allocated_rid, &name, &type, NULL ) ) {
1099                         allocated_rid = 0;
1100                 }
1101         }
1102
1103         TALLOC_FREE( ctx );
1104
1105         if ( allocated_rid == 0 ) {
1106                 DEBUG(0,("pdb_new_rid: Failed to find unused RID\n"));
1107                 return False;
1108         }
1109
1110         *rid = allocated_rid;
1111
1112         return True;
1113 }
1114
1115 /***************************************************************
1116   Initialize the static context (at smbd startup etc). 
1117
1118   If uninitialised, context will auto-init on first use.
1119  ***************************************************************/
1120
1121 BOOL initialize_password_db(BOOL reload)
1122 {       
1123         return (pdb_get_methods_reload(reload) != NULL);
1124 }
1125
1126
1127 /***************************************************************************
1128   Default implementations of some functions.
1129  ****************************************************************************/
1130
1131 static NTSTATUS pdb_default_getsampwnam (struct pdb_methods *methods, struct samu *user, const char *sname)
1132 {
1133         return NT_STATUS_NO_SUCH_USER;
1134 }
1135
1136 static NTSTATUS pdb_default_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1137 {
1138         return NT_STATUS_NO_SUCH_USER;
1139 }
1140
1141 static NTSTATUS pdb_default_add_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1142 {
1143         return NT_STATUS_NOT_IMPLEMENTED;
1144 }
1145
1146 static NTSTATUS pdb_default_update_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1147 {
1148         return NT_STATUS_NOT_IMPLEMENTED;
1149 }
1150
1151 static NTSTATUS pdb_default_delete_sam_account (struct pdb_methods *methods, struct samu *pwd)
1152 {
1153         return NT_STATUS_NOT_IMPLEMENTED;
1154 }
1155
1156 static NTSTATUS pdb_default_rename_sam_account (struct pdb_methods *methods, struct samu *pwd, const char *newname)
1157 {
1158         return NT_STATUS_NOT_IMPLEMENTED;
1159 }
1160
1161 static NTSTATUS pdb_default_update_login_attempts (struct pdb_methods *methods, struct samu *newpwd, BOOL success)
1162 {
1163         return NT_STATUS_OK;
1164 }
1165
1166 static NTSTATUS pdb_default_setsampwent(struct pdb_methods *methods, BOOL update, uint32 acb_mask)
1167 {
1168         return NT_STATUS_NOT_IMPLEMENTED;
1169 }
1170
1171 static NTSTATUS pdb_default_getsampwent(struct pdb_methods *methods, struct samu *user)
1172 {
1173         return NT_STATUS_NOT_IMPLEMENTED;
1174 }
1175
1176 static void pdb_default_endsampwent(struct pdb_methods *methods)
1177 {
1178         return; /* NT_STATUS_NOT_IMPLEMENTED; */
1179 }
1180
1181 static NTSTATUS pdb_default_get_account_policy(struct pdb_methods *methods, int policy_index, uint32 *value)
1182 {
1183         return account_policy_get(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1184 }
1185
1186 static NTSTATUS pdb_default_set_account_policy(struct pdb_methods *methods, int policy_index, uint32 value)
1187 {
1188         return account_policy_set(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1189 }
1190
1191 static NTSTATUS pdb_default_get_seq_num(struct pdb_methods *methods, time_t *seq_num)
1192 {
1193         *seq_num = time(NULL);
1194         return NT_STATUS_OK;
1195 }
1196
1197 static BOOL pdb_default_uid_to_rid(struct pdb_methods *methods, uid_t uid,
1198                                    uint32 *rid)
1199 {
1200         struct samu *sampw = NULL;
1201         struct passwd *unix_pw;
1202         BOOL ret;
1203         
1204         unix_pw = sys_getpwuid( uid );
1205
1206         if ( !unix_pw ) {
1207                 DEBUG(4,("pdb_default_uid_to_rid: host has no idea of uid "
1208                          "%lu\n", (unsigned long)uid));
1209                 return False;
1210         }
1211         
1212         if ( !(sampw = samu_new( NULL )) ) {
1213                 DEBUG(0,("pdb_default_uid_to_rid: samu_new() failed!\n"));
1214                 return False;
1215         }
1216
1217         become_root();
1218         ret = NT_STATUS_IS_OK(
1219                 methods->getsampwnam(methods, sampw, unix_pw->pw_name ));
1220         unbecome_root();
1221
1222         if (!ret) {
1223                 DEBUG(5, ("pdb_default_uid_to_rid: Did not find user "
1224                           "%s (%d)\n", unix_pw->pw_name, uid));
1225                 TALLOC_FREE(sampw);
1226                 return False;
1227         }
1228
1229         ret = sid_peek_check_rid(get_global_sam_sid(),
1230                                  pdb_get_user_sid(sampw), rid);
1231
1232         if (!ret) {
1233                 DEBUG(1, ("Could not peek rid out of sid %s\n",
1234                           sid_string_static(pdb_get_user_sid(sampw))));
1235         }
1236
1237         TALLOC_FREE(sampw);
1238         return ret;
1239 }
1240
1241 static BOOL pdb_default_gid_to_sid(struct pdb_methods *methods, gid_t gid,
1242                                    DOM_SID *sid)
1243 {
1244         GROUP_MAP map;
1245
1246         if (!NT_STATUS_IS_OK(methods->getgrgid(methods, &map, gid))) {
1247                 return False;
1248         }
1249
1250         sid_copy(sid, &map.sid);
1251         return True;
1252 }
1253
1254 static BOOL pdb_default_sid_to_id(struct pdb_methods *methods,
1255                                   const DOM_SID *sid,
1256                                   union unid_t *id, enum SID_NAME_USE *type)
1257 {
1258         TALLOC_CTX *mem_ctx;
1259         BOOL ret = False;
1260         const char *name;
1261         uint32 rid;
1262
1263         mem_ctx = talloc_new(NULL);
1264
1265         if (mem_ctx == NULL) {
1266                 DEBUG(0, ("talloc_new failed\n"));
1267                 return False;
1268         }
1269
1270         if (sid_peek_check_rid(get_global_sam_sid(), sid, &rid)) {
1271                 /* Here we might have users as well as groups and aliases */
1272                 ret = lookup_global_sam_rid(mem_ctx, rid, &name, type, id);
1273                 goto done;
1274         }
1275
1276         if (sid_peek_check_rid(&global_sid_Builtin, sid, &rid)) {
1277                 /* Here we only have aliases */
1278                 GROUP_MAP map;
1279                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, &map, *sid))) {
1280                         DEBUG(10, ("Could not find map for sid %s\n",
1281                                    sid_string_static(sid)));
1282                         goto done;
1283                 }
1284                 if ((map.sid_name_use != SID_NAME_ALIAS) &&
1285                     (map.sid_name_use != SID_NAME_WKN_GRP)) {
1286                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1287                                    "alias\n", sid_string_static(sid),
1288                                    sid_type_lookup(map.sid_name_use)));
1289                         goto done;
1290                 }
1291
1292                 id->gid = map.gid;
1293                 *type = SID_NAME_ALIAS;
1294                 ret = True;
1295                 goto done;
1296         }
1297
1298         DEBUG(5, ("Sid %s is neither ours nor builtin, don't know it\n",
1299                   sid_string_static(sid)));
1300
1301  done:
1302
1303         TALLOC_FREE(mem_ctx);
1304         return ret;
1305 }
1306
1307 static void add_uid_to_array_unique(TALLOC_CTX *mem_ctx,
1308                                     uid_t uid, uid_t **pp_uids, size_t *p_num)
1309 {
1310         size_t i;
1311
1312         for (i=0; i<*p_num; i++) {
1313                 if ((*pp_uids)[i] == uid)
1314                         return;
1315         }
1316         
1317         *pp_uids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_uids, uid_t, *p_num+1);
1318
1319         if (*pp_uids == NULL)
1320                 return;
1321
1322         (*pp_uids)[*p_num] = uid;
1323         *p_num += 1;
1324 }
1325
1326 static BOOL get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, size_t *p_num)
1327 {
1328         struct group *grp;
1329         char **gr;
1330         struct passwd *pwd;
1331         char *winbindd_env;
1332  
1333         *pp_uids = NULL;
1334         *p_num = 0;
1335
1336         /* We only look at our own sam, so don't care about imported stuff */
1337
1338         winbindd_env = getenv(WINBINDD_DONT_ENV);
1339         winbind_off();
1340
1341         if ((grp = getgrgid(gid)) == NULL) {
1342                 /* allow winbindd lookups, but only if they weren't already disabled */
1343                 if ( !(winbindd_env && strequal(winbindd_env, "1")) ) {
1344                         winbind_on();
1345                 }
1346
1347                 return False;
1348         }
1349
1350         /* Primary group members */
1351
1352         setpwent();
1353         while ((pwd = getpwent()) != NULL) {
1354                 if (pwd->pw_gid == gid) {
1355                         add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1356                                                 pp_uids, p_num);
1357                 }
1358         }
1359         endpwent();
1360
1361         /* Secondary group members */
1362
1363         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1364                 struct passwd *pw = getpwnam(*gr);
1365
1366                 if (pw == NULL)
1367                         continue;
1368                 add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num);
1369         }
1370
1371         /* allow winbindd lookups, but only if they weren't already disabled */
1372
1373         if ( !(winbindd_env && strequal(winbindd_env, "1")) ) {
1374                 winbind_on();
1375         }
1376
1377         return True;
1378 }
1379
1380 NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1381                                         TALLOC_CTX *mem_ctx,
1382                                         const DOM_SID *group,
1383                                         uint32 **pp_member_rids,
1384                                         size_t *p_num_members)
1385 {
1386         gid_t gid;
1387         uid_t *uids;
1388         size_t i, num_uids;
1389
1390         *pp_member_rids = NULL;
1391         *p_num_members = 0;
1392
1393         if (!sid_to_gid(group, &gid))
1394                 return NT_STATUS_NO_SUCH_GROUP;
1395
1396         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1397                 return NT_STATUS_NO_SUCH_GROUP;
1398
1399         if (num_uids == 0)
1400                 return NT_STATUS_OK;
1401
1402         *pp_member_rids = TALLOC_ZERO_ARRAY(mem_ctx, uint32, num_uids);
1403
1404         for (i=0; i<num_uids; i++) {
1405                 DOM_SID sid;
1406
1407                 uid_to_sid(&sid, uids[i]);
1408
1409                 if (!sid_check_is_in_our_domain(&sid)) {
1410                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1411                                   "in our domain\n"));
1412                         continue;
1413                 }
1414
1415                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1416                 *p_num_members += 1;
1417         }
1418
1419         return NT_STATUS_OK;
1420 }
1421
1422 NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1423                                             TALLOC_CTX *mem_ctx,
1424                                             struct samu *user,
1425                                             DOM_SID **pp_sids,
1426                                             gid_t **pp_gids,
1427                                             size_t *p_num_groups)
1428 {
1429         size_t i;
1430         gid_t gid;
1431         struct passwd *pw;
1432         const char *username = pdb_get_username(user);
1433         
1434
1435         /* Ignore the primary group SID.  Honor the real Unix primary group.
1436            The primary group SID is only of real use to Windows clients */
1437            
1438         if ( !(pw = getpwnam_alloc(mem_ctx, username)) ) {
1439                 return NT_STATUS_NO_SUCH_USER;
1440         }
1441         
1442         gid = pw->pw_gid;
1443         
1444         TALLOC_FREE( pw );
1445
1446         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1447                 return NT_STATUS_NO_SUCH_USER;
1448         }
1449
1450         if (*p_num_groups == 0) {
1451                 smb_panic("primary group missing");
1452         }
1453
1454         *pp_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, *p_num_groups);
1455
1456         if (*pp_sids == NULL) {
1457                 TALLOC_FREE(*pp_gids);
1458                 return NT_STATUS_NO_MEMORY;
1459         }
1460
1461         for (i=0; i<*p_num_groups; i++) {
1462                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1463         }
1464
1465         return NT_STATUS_OK;
1466 }
1467
1468 /*******************************************************************
1469  Look up a rid in the SAM we're responsible for (i.e. passdb)
1470  ********************************************************************/
1471
1472 static BOOL lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32 rid,
1473                                   const char **name,
1474                                   enum SID_NAME_USE *psid_name_use,
1475                                   union unid_t *unix_id)
1476 {
1477         struct samu *sam_account = NULL;
1478         GROUP_MAP map;
1479         BOOL ret;
1480         DOM_SID sid;
1481
1482         *psid_name_use = SID_NAME_UNKNOWN;
1483         
1484         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1485                  (unsigned int)rid));
1486
1487         sid_copy(&sid, get_global_sam_sid());
1488         sid_append_rid(&sid, rid);
1489         
1490         /* see if the passdb can help us with the name of the user */
1491
1492         if ( !(sam_account = samu_new( NULL )) ) {
1493                 return False;
1494         }
1495
1496         /* BEING ROOT BLLOCK */
1497         become_root();
1498         if (pdb_getsampwsid(sam_account, &sid)) {
1499                 struct passwd *pw;
1500
1501                 unbecome_root();                /* -----> EXIT BECOME_ROOT() */
1502                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1503                 if (!*name) {
1504                         TALLOC_FREE(sam_account);
1505                         return False;
1506                 }
1507
1508                 *psid_name_use = SID_NAME_USER;
1509
1510                 TALLOC_FREE(sam_account);
1511
1512                 if (unix_id == NULL) {
1513                         return True;
1514                 }
1515
1516                 pw = Get_Pwnam(*name);
1517                 if (pw == NULL) {
1518                         return False;
1519                 }
1520                 unix_id->uid = pw->pw_uid;
1521                 return True;
1522         }
1523         TALLOC_FREE(sam_account);
1524         
1525         ret = pdb_getgrsid(&map, sid);
1526         unbecome_root();
1527         /* END BECOME_ROOT BLOCK */
1528   
1529         /* do not resolve SIDs to a name unless there is a valid 
1530            gid associated with it */
1531                    
1532         if ( ret && (map.gid != (gid_t)-1) ) {
1533                 *name = talloc_strdup(mem_ctx, map.nt_name);
1534                 *psid_name_use = map.sid_name_use;
1535
1536                 if ( unix_id ) {
1537                         unix_id->gid = map.gid;
1538                 }
1539
1540                 return True;
1541         }
1542         
1543         /* Windows will always map RID 513 to something.  On a non-domain 
1544            controller, this gets mapped to SERVER\None. */
1545
1546         if ( unix_id ) {
1547                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1548                 return False;
1549         }
1550         
1551         if ( rid == DOMAIN_GROUP_RID_USERS ) {
1552                 *name = talloc_strdup(mem_ctx, "None" );
1553                 *psid_name_use = SID_NAME_DOM_GRP;
1554                 
1555                 return True;
1556         }
1557
1558         return False;
1559 }
1560
1561 NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1562                                  const DOM_SID *domain_sid,
1563                                  int num_rids,
1564                                  uint32 *rids,
1565                                  const char **names,
1566                                  enum SID_NAME_USE *attrs)
1567 {
1568         int i;
1569         NTSTATUS result;
1570         BOOL have_mapped = False;
1571         BOOL have_unmapped = False;
1572
1573         if (sid_check_is_builtin(domain_sid)) {
1574
1575                 for (i=0; i<num_rids; i++) {
1576                         const char *name;
1577
1578                         if (lookup_builtin_rid(names, rids[i], &name)) {
1579                                 attrs[i] = SID_NAME_ALIAS;
1580                                 names[i] = name;
1581                                 DEBUG(5,("lookup_rids: %s:%d\n",
1582                                          names[i], attrs[i]));
1583                                 have_mapped = True;
1584                         } else {
1585                                 have_unmapped = True;
1586                                 attrs[i] = SID_NAME_UNKNOWN;
1587                         }
1588                 }
1589                 goto done;
1590         }
1591
1592         /* Should not happen, but better check once too many */
1593         if (!sid_check_is_domain(domain_sid)) {
1594                 return NT_STATUS_INVALID_HANDLE;
1595         }
1596
1597         for (i = 0; i < num_rids; i++) {
1598                 const char *name;
1599
1600                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1601                                           NULL)) {
1602                         if (name == NULL) {
1603                                 return NT_STATUS_NO_MEMORY;
1604                         }
1605                         names[i] = name;
1606                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1607                         have_mapped = True;
1608                 } else {
1609                         have_unmapped = True;
1610                         attrs[i] = SID_NAME_UNKNOWN;
1611                 }
1612         }
1613
1614  done:
1615
1616         result = NT_STATUS_NONE_MAPPED;
1617
1618         if (have_mapped)
1619                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1620
1621         return result;
1622 }
1623
1624 NTSTATUS pdb_default_lookup_names(struct pdb_methods *methods,
1625                                   const DOM_SID *domain_sid,
1626                                   int num_names,
1627                                   const char **names,
1628                                   uint32 *rids,
1629                                   enum SID_NAME_USE *attrs)
1630 {
1631         int i;
1632         NTSTATUS result;
1633         BOOL have_mapped = False;
1634         BOOL have_unmapped = False;
1635
1636         if (sid_check_is_builtin(domain_sid)) {
1637
1638                 for (i=0; i<num_names; i++) {
1639                         uint32 rid;
1640
1641                         if (lookup_builtin_name(names[i], &rid)) {
1642                                 attrs[i] = SID_NAME_ALIAS;
1643                                 rids[i] = rid;
1644                                 DEBUG(5,("lookup_rids: %s:%d\n",
1645                                          names[i], attrs[i]));
1646                                 have_mapped = True;
1647                         } else {
1648                                 have_unmapped = True;
1649                                 attrs[i] = SID_NAME_UNKNOWN;
1650                         }
1651                 }
1652                 goto done;
1653         }
1654
1655         /* Should not happen, but better check once too many */
1656         if (!sid_check_is_domain(domain_sid)) {
1657                 return NT_STATUS_INVALID_HANDLE;
1658         }
1659
1660         for (i = 0; i < num_names; i++) {
1661                 if (lookup_global_sam_name(names[i], 0, &rids[i], &attrs[i])) {
1662                         DEBUG(5,("lookup_names: %s-> %d:%d\n", names[i],
1663                                  rids[i], attrs[i]));
1664                         have_mapped = True;
1665                 } else {
1666                         have_unmapped = True;
1667                         attrs[i] = SID_NAME_UNKNOWN;
1668                 }
1669         }
1670
1671  done:
1672
1673         result = NT_STATUS_NONE_MAPPED;
1674
1675         if (have_mapped)
1676                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1677
1678         return result;
1679 }
1680
1681 static struct pdb_search *pdb_search_init(enum pdb_search_type type)
1682 {
1683         TALLOC_CTX *mem_ctx;
1684         struct pdb_search *result;
1685
1686         mem_ctx = talloc_init("pdb_search");
1687         if (mem_ctx == NULL) {
1688                 DEBUG(0, ("talloc_init failed\n"));
1689                 return NULL;
1690         }
1691
1692         result = TALLOC_P(mem_ctx, struct pdb_search);
1693         if (result == NULL) {
1694                 DEBUG(0, ("talloc failed\n"));
1695                 return NULL;
1696         }
1697
1698         result->mem_ctx = mem_ctx;
1699         result->type = type;
1700         result->cache = NULL;
1701         result->num_entries = 0;
1702         result->cache_size = 0;
1703         result->search_ended = False;
1704
1705         /* Segfault appropriately if not initialized */
1706         result->next_entry = NULL;
1707         result->search_end = NULL;
1708
1709         return result;
1710 }
1711
1712 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32 rid,
1713                               uint16 acct_flags,
1714                               const char *account_name,
1715                               const char *fullname,
1716                               const char *description,
1717                               struct samr_displayentry *entry)
1718 {
1719         entry->rid = rid;
1720         entry->acct_flags = acct_flags;
1721
1722         if (account_name != NULL)
1723                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1724         else
1725                 entry->account_name = "";
1726
1727         if (fullname != NULL)
1728                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1729         else
1730                 entry->fullname = "";
1731
1732         if (description != NULL)
1733                 entry->description = talloc_strdup(mem_ctx, description);
1734         else
1735                 entry->description = "";
1736 }
1737
1738 static BOOL user_search_in_progress = False;
1739 struct user_search {
1740         uint16 acct_flags;
1741 };
1742
1743 static BOOL next_entry_users(struct pdb_search *s,
1744                              struct samr_displayentry *entry)
1745 {
1746         struct user_search *state = (struct user_search *)s->private_data;
1747         struct samu *user = NULL;
1748
1749  next:
1750         if ( !(user = samu_new( NULL )) ) {
1751                 DEBUG(0, ("next_entry_users: samu_new() failed!\n"));
1752                 return False;
1753         }
1754
1755         if (!pdb_getsampwent(user)) {
1756                 TALLOC_FREE(user);
1757                 return False;
1758         }
1759
1760         if ((state->acct_flags != 0) &&
1761             ((pdb_get_acct_ctrl(user) & state->acct_flags) == 0)) {
1762                 TALLOC_FREE(user);
1763                 goto next;
1764         }
1765
1766         fill_displayentry(s->mem_ctx, pdb_get_user_rid(user),
1767                           pdb_get_acct_ctrl(user), pdb_get_username(user),
1768                           pdb_get_fullname(user), pdb_get_acct_desc(user),
1769                           entry);
1770
1771         TALLOC_FREE(user);
1772         return True;
1773 }
1774
1775 static void search_end_users(struct pdb_search *search)
1776 {
1777         pdb_endsampwent();
1778         user_search_in_progress = False;
1779 }
1780
1781 static BOOL pdb_default_search_users(struct pdb_methods *methods,
1782                                      struct pdb_search *search,
1783                                      uint32 acct_flags)
1784 {
1785         struct user_search *state;
1786
1787         if (user_search_in_progress) {
1788                 DEBUG(1, ("user search in progress\n"));
1789                 return False;
1790         }
1791
1792         if (!pdb_setsampwent(False, acct_flags)) {
1793                 DEBUG(5, ("Could not start search\n"));
1794                 return False;
1795         }
1796
1797         user_search_in_progress = True;
1798
1799         state = TALLOC_P(search->mem_ctx, struct user_search);
1800         if (state == NULL) {
1801                 DEBUG(0, ("talloc failed\n"));
1802                 return False;
1803         }
1804
1805         state->acct_flags = acct_flags;
1806
1807         search->private_data = state;
1808         search->next_entry = next_entry_users;
1809         search->search_end = search_end_users;
1810         return True;
1811 }
1812
1813 struct group_search {
1814         GROUP_MAP *groups;
1815         size_t num_groups, current_group;
1816 };
1817
1818 static BOOL next_entry_groups(struct pdb_search *s,
1819                               struct samr_displayentry *entry)
1820 {
1821         struct group_search *state = (struct group_search *)s->private_data;
1822         uint32 rid;
1823         GROUP_MAP *map = &state->groups[state->current_group];
1824
1825         if (state->current_group == state->num_groups)
1826                 return False;
1827
1828         sid_peek_rid(&map->sid, &rid);
1829
1830         fill_displayentry(s->mem_ctx, rid, 0, map->nt_name, NULL, map->comment,
1831                           entry);
1832
1833         state->current_group += 1;
1834         return True;
1835 }
1836
1837 static void search_end_groups(struct pdb_search *search)
1838 {
1839         struct group_search *state =
1840                 (struct group_search *)search->private_data;
1841         SAFE_FREE(state->groups);
1842 }
1843
1844 static BOOL pdb_search_grouptype(struct pdb_search *search,
1845                                  const DOM_SID *sid, enum SID_NAME_USE type)
1846 {
1847         struct group_search *state;
1848
1849         state = TALLOC_P(search->mem_ctx, struct group_search);
1850         if (state == NULL) {
1851                 DEBUG(0, ("talloc failed\n"));
1852                 return False;
1853         }
1854
1855         if (!pdb_enum_group_mapping(sid, type, &state->groups, &state->num_groups,
1856                                     True)) {
1857                 DEBUG(0, ("Could not enum groups\n"));
1858                 return False;
1859         }
1860
1861         state->current_group = 0;
1862         search->private_data = state;
1863         search->next_entry = next_entry_groups;
1864         search->search_end = search_end_groups;
1865         return True;
1866 }
1867
1868 static BOOL pdb_default_search_groups(struct pdb_methods *methods,
1869                                       struct pdb_search *search)
1870 {
1871         return pdb_search_grouptype(search, get_global_sam_sid(), SID_NAME_DOM_GRP);
1872 }
1873
1874 static BOOL pdb_default_search_aliases(struct pdb_methods *methods,
1875                                        struct pdb_search *search,
1876                                        const DOM_SID *sid)
1877 {
1878
1879         return pdb_search_grouptype(search, sid, SID_NAME_ALIAS);
1880 }
1881
1882 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
1883                                                      uint32 idx)
1884 {
1885         if (idx < search->num_entries)
1886                 return &search->cache[idx];
1887
1888         if (search->search_ended)
1889                 return NULL;
1890
1891         while (idx >= search->num_entries) {
1892                 struct samr_displayentry entry;
1893
1894                 if (!search->next_entry(search, &entry)) {
1895                         search->search_end(search);
1896                         search->search_ended = True;
1897                         break;
1898                 }
1899
1900                 ADD_TO_LARGE_ARRAY(search->mem_ctx, struct samr_displayentry,
1901                                    entry, &search->cache, &search->num_entries,
1902                                    &search->cache_size);
1903         }
1904
1905         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
1906 }
1907
1908 struct pdb_search *pdb_search_users(uint32 acct_flags)
1909 {
1910         struct pdb_methods *pdb = pdb_get_methods();
1911         struct pdb_search *result;
1912
1913         result = pdb_search_init(PDB_USER_SEARCH);
1914         if (result == NULL) {
1915                 return NULL;
1916         }
1917
1918         if (!pdb->search_users(pdb, result, acct_flags)) {
1919                 talloc_destroy(result->mem_ctx);
1920                 return NULL;
1921         }
1922         return result;
1923 }
1924
1925 struct pdb_search *pdb_search_groups(void)
1926 {
1927         struct pdb_methods *pdb = pdb_get_methods();
1928         struct pdb_search *result;
1929
1930         result = pdb_search_init(PDB_GROUP_SEARCH);
1931         if (result == NULL) {
1932                  return NULL;
1933         }
1934
1935         if (!pdb->search_groups(pdb, result)) {
1936                 talloc_destroy(result->mem_ctx);
1937                 return NULL;
1938         }
1939         return result;
1940 }
1941
1942 struct pdb_search *pdb_search_aliases(const DOM_SID *sid)
1943 {
1944         struct pdb_methods *pdb = pdb_get_methods();
1945         struct pdb_search *result;
1946
1947         if (pdb == NULL) return NULL;
1948
1949         result = pdb_search_init(PDB_ALIAS_SEARCH);
1950         if (result == NULL) return NULL;
1951
1952         if (!pdb->search_aliases(pdb, result, sid)) {
1953                 talloc_destroy(result->mem_ctx);
1954                 return NULL;
1955         }
1956         return result;
1957 }
1958
1959 uint32 pdb_search_entries(struct pdb_search *search,
1960                           uint32 start_idx, uint32 max_entries,
1961                           struct samr_displayentry **result)
1962 {
1963         struct samr_displayentry *end_entry;
1964         uint32 end_idx = start_idx+max_entries-1;
1965
1966         /* The first entry needs to be searched after the last. Otherwise the
1967          * first entry might have moved due to a realloc during the search for
1968          * the last entry. */
1969
1970         end_entry = pdb_search_getentry(search, end_idx);
1971         *result = pdb_search_getentry(search, start_idx);
1972
1973         if (end_entry != NULL)
1974                 return max_entries;
1975
1976         if (start_idx >= search->num_entries)
1977                 return 0;
1978
1979         return search->num_entries - start_idx;
1980 }
1981
1982 void pdb_search_destroy(struct pdb_search *search)
1983 {
1984         if (search == NULL)
1985                 return;
1986
1987         if (!search->search_ended)
1988                 search->search_end(search);
1989
1990         talloc_destroy(search->mem_ctx);
1991 }
1992
1993 /*******************************************************************
1994  Create a pdb_methods structure and initialize it with the default
1995  operations.  In this way a passdb module can simply implement
1996  the functionality it cares about.  However, normally this is done 
1997  in groups of related functions.
1998 *******************************************************************/
1999
2000 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
2001 {
2002         /* allocate memory for the structure as its own talloc CTX */
2003
2004         if ( !(*methods = TALLOC_ZERO_P(NULL, struct pdb_methods) ) ) {
2005                 return NT_STATUS_NO_MEMORY;
2006         }
2007
2008         (*methods)->setsampwent = pdb_default_setsampwent;
2009         (*methods)->endsampwent = pdb_default_endsampwent;
2010         (*methods)->getsampwent = pdb_default_getsampwent;
2011         (*methods)->getsampwnam = pdb_default_getsampwnam;
2012         (*methods)->getsampwsid = pdb_default_getsampwsid;
2013         (*methods)->create_user = pdb_default_create_user;
2014         (*methods)->delete_user = pdb_default_delete_user;
2015         (*methods)->add_sam_account = pdb_default_add_sam_account;
2016         (*methods)->update_sam_account = pdb_default_update_sam_account;
2017         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
2018         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
2019         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
2020
2021         (*methods)->getgrsid = pdb_default_getgrsid;
2022         (*methods)->getgrgid = pdb_default_getgrgid;
2023         (*methods)->getgrnam = pdb_default_getgrnam;
2024         (*methods)->create_dom_group = pdb_default_create_dom_group;
2025         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
2026         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
2027         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
2028         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
2029         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
2030         (*methods)->enum_group_members = pdb_default_enum_group_members;
2031         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
2032         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2033         (*methods)->add_groupmem = pdb_default_add_groupmem;
2034         (*methods)->del_groupmem = pdb_default_del_groupmem;
2035         (*methods)->find_alias = pdb_default_find_alias;
2036         (*methods)->create_alias = pdb_default_create_alias;
2037         (*methods)->delete_alias = pdb_default_delete_alias;
2038         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2039         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2040         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2041         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2042         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2043         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2044         (*methods)->lookup_rids = pdb_default_lookup_rids;
2045         (*methods)->get_account_policy = pdb_default_get_account_policy;
2046         (*methods)->set_account_policy = pdb_default_set_account_policy;
2047         (*methods)->get_seq_num = pdb_default_get_seq_num;
2048         (*methods)->uid_to_rid = pdb_default_uid_to_rid;
2049         (*methods)->gid_to_sid = pdb_default_gid_to_sid;
2050         (*methods)->sid_to_id = pdb_default_sid_to_id;
2051
2052         (*methods)->search_users = pdb_default_search_users;
2053         (*methods)->search_groups = pdb_default_search_groups;
2054         (*methods)->search_aliases = pdb_default_search_aliases;
2055
2056         return NT_STATUS_OK;
2057 }