r17465: Get rid of add_initial_entry. In the two places it was called in it seemed a
[gd/samba-autobuild/.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 NTSTATUS pdb_getgrsid(GROUP_MAP *map, const DOM_SID *sid)
565 {
566         struct pdb_methods *pdb = pdb_get_methods();
567         return pdb->getgrsid(pdb, map, sid);
568 }
569
570 NTSTATUS pdb_getgrgid(GROUP_MAP *map, gid_t gid)
571 {
572         struct pdb_methods *pdb = pdb_get_methods();
573         return pdb->getgrgid(pdb, map, gid);
574 }
575
576 NTSTATUS pdb_getgrnam(GROUP_MAP *map, const char *name)
577 {
578         struct pdb_methods *pdb = pdb_get_methods();
579         return 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         GROUP_MAP map;
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 = 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         map.gid = grp->gr_gid;
615         map.sid_name_use = SID_NAME_DOM_GRP;
616         sid_compose(&map.sid, get_global_sam_sid(), *rid);
617         fstrcpy(map.nt_name, name);
618         map.comment[0] = '\0';
619         return pdb_add_group_mapping_entry(&map);
620 }
621
622 NTSTATUS pdb_create_dom_group(TALLOC_CTX *mem_ctx, const char *name,
623                               uint32 *rid)
624 {
625         struct pdb_methods *pdb = pdb_get_methods();
626         return pdb->create_dom_group(pdb, mem_ctx, name, rid);
627 }
628
629 static NTSTATUS pdb_default_delete_dom_group(struct pdb_methods *methods,
630                                              TALLOC_CTX *mem_ctx,
631                                              uint32 rid)
632 {
633         DOM_SID group_sid;
634         GROUP_MAP map;
635         NTSTATUS status;
636         struct group *grp;
637         const char *grp_name;
638
639         sid_compose(&group_sid, get_global_sam_sid(), rid);
640
641         if (!get_domain_group_from_sid(&group_sid, &map)) {
642                 DEBUG(10, ("Could not find group for rid %d\n", rid));
643                 return NT_STATUS_NO_SUCH_GROUP;
644         }
645
646         /* We need the group name for the smb_delete_group later on */
647
648         if (map.gid == (gid_t)-1) {
649                 return NT_STATUS_NO_SUCH_GROUP;
650         }
651
652         grp = getgrgid(map.gid);
653         if (grp == NULL) {
654                 return NT_STATUS_NO_SUCH_GROUP;
655         }
656
657         /* Copy the name, no idea what pdb_delete_group_mapping_entry does.. */
658
659         grp_name = talloc_strdup(mem_ctx, grp->gr_name);
660         if (grp_name == NULL) {
661                 return NT_STATUS_NO_MEMORY;
662         }
663
664         status = pdb_delete_group_mapping_entry(group_sid);
665
666         if (!NT_STATUS_IS_OK(status)) {
667                 return status;
668         }
669
670         /* Don't check the result of smb_delete_group */
671         
672         smb_delete_group(grp_name);
673
674         return NT_STATUS_OK;
675 }
676
677 NTSTATUS pdb_delete_dom_group(TALLOC_CTX *mem_ctx, uint32 rid)
678 {
679         struct pdb_methods *pdb = pdb_get_methods();
680         return pdb->delete_dom_group(pdb, mem_ctx, rid);
681 }
682
683 NTSTATUS pdb_add_group_mapping_entry(GROUP_MAP *map)
684 {
685         struct pdb_methods *pdb = pdb_get_methods();
686         return pdb->add_group_mapping_entry(pdb, map);
687 }
688
689 NTSTATUS pdb_update_group_mapping_entry(GROUP_MAP *map)
690 {
691         struct pdb_methods *pdb = pdb_get_methods();
692         return pdb->update_group_mapping_entry(pdb, map);
693 }
694
695 NTSTATUS pdb_delete_group_mapping_entry(DOM_SID sid)
696 {
697         struct pdb_methods *pdb = pdb_get_methods();
698         return pdb->delete_group_mapping_entry(pdb, sid);
699 }
700
701 BOOL pdb_enum_group_mapping(const DOM_SID *sid, enum SID_NAME_USE sid_name_use, GROUP_MAP **pp_rmap,
702                             size_t *p_num_entries, BOOL unix_only)
703 {
704         struct pdb_methods *pdb = pdb_get_methods();
705         return NT_STATUS_IS_OK(pdb-> enum_group_mapping(pdb, sid, sid_name_use,
706                 pp_rmap, p_num_entries, unix_only));
707 }
708
709 NTSTATUS pdb_enum_group_members(TALLOC_CTX *mem_ctx,
710                                 const DOM_SID *sid,
711                                 uint32 **pp_member_rids,
712                                 size_t *p_num_members)
713 {
714         struct pdb_methods *pdb = pdb_get_methods();
715         NTSTATUS result;
716
717         result = pdb->enum_group_members(pdb, mem_ctx, 
718                         sid, pp_member_rids, p_num_members);
719                 
720         /* special check for rid 513 */
721                 
722         if ( !NT_STATUS_IS_OK( result ) ) {
723                 uint32 rid;
724                 
725                 sid_peek_rid( sid, &rid );
726                 
727                 if ( rid == DOMAIN_GROUP_RID_USERS ) {
728                         *p_num_members = 0;
729                         *pp_member_rids = NULL;
730                         
731                         return NT_STATUS_OK;
732                 }
733         }
734         
735         return result;
736 }
737
738 NTSTATUS pdb_enum_group_memberships(TALLOC_CTX *mem_ctx, struct samu *user,
739                                     DOM_SID **pp_sids, gid_t **pp_gids,
740                                     size_t *p_num_groups)
741 {
742         struct pdb_methods *pdb = pdb_get_methods();
743         return pdb->enum_group_memberships(
744                 pdb, mem_ctx, user,
745                 pp_sids, pp_gids, p_num_groups);
746 }
747
748 static NTSTATUS pdb_default_set_unix_primary_group(struct pdb_methods *methods,
749                                                    TALLOC_CTX *mem_ctx,
750                                                    struct samu *sampass)
751 {
752         struct group *grp;
753         gid_t gid;
754
755         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid) ||
756             (grp = getgrgid(gid)) == NULL) {
757                 return NT_STATUS_INVALID_PRIMARY_GROUP;
758         }
759
760         if (smb_set_primary_group(grp->gr_name,
761                                   pdb_get_username(sampass)) != 0) {
762                 return NT_STATUS_ACCESS_DENIED;
763         }
764
765         return NT_STATUS_OK;
766 }
767
768 NTSTATUS pdb_set_unix_primary_group(TALLOC_CTX *mem_ctx, struct samu *user)
769 {
770         struct pdb_methods *pdb = pdb_get_methods();
771         return pdb->set_unix_primary_group(pdb, mem_ctx, user);
772 }
773
774 /*
775  * Helper function to see whether a user is in a group. We can't use
776  * user_in_group_sid here because this creates dependencies only smbd can
777  * fulfil.
778  */
779
780 static BOOL pdb_user_in_group(TALLOC_CTX *mem_ctx, struct samu *account,
781                               const DOM_SID *group_sid)
782 {
783         DOM_SID *sids;
784         gid_t *gids;
785         size_t i, num_groups;
786
787         if (!NT_STATUS_IS_OK(pdb_enum_group_memberships(mem_ctx, account,
788                                                         &sids, &gids,
789                                                         &num_groups))) {
790                 return False;
791         }
792
793         for (i=0; i<num_groups; i++) {
794                 if (sid_equal(group_sid, &sids[i])) {
795                         return True;
796                 }
797         }
798         return False;
799 }
800
801 static NTSTATUS pdb_default_add_groupmem(struct pdb_methods *methods,
802                                          TALLOC_CTX *mem_ctx,
803                                          uint32 group_rid,
804                                          uint32 member_rid)
805 {
806         DOM_SID group_sid, member_sid;
807         struct samu *account = NULL;
808         GROUP_MAP map;
809         struct group *grp;
810         struct passwd *pwd;
811         const char *group_name;
812         uid_t uid;
813
814         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
815         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
816
817         if (!get_domain_group_from_sid(&group_sid, &map) ||
818             (map.gid == (gid_t)-1) ||
819             ((grp = getgrgid(map.gid)) == NULL)) {
820                 return NT_STATUS_NO_SUCH_GROUP;
821         }
822
823         group_name = talloc_strdup(mem_ctx, grp->gr_name);
824         if (group_name == NULL) {
825                 return NT_STATUS_NO_MEMORY;
826         }
827
828         if ( !(account = samu_new( NULL )) ) {
829                 return NT_STATUS_NO_MEMORY;
830         }
831
832         if (!pdb_getsampwsid(account, &member_sid) ||
833             !sid_to_uid(&member_sid, &uid) ||
834             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
835                 return NT_STATUS_NO_SUCH_USER;
836         }
837
838         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
839                 return NT_STATUS_MEMBER_IN_GROUP;
840         }
841
842         /* 
843          * ok, the group exist, the user exist, the user is not in the group,
844          * we can (finally) add it to the group !
845          */
846
847         smb_add_user_group(group_name, pwd->pw_name);
848
849         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
850                 return NT_STATUS_ACCESS_DENIED;
851         }
852
853         return NT_STATUS_OK;
854 }
855
856 NTSTATUS pdb_add_groupmem(TALLOC_CTX *mem_ctx, uint32 group_rid,
857                           uint32 member_rid)
858 {
859         struct pdb_methods *pdb = pdb_get_methods();
860         return pdb->add_groupmem(pdb, mem_ctx, group_rid, member_rid);
861 }
862
863 static NTSTATUS pdb_default_del_groupmem(struct pdb_methods *methods,
864                                          TALLOC_CTX *mem_ctx,
865                                          uint32 group_rid,
866                                          uint32 member_rid)
867 {
868         DOM_SID group_sid, member_sid;
869         struct samu *account = NULL;
870         GROUP_MAP map;
871         struct group *grp;
872         struct passwd *pwd;
873         const char *group_name;
874         uid_t uid;
875
876         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
877         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
878
879         if (!get_domain_group_from_sid(&group_sid, &map) ||
880             (map.gid == (gid_t)-1) ||
881             ((grp = getgrgid(map.gid)) == NULL)) {
882                 return NT_STATUS_NO_SUCH_GROUP;
883         }
884
885         group_name = talloc_strdup(mem_ctx, grp->gr_name);
886         if (group_name == NULL) {
887                 return NT_STATUS_NO_MEMORY;
888         }
889
890         if ( !(account = samu_new( NULL )) ) {
891                 return NT_STATUS_NO_MEMORY;
892         }
893
894         if (!pdb_getsampwsid(account, &member_sid) ||
895             !sid_to_uid(&member_sid, &uid) ||
896             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
897                 return NT_STATUS_NO_SUCH_USER;
898         }
899
900         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
901                 return NT_STATUS_MEMBER_NOT_IN_GROUP;
902         }
903
904         /* 
905          * ok, the group exist, the user exist, the user is in the group,
906          * we can (finally) delete it from the group!
907          */
908
909         smb_delete_user_group(group_name, pwd->pw_name);
910
911         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
912                 return NT_STATUS_ACCESS_DENIED;
913         }
914
915         return NT_STATUS_OK;
916 }
917
918 NTSTATUS pdb_del_groupmem(TALLOC_CTX *mem_ctx, uint32 group_rid,
919                           uint32 member_rid)
920 {
921         struct pdb_methods *pdb = pdb_get_methods();
922         return pdb->del_groupmem(pdb, mem_ctx, group_rid, member_rid);
923 }
924
925 NTSTATUS pdb_create_alias(const char *name, uint32 *rid)
926 {
927         struct pdb_methods *pdb = pdb_get_methods();
928         return pdb->create_alias(pdb, name, rid);
929 }
930
931 BOOL pdb_delete_alias(const DOM_SID *sid)
932 {
933         struct pdb_methods *pdb = pdb_get_methods();
934         return NT_STATUS_IS_OK(pdb->delete_alias(pdb, sid));
935                                                             
936 }
937
938 BOOL pdb_get_aliasinfo(const DOM_SID *sid, struct acct_info *info)
939 {
940         struct pdb_methods *pdb = pdb_get_methods();
941         return NT_STATUS_IS_OK(pdb->get_aliasinfo(pdb, sid, info));
942 }
943
944 BOOL pdb_set_aliasinfo(const DOM_SID *sid, struct acct_info *info)
945 {
946         struct pdb_methods *pdb = pdb_get_methods();
947         return NT_STATUS_IS_OK(pdb->set_aliasinfo(pdb, sid, info));
948 }
949
950 NTSTATUS pdb_add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
951 {
952         struct pdb_methods *pdb = pdb_get_methods();
953         return pdb->add_aliasmem(pdb, alias, member);
954 }
955
956 NTSTATUS pdb_del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
957 {
958         struct pdb_methods *pdb = pdb_get_methods();
959         return pdb->del_aliasmem(pdb, alias, member);
960 }
961
962 NTSTATUS pdb_enum_aliasmem(const DOM_SID *alias,
963                            DOM_SID **pp_members, size_t *p_num_members)
964 {
965         struct pdb_methods *pdb = pdb_get_methods();
966         return pdb->enum_aliasmem(pdb, alias, pp_members, p_num_members);
967 }
968
969 NTSTATUS pdb_enum_alias_memberships(TALLOC_CTX *mem_ctx,
970                                     const DOM_SID *domain_sid,
971                                     const DOM_SID *members, size_t num_members,
972                                     uint32 **pp_alias_rids,
973                                     size_t *p_num_alias_rids)
974 {
975         struct pdb_methods *pdb = pdb_get_methods();
976         return pdb->enum_alias_memberships(pdb, mem_ctx,
977                                                        domain_sid,
978                                                        members, num_members,
979                                                        pp_alias_rids,
980                                                        p_num_alias_rids);
981 }
982
983 NTSTATUS pdb_lookup_rids(const DOM_SID *domain_sid,
984                          int num_rids,
985                          uint32 *rids,
986                          const char **names,
987                          enum SID_NAME_USE *attrs)
988 {
989         struct pdb_methods *pdb = pdb_get_methods();
990         return pdb->lookup_rids(pdb, domain_sid, num_rids, rids, names, attrs);
991 }
992
993 NTSTATUS pdb_lookup_names(const DOM_SID *domain_sid,
994                           int num_names,
995                           const char **names,
996                           uint32 *rids,
997                           enum SID_NAME_USE *attrs)
998 {
999         struct pdb_methods *pdb = pdb_get_methods();
1000         return pdb->lookup_names(pdb, domain_sid, num_names, names, rids, attrs);
1001 }
1002
1003 BOOL pdb_get_account_policy(int policy_index, uint32 *value)
1004 {
1005         struct pdb_methods *pdb = pdb_get_methods();
1006         return NT_STATUS_IS_OK(pdb->get_account_policy(pdb, policy_index, value));
1007 }
1008
1009 BOOL pdb_set_account_policy(int policy_index, uint32 value)
1010 {
1011         struct pdb_methods *pdb = pdb_get_methods();
1012         return NT_STATUS_IS_OK(pdb->set_account_policy(pdb, policy_index, value));
1013 }
1014
1015 BOOL pdb_get_seq_num(time_t *seq_num)
1016 {
1017         struct pdb_methods *pdb = pdb_get_methods();
1018         return NT_STATUS_IS_OK(pdb->get_seq_num(pdb, seq_num));
1019 }
1020
1021 BOOL pdb_uid_to_rid(uid_t uid, uint32 *rid)
1022 {
1023         struct pdb_methods *pdb = pdb_get_methods();
1024         return pdb->uid_to_rid(pdb, uid, rid);
1025 }
1026
1027 BOOL pdb_gid_to_sid(gid_t gid, DOM_SID *sid)
1028 {
1029         struct pdb_methods *pdb = pdb_get_methods();
1030         return pdb->gid_to_sid(pdb, gid, sid);
1031 }
1032
1033 BOOL pdb_sid_to_id(const DOM_SID *sid, union unid_t *id,
1034                    enum SID_NAME_USE *type)
1035 {
1036         struct pdb_methods *pdb = pdb_get_methods();
1037         return pdb->sid_to_id(pdb, sid, id, type);
1038 }
1039
1040 BOOL pdb_rid_algorithm(void)
1041 {
1042         struct pdb_methods *pdb = pdb_get_methods();
1043         return pdb->rid_algorithm(pdb);
1044 }
1045
1046 /********************************************************************
1047  Allocate a new RID from the passdb backend.  Verify that it is free
1048  by calling lookup_global_sam_rid() to verify that the RID is not
1049  in use.  This handles servers that have existing users or groups
1050  with add RIDs (assigned from previous algorithmic mappings)
1051 ********************************************************************/
1052
1053 BOOL pdb_new_rid(uint32 *rid)
1054 {
1055         struct pdb_methods *pdb = pdb_get_methods();
1056         const char *name = NULL;
1057         enum SID_NAME_USE type;
1058         uint32 allocated_rid = 0;
1059         int i;
1060         TALLOC_CTX *ctx;
1061
1062         if (pdb_rid_algorithm()) {
1063                 DEBUG(0, ("Trying to allocate a RID when algorithmic RIDs "
1064                           "are active\n"));
1065                 return False;
1066         }
1067
1068         if (algorithmic_rid_base() != BASE_RID) {
1069                 DEBUG(0, ("'algorithmic rid base' is set but a passdb backend "
1070                           "without algorithmic RIDs is chosen.\n"));
1071                 DEBUGADD(0, ("Please map all used groups using 'net groupmap "
1072                              "add', set the maximum used RID using\n"));
1073                 DEBUGADD(0, ("'net setmaxrid' and remove the parameter\n"));
1074                 return False;
1075         }
1076
1077         if ( (ctx = talloc_init("pdb_new_rid")) == NULL ) {
1078                 DEBUG(0,("pdb_new_rid: Talloc initialization failure\n"));
1079                 return False;
1080         }
1081
1082         /* Attempt to get an unused RID (max tires is 250...yes that it is 
1083            and arbitrary number I pulkled out of my head).   -- jerry */
1084
1085         for ( i=0; allocated_rid==0 && i<250; i++ ) {
1086                 /* get a new RID */
1087
1088                 if ( !pdb->new_rid(pdb, &allocated_rid) ) {
1089                         return False;
1090                 }
1091
1092                 /* validate that the RID is not in use */
1093
1094                 if ( lookup_global_sam_rid( ctx, allocated_rid, &name, &type, NULL ) ) {
1095                         allocated_rid = 0;
1096                 }
1097         }
1098
1099         TALLOC_FREE( ctx );
1100
1101         if ( allocated_rid == 0 ) {
1102                 DEBUG(0,("pdb_new_rid: Failed to find unused RID\n"));
1103                 return False;
1104         }
1105
1106         *rid = allocated_rid;
1107
1108         return True;
1109 }
1110
1111 /***************************************************************
1112   Initialize the static context (at smbd startup etc). 
1113
1114   If uninitialised, context will auto-init on first use.
1115  ***************************************************************/
1116
1117 BOOL initialize_password_db(BOOL reload)
1118 {       
1119         return (pdb_get_methods_reload(reload) != NULL);
1120 }
1121
1122
1123 /***************************************************************************
1124   Default implementations of some functions.
1125  ****************************************************************************/
1126
1127 static NTSTATUS pdb_default_getsampwnam (struct pdb_methods *methods, struct samu *user, const char *sname)
1128 {
1129         return NT_STATUS_NO_SUCH_USER;
1130 }
1131
1132 static NTSTATUS pdb_default_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1133 {
1134         return NT_STATUS_NO_SUCH_USER;
1135 }
1136
1137 static NTSTATUS pdb_default_add_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1138 {
1139         return NT_STATUS_NOT_IMPLEMENTED;
1140 }
1141
1142 static NTSTATUS pdb_default_update_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1143 {
1144         return NT_STATUS_NOT_IMPLEMENTED;
1145 }
1146
1147 static NTSTATUS pdb_default_delete_sam_account (struct pdb_methods *methods, struct samu *pwd)
1148 {
1149         return NT_STATUS_NOT_IMPLEMENTED;
1150 }
1151
1152 static NTSTATUS pdb_default_rename_sam_account (struct pdb_methods *methods, struct samu *pwd, const char *newname)
1153 {
1154         return NT_STATUS_NOT_IMPLEMENTED;
1155 }
1156
1157 static NTSTATUS pdb_default_update_login_attempts (struct pdb_methods *methods, struct samu *newpwd, BOOL success)
1158 {
1159         return NT_STATUS_OK;
1160 }
1161
1162 static NTSTATUS pdb_default_setsampwent(struct pdb_methods *methods, BOOL update, uint32 acb_mask)
1163 {
1164         return NT_STATUS_NOT_IMPLEMENTED;
1165 }
1166
1167 static NTSTATUS pdb_default_getsampwent(struct pdb_methods *methods, struct samu *user)
1168 {
1169         return NT_STATUS_NOT_IMPLEMENTED;
1170 }
1171
1172 static void pdb_default_endsampwent(struct pdb_methods *methods)
1173 {
1174         return; /* NT_STATUS_NOT_IMPLEMENTED; */
1175 }
1176
1177 static NTSTATUS pdb_default_get_account_policy(struct pdb_methods *methods, int policy_index, uint32 *value)
1178 {
1179         return account_policy_get(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1180 }
1181
1182 static NTSTATUS pdb_default_set_account_policy(struct pdb_methods *methods, int policy_index, uint32 value)
1183 {
1184         return account_policy_set(policy_index, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1185 }
1186
1187 static NTSTATUS pdb_default_get_seq_num(struct pdb_methods *methods, time_t *seq_num)
1188 {
1189         *seq_num = time(NULL);
1190         return NT_STATUS_OK;
1191 }
1192
1193 static BOOL pdb_default_uid_to_rid(struct pdb_methods *methods, uid_t uid,
1194                                    uint32 *rid)
1195 {
1196         struct samu *sampw = NULL;
1197         struct passwd *unix_pw;
1198         BOOL ret;
1199         
1200         unix_pw = sys_getpwuid( uid );
1201
1202         if ( !unix_pw ) {
1203                 DEBUG(4,("pdb_default_uid_to_rid: host has no idea of uid "
1204                          "%lu\n", (unsigned long)uid));
1205                 return False;
1206         }
1207         
1208         if ( !(sampw = samu_new( NULL )) ) {
1209                 DEBUG(0,("pdb_default_uid_to_rid: samu_new() failed!\n"));
1210                 return False;
1211         }
1212
1213         become_root();
1214         ret = NT_STATUS_IS_OK(
1215                 methods->getsampwnam(methods, sampw, unix_pw->pw_name ));
1216         unbecome_root();
1217
1218         if (!ret) {
1219                 DEBUG(5, ("pdb_default_uid_to_rid: Did not find user "
1220                           "%s (%d)\n", unix_pw->pw_name, uid));
1221                 TALLOC_FREE(sampw);
1222                 return False;
1223         }
1224
1225         ret = sid_peek_check_rid(get_global_sam_sid(),
1226                                  pdb_get_user_sid(sampw), rid);
1227
1228         if (!ret) {
1229                 DEBUG(1, ("Could not peek rid out of sid %s\n",
1230                           sid_string_static(pdb_get_user_sid(sampw))));
1231         }
1232
1233         TALLOC_FREE(sampw);
1234         return ret;
1235 }
1236
1237 static BOOL pdb_default_gid_to_sid(struct pdb_methods *methods, gid_t gid,
1238                                    DOM_SID *sid)
1239 {
1240         GROUP_MAP map;
1241
1242         if (!NT_STATUS_IS_OK(methods->getgrgid(methods, &map, gid))) {
1243                 return False;
1244         }
1245
1246         sid_copy(sid, &map.sid);
1247         return True;
1248 }
1249
1250 static BOOL pdb_default_sid_to_id(struct pdb_methods *methods,
1251                                   const DOM_SID *sid,
1252                                   union unid_t *id, enum SID_NAME_USE *type)
1253 {
1254         TALLOC_CTX *mem_ctx;
1255         BOOL ret = False;
1256         const char *name;
1257         uint32 rid;
1258
1259         mem_ctx = talloc_new(NULL);
1260
1261         if (mem_ctx == NULL) {
1262                 DEBUG(0, ("talloc_new failed\n"));
1263                 return False;
1264         }
1265
1266         if (sid_peek_check_rid(get_global_sam_sid(), sid, &rid)) {
1267                 /* Here we might have users as well as groups and aliases */
1268                 ret = lookup_global_sam_rid(mem_ctx, rid, &name, type, id);
1269                 goto done;
1270         }
1271
1272         if (sid_peek_check_rid(&global_sid_Builtin, sid, &rid)) {
1273                 /* Here we only have aliases */
1274                 GROUP_MAP map;
1275                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, &map, sid))) {
1276                         DEBUG(10, ("Could not find map for sid %s\n",
1277                                    sid_string_static(sid)));
1278                         goto done;
1279                 }
1280                 if ((map.sid_name_use != SID_NAME_ALIAS) &&
1281                     (map.sid_name_use != SID_NAME_WKN_GRP)) {
1282                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1283                                    "alias\n", sid_string_static(sid),
1284                                    sid_type_lookup(map.sid_name_use)));
1285                         goto done;
1286                 }
1287
1288                 id->gid = map.gid;
1289                 *type = SID_NAME_ALIAS;
1290                 ret = True;
1291                 goto done;
1292         }
1293
1294         DEBUG(5, ("Sid %s is neither ours nor builtin, don't know it\n",
1295                   sid_string_static(sid)));
1296
1297  done:
1298
1299         TALLOC_FREE(mem_ctx);
1300         return ret;
1301 }
1302
1303 static void add_uid_to_array_unique(TALLOC_CTX *mem_ctx,
1304                                     uid_t uid, uid_t **pp_uids, size_t *p_num)
1305 {
1306         size_t i;
1307
1308         for (i=0; i<*p_num; i++) {
1309                 if ((*pp_uids)[i] == uid)
1310                         return;
1311         }
1312         
1313         *pp_uids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_uids, uid_t, *p_num+1);
1314
1315         if (*pp_uids == NULL)
1316                 return;
1317
1318         (*pp_uids)[*p_num] = uid;
1319         *p_num += 1;
1320 }
1321
1322 static BOOL get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, size_t *p_num)
1323 {
1324         struct group *grp;
1325         char **gr;
1326         struct passwd *pwd;
1327         char *winbindd_env;
1328  
1329         *pp_uids = NULL;
1330         *p_num = 0;
1331
1332         /* We only look at our own sam, so don't care about imported stuff */
1333
1334         winbindd_env = getenv(WINBINDD_DONT_ENV);
1335         winbind_off();
1336
1337         if ((grp = getgrgid(gid)) == NULL) {
1338                 /* allow winbindd lookups, but only if they weren't already disabled */
1339                 if ( !(winbindd_env && strequal(winbindd_env, "1")) ) {
1340                         winbind_on();
1341                 }
1342
1343                 return False;
1344         }
1345
1346         /* Primary group members */
1347
1348         setpwent();
1349         while ((pwd = getpwent()) != NULL) {
1350                 if (pwd->pw_gid == gid) {
1351                         add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1352                                                 pp_uids, p_num);
1353                 }
1354         }
1355         endpwent();
1356
1357         /* Secondary group members */
1358
1359         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1360                 struct passwd *pw = getpwnam(*gr);
1361
1362                 if (pw == NULL)
1363                         continue;
1364                 add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num);
1365         }
1366
1367         /* allow winbindd lookups, but only if they weren't already disabled */
1368
1369         if ( !(winbindd_env && strequal(winbindd_env, "1")) ) {
1370                 winbind_on();
1371         }
1372
1373         return True;
1374 }
1375
1376 NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1377                                         TALLOC_CTX *mem_ctx,
1378                                         const DOM_SID *group,
1379                                         uint32 **pp_member_rids,
1380                                         size_t *p_num_members)
1381 {
1382         gid_t gid;
1383         uid_t *uids;
1384         size_t i, num_uids;
1385
1386         *pp_member_rids = NULL;
1387         *p_num_members = 0;
1388
1389         if (!sid_to_gid(group, &gid))
1390                 return NT_STATUS_NO_SUCH_GROUP;
1391
1392         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1393                 return NT_STATUS_NO_SUCH_GROUP;
1394
1395         if (num_uids == 0)
1396                 return NT_STATUS_OK;
1397
1398         *pp_member_rids = TALLOC_ZERO_ARRAY(mem_ctx, uint32, num_uids);
1399
1400         for (i=0; i<num_uids; i++) {
1401                 DOM_SID sid;
1402
1403                 uid_to_sid(&sid, uids[i]);
1404
1405                 if (!sid_check_is_in_our_domain(&sid)) {
1406                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1407                                   "in our domain\n"));
1408                         continue;
1409                 }
1410
1411                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1412                 *p_num_members += 1;
1413         }
1414
1415         return NT_STATUS_OK;
1416 }
1417
1418 NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1419                                             TALLOC_CTX *mem_ctx,
1420                                             struct samu *user,
1421                                             DOM_SID **pp_sids,
1422                                             gid_t **pp_gids,
1423                                             size_t *p_num_groups)
1424 {
1425         size_t i;
1426         gid_t gid;
1427         struct passwd *pw;
1428         const char *username = pdb_get_username(user);
1429         
1430
1431         /* Ignore the primary group SID.  Honor the real Unix primary group.
1432            The primary group SID is only of real use to Windows clients */
1433            
1434         if ( !(pw = getpwnam_alloc(mem_ctx, username)) ) {
1435                 return NT_STATUS_NO_SUCH_USER;
1436         }
1437         
1438         gid = pw->pw_gid;
1439         
1440         TALLOC_FREE( pw );
1441
1442         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1443                 return NT_STATUS_NO_SUCH_USER;
1444         }
1445
1446         if (*p_num_groups == 0) {
1447                 smb_panic("primary group missing");
1448         }
1449
1450         *pp_sids = TALLOC_ARRAY(mem_ctx, DOM_SID, *p_num_groups);
1451
1452         if (*pp_sids == NULL) {
1453                 TALLOC_FREE(*pp_gids);
1454                 return NT_STATUS_NO_MEMORY;
1455         }
1456
1457         for (i=0; i<*p_num_groups; i++) {
1458                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1459         }
1460
1461         return NT_STATUS_OK;
1462 }
1463
1464 /*******************************************************************
1465  Look up a rid in the SAM we're responsible for (i.e. passdb)
1466  ********************************************************************/
1467
1468 static BOOL lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32 rid,
1469                                   const char **name,
1470                                   enum SID_NAME_USE *psid_name_use,
1471                                   union unid_t *unix_id)
1472 {
1473         struct samu *sam_account = NULL;
1474         GROUP_MAP map;
1475         BOOL ret;
1476         DOM_SID sid;
1477
1478         *psid_name_use = SID_NAME_UNKNOWN;
1479         
1480         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1481                  (unsigned int)rid));
1482
1483         sid_copy(&sid, get_global_sam_sid());
1484         sid_append_rid(&sid, rid);
1485         
1486         /* see if the passdb can help us with the name of the user */
1487
1488         if ( !(sam_account = samu_new( NULL )) ) {
1489                 return False;
1490         }
1491
1492         /* BEING ROOT BLLOCK */
1493         become_root();
1494         if (pdb_getsampwsid(sam_account, &sid)) {
1495                 struct passwd *pw;
1496
1497                 unbecome_root();                /* -----> EXIT BECOME_ROOT() */
1498                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1499                 if (!*name) {
1500                         TALLOC_FREE(sam_account);
1501                         return False;
1502                 }
1503
1504                 *psid_name_use = SID_NAME_USER;
1505
1506                 TALLOC_FREE(sam_account);
1507
1508                 if (unix_id == NULL) {
1509                         return True;
1510                 }
1511
1512                 pw = Get_Pwnam(*name);
1513                 if (pw == NULL) {
1514                         return False;
1515                 }
1516                 unix_id->uid = pw->pw_uid;
1517                 return True;
1518         }
1519         TALLOC_FREE(sam_account);
1520         
1521         ret = NT_STATUS_IS_OK(pdb_getgrsid(&map, &sid));
1522         unbecome_root();
1523         /* END BECOME_ROOT BLOCK */
1524   
1525         /* do not resolve SIDs to a name unless there is a valid 
1526            gid associated with it */
1527                    
1528         if ( ret && (map.gid != (gid_t)-1) ) {
1529                 *name = talloc_strdup(mem_ctx, map.nt_name);
1530                 *psid_name_use = map.sid_name_use;
1531
1532                 if ( unix_id ) {
1533                         unix_id->gid = map.gid;
1534                 }
1535
1536                 return True;
1537         }
1538         
1539         /* Windows will always map RID 513 to something.  On a non-domain 
1540            controller, this gets mapped to SERVER\None. */
1541
1542         if ( unix_id ) {
1543                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1544                 return False;
1545         }
1546         
1547         if ( rid == DOMAIN_GROUP_RID_USERS ) {
1548                 *name = talloc_strdup(mem_ctx, "None" );
1549                 *psid_name_use = SID_NAME_DOM_GRP;
1550                 
1551                 return True;
1552         }
1553
1554         return False;
1555 }
1556
1557 NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1558                                  const DOM_SID *domain_sid,
1559                                  int num_rids,
1560                                  uint32 *rids,
1561                                  const char **names,
1562                                  enum SID_NAME_USE *attrs)
1563 {
1564         int i;
1565         NTSTATUS result;
1566         BOOL have_mapped = False;
1567         BOOL have_unmapped = False;
1568
1569         if (sid_check_is_builtin(domain_sid)) {
1570
1571                 for (i=0; i<num_rids; i++) {
1572                         const char *name;
1573
1574                         if (lookup_builtin_rid(names, rids[i], &name)) {
1575                                 attrs[i] = SID_NAME_ALIAS;
1576                                 names[i] = name;
1577                                 DEBUG(5,("lookup_rids: %s:%d\n",
1578                                          names[i], attrs[i]));
1579                                 have_mapped = True;
1580                         } else {
1581                                 have_unmapped = True;
1582                                 attrs[i] = SID_NAME_UNKNOWN;
1583                         }
1584                 }
1585                 goto done;
1586         }
1587
1588         /* Should not happen, but better check once too many */
1589         if (!sid_check_is_domain(domain_sid)) {
1590                 return NT_STATUS_INVALID_HANDLE;
1591         }
1592
1593         for (i = 0; i < num_rids; i++) {
1594                 const char *name;
1595
1596                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1597                                           NULL)) {
1598                         if (name == NULL) {
1599                                 return NT_STATUS_NO_MEMORY;
1600                         }
1601                         names[i] = name;
1602                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1603                         have_mapped = True;
1604                 } else {
1605                         have_unmapped = True;
1606                         attrs[i] = SID_NAME_UNKNOWN;
1607                 }
1608         }
1609
1610  done:
1611
1612         result = NT_STATUS_NONE_MAPPED;
1613
1614         if (have_mapped)
1615                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1616
1617         return result;
1618 }
1619
1620 NTSTATUS pdb_default_lookup_names(struct pdb_methods *methods,
1621                                   const DOM_SID *domain_sid,
1622                                   int num_names,
1623                                   const char **names,
1624                                   uint32 *rids,
1625                                   enum SID_NAME_USE *attrs)
1626 {
1627         int i;
1628         NTSTATUS result;
1629         BOOL have_mapped = False;
1630         BOOL have_unmapped = False;
1631
1632         if (sid_check_is_builtin(domain_sid)) {
1633
1634                 for (i=0; i<num_names; i++) {
1635                         uint32 rid;
1636
1637                         if (lookup_builtin_name(names[i], &rid)) {
1638                                 attrs[i] = SID_NAME_ALIAS;
1639                                 rids[i] = rid;
1640                                 DEBUG(5,("lookup_rids: %s:%d\n",
1641                                          names[i], attrs[i]));
1642                                 have_mapped = True;
1643                         } else {
1644                                 have_unmapped = True;
1645                                 attrs[i] = SID_NAME_UNKNOWN;
1646                         }
1647                 }
1648                 goto done;
1649         }
1650
1651         /* Should not happen, but better check once too many */
1652         if (!sid_check_is_domain(domain_sid)) {
1653                 return NT_STATUS_INVALID_HANDLE;
1654         }
1655
1656         for (i = 0; i < num_names; i++) {
1657                 if (lookup_global_sam_name(names[i], 0, &rids[i], &attrs[i])) {
1658                         DEBUG(5,("lookup_names: %s-> %d:%d\n", names[i],
1659                                  rids[i], attrs[i]));
1660                         have_mapped = True;
1661                 } else {
1662                         have_unmapped = True;
1663                         attrs[i] = SID_NAME_UNKNOWN;
1664                 }
1665         }
1666
1667  done:
1668
1669         result = NT_STATUS_NONE_MAPPED;
1670
1671         if (have_mapped)
1672                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1673
1674         return result;
1675 }
1676
1677 static struct pdb_search *pdb_search_init(enum pdb_search_type type)
1678 {
1679         TALLOC_CTX *mem_ctx;
1680         struct pdb_search *result;
1681
1682         mem_ctx = talloc_init("pdb_search");
1683         if (mem_ctx == NULL) {
1684                 DEBUG(0, ("talloc_init failed\n"));
1685                 return NULL;
1686         }
1687
1688         result = TALLOC_P(mem_ctx, struct pdb_search);
1689         if (result == NULL) {
1690                 DEBUG(0, ("talloc failed\n"));
1691                 return NULL;
1692         }
1693
1694         result->mem_ctx = mem_ctx;
1695         result->type = type;
1696         result->cache = NULL;
1697         result->num_entries = 0;
1698         result->cache_size = 0;
1699         result->search_ended = False;
1700
1701         /* Segfault appropriately if not initialized */
1702         result->next_entry = NULL;
1703         result->search_end = NULL;
1704
1705         return result;
1706 }
1707
1708 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32 rid,
1709                               uint16 acct_flags,
1710                               const char *account_name,
1711                               const char *fullname,
1712                               const char *description,
1713                               struct samr_displayentry *entry)
1714 {
1715         entry->rid = rid;
1716         entry->acct_flags = acct_flags;
1717
1718         if (account_name != NULL)
1719                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1720         else
1721                 entry->account_name = "";
1722
1723         if (fullname != NULL)
1724                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1725         else
1726                 entry->fullname = "";
1727
1728         if (description != NULL)
1729                 entry->description = talloc_strdup(mem_ctx, description);
1730         else
1731                 entry->description = "";
1732 }
1733
1734 static BOOL user_search_in_progress = False;
1735 struct user_search {
1736         uint16 acct_flags;
1737 };
1738
1739 static BOOL next_entry_users(struct pdb_search *s,
1740                              struct samr_displayentry *entry)
1741 {
1742         struct user_search *state = (struct user_search *)s->private_data;
1743         struct samu *user = NULL;
1744
1745  next:
1746         if ( !(user = samu_new( NULL )) ) {
1747                 DEBUG(0, ("next_entry_users: samu_new() failed!\n"));
1748                 return False;
1749         }
1750
1751         if (!pdb_getsampwent(user)) {
1752                 TALLOC_FREE(user);
1753                 return False;
1754         }
1755
1756         if ((state->acct_flags != 0) &&
1757             ((pdb_get_acct_ctrl(user) & state->acct_flags) == 0)) {
1758                 TALLOC_FREE(user);
1759                 goto next;
1760         }
1761
1762         fill_displayentry(s->mem_ctx, pdb_get_user_rid(user),
1763                           pdb_get_acct_ctrl(user), pdb_get_username(user),
1764                           pdb_get_fullname(user), pdb_get_acct_desc(user),
1765                           entry);
1766
1767         TALLOC_FREE(user);
1768         return True;
1769 }
1770
1771 static void search_end_users(struct pdb_search *search)
1772 {
1773         pdb_endsampwent();
1774         user_search_in_progress = False;
1775 }
1776
1777 static BOOL pdb_default_search_users(struct pdb_methods *methods,
1778                                      struct pdb_search *search,
1779                                      uint32 acct_flags)
1780 {
1781         struct user_search *state;
1782
1783         if (user_search_in_progress) {
1784                 DEBUG(1, ("user search in progress\n"));
1785                 return False;
1786         }
1787
1788         if (!pdb_setsampwent(False, acct_flags)) {
1789                 DEBUG(5, ("Could not start search\n"));
1790                 return False;
1791         }
1792
1793         user_search_in_progress = True;
1794
1795         state = TALLOC_P(search->mem_ctx, struct user_search);
1796         if (state == NULL) {
1797                 DEBUG(0, ("talloc failed\n"));
1798                 return False;
1799         }
1800
1801         state->acct_flags = acct_flags;
1802
1803         search->private_data = state;
1804         search->next_entry = next_entry_users;
1805         search->search_end = search_end_users;
1806         return True;
1807 }
1808
1809 struct group_search {
1810         GROUP_MAP *groups;
1811         size_t num_groups, current_group;
1812 };
1813
1814 static BOOL next_entry_groups(struct pdb_search *s,
1815                               struct samr_displayentry *entry)
1816 {
1817         struct group_search *state = (struct group_search *)s->private_data;
1818         uint32 rid;
1819         GROUP_MAP *map = &state->groups[state->current_group];
1820
1821         if (state->current_group == state->num_groups)
1822                 return False;
1823
1824         sid_peek_rid(&map->sid, &rid);
1825
1826         fill_displayentry(s->mem_ctx, rid, 0, map->nt_name, NULL, map->comment,
1827                           entry);
1828
1829         state->current_group += 1;
1830         return True;
1831 }
1832
1833 static void search_end_groups(struct pdb_search *search)
1834 {
1835         struct group_search *state =
1836                 (struct group_search *)search->private_data;
1837         SAFE_FREE(state->groups);
1838 }
1839
1840 static BOOL pdb_search_grouptype(struct pdb_search *search,
1841                                  const DOM_SID *sid, enum SID_NAME_USE type)
1842 {
1843         struct group_search *state;
1844
1845         state = TALLOC_P(search->mem_ctx, struct group_search);
1846         if (state == NULL) {
1847                 DEBUG(0, ("talloc failed\n"));
1848                 return False;
1849         }
1850
1851         if (!pdb_enum_group_mapping(sid, type, &state->groups, &state->num_groups,
1852                                     True)) {
1853                 DEBUG(0, ("Could not enum groups\n"));
1854                 return False;
1855         }
1856
1857         state->current_group = 0;
1858         search->private_data = state;
1859         search->next_entry = next_entry_groups;
1860         search->search_end = search_end_groups;
1861         return True;
1862 }
1863
1864 static BOOL pdb_default_search_groups(struct pdb_methods *methods,
1865                                       struct pdb_search *search)
1866 {
1867         return pdb_search_grouptype(search, get_global_sam_sid(), SID_NAME_DOM_GRP);
1868 }
1869
1870 static BOOL pdb_default_search_aliases(struct pdb_methods *methods,
1871                                        struct pdb_search *search,
1872                                        const DOM_SID *sid)
1873 {
1874
1875         return pdb_search_grouptype(search, sid, SID_NAME_ALIAS);
1876 }
1877
1878 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
1879                                                      uint32 idx)
1880 {
1881         if (idx < search->num_entries)
1882                 return &search->cache[idx];
1883
1884         if (search->search_ended)
1885                 return NULL;
1886
1887         while (idx >= search->num_entries) {
1888                 struct samr_displayentry entry;
1889
1890                 if (!search->next_entry(search, &entry)) {
1891                         search->search_end(search);
1892                         search->search_ended = True;
1893                         break;
1894                 }
1895
1896                 ADD_TO_LARGE_ARRAY(search->mem_ctx, struct samr_displayentry,
1897                                    entry, &search->cache, &search->num_entries,
1898                                    &search->cache_size);
1899         }
1900
1901         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
1902 }
1903
1904 struct pdb_search *pdb_search_users(uint32 acct_flags)
1905 {
1906         struct pdb_methods *pdb = pdb_get_methods();
1907         struct pdb_search *result;
1908
1909         result = pdb_search_init(PDB_USER_SEARCH);
1910         if (result == NULL) {
1911                 return NULL;
1912         }
1913
1914         if (!pdb->search_users(pdb, result, acct_flags)) {
1915                 talloc_destroy(result->mem_ctx);
1916                 return NULL;
1917         }
1918         return result;
1919 }
1920
1921 struct pdb_search *pdb_search_groups(void)
1922 {
1923         struct pdb_methods *pdb = pdb_get_methods();
1924         struct pdb_search *result;
1925
1926         result = pdb_search_init(PDB_GROUP_SEARCH);
1927         if (result == NULL) {
1928                  return NULL;
1929         }
1930
1931         if (!pdb->search_groups(pdb, result)) {
1932                 talloc_destroy(result->mem_ctx);
1933                 return NULL;
1934         }
1935         return result;
1936 }
1937
1938 struct pdb_search *pdb_search_aliases(const DOM_SID *sid)
1939 {
1940         struct pdb_methods *pdb = pdb_get_methods();
1941         struct pdb_search *result;
1942
1943         if (pdb == NULL) return NULL;
1944
1945         result = pdb_search_init(PDB_ALIAS_SEARCH);
1946         if (result == NULL) return NULL;
1947
1948         if (!pdb->search_aliases(pdb, result, sid)) {
1949                 talloc_destroy(result->mem_ctx);
1950                 return NULL;
1951         }
1952         return result;
1953 }
1954
1955 uint32 pdb_search_entries(struct pdb_search *search,
1956                           uint32 start_idx, uint32 max_entries,
1957                           struct samr_displayentry **result)
1958 {
1959         struct samr_displayentry *end_entry;
1960         uint32 end_idx = start_idx+max_entries-1;
1961
1962         /* The first entry needs to be searched after the last. Otherwise the
1963          * first entry might have moved due to a realloc during the search for
1964          * the last entry. */
1965
1966         end_entry = pdb_search_getentry(search, end_idx);
1967         *result = pdb_search_getentry(search, start_idx);
1968
1969         if (end_entry != NULL)
1970                 return max_entries;
1971
1972         if (start_idx >= search->num_entries)
1973                 return 0;
1974
1975         return search->num_entries - start_idx;
1976 }
1977
1978 void pdb_search_destroy(struct pdb_search *search)
1979 {
1980         if (search == NULL)
1981                 return;
1982
1983         if (!search->search_ended)
1984                 search->search_end(search);
1985
1986         talloc_destroy(search->mem_ctx);
1987 }
1988
1989 /*******************************************************************
1990  Create a pdb_methods structure and initialize it with the default
1991  operations.  In this way a passdb module can simply implement
1992  the functionality it cares about.  However, normally this is done 
1993  in groups of related functions.
1994 *******************************************************************/
1995
1996 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
1997 {
1998         /* allocate memory for the structure as its own talloc CTX */
1999
2000         if ( !(*methods = TALLOC_ZERO_P(NULL, struct pdb_methods) ) ) {
2001                 return NT_STATUS_NO_MEMORY;
2002         }
2003
2004         (*methods)->setsampwent = pdb_default_setsampwent;
2005         (*methods)->endsampwent = pdb_default_endsampwent;
2006         (*methods)->getsampwent = pdb_default_getsampwent;
2007         (*methods)->getsampwnam = pdb_default_getsampwnam;
2008         (*methods)->getsampwsid = pdb_default_getsampwsid;
2009         (*methods)->create_user = pdb_default_create_user;
2010         (*methods)->delete_user = pdb_default_delete_user;
2011         (*methods)->add_sam_account = pdb_default_add_sam_account;
2012         (*methods)->update_sam_account = pdb_default_update_sam_account;
2013         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
2014         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
2015         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
2016
2017         (*methods)->getgrsid = pdb_default_getgrsid;
2018         (*methods)->getgrgid = pdb_default_getgrgid;
2019         (*methods)->getgrnam = pdb_default_getgrnam;
2020         (*methods)->create_dom_group = pdb_default_create_dom_group;
2021         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
2022         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
2023         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
2024         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
2025         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
2026         (*methods)->enum_group_members = pdb_default_enum_group_members;
2027         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
2028         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2029         (*methods)->add_groupmem = pdb_default_add_groupmem;
2030         (*methods)->del_groupmem = pdb_default_del_groupmem;
2031         (*methods)->create_alias = pdb_default_create_alias;
2032         (*methods)->delete_alias = pdb_default_delete_alias;
2033         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2034         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2035         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2036         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2037         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2038         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2039         (*methods)->lookup_rids = pdb_default_lookup_rids;
2040         (*methods)->get_account_policy = pdb_default_get_account_policy;
2041         (*methods)->set_account_policy = pdb_default_set_account_policy;
2042         (*methods)->get_seq_num = pdb_default_get_seq_num;
2043         (*methods)->uid_to_rid = pdb_default_uid_to_rid;
2044         (*methods)->gid_to_sid = pdb_default_gid_to_sid;
2045         (*methods)->sid_to_id = pdb_default_sid_to_id;
2046
2047         (*methods)->search_users = pdb_default_search_users;
2048         (*methods)->search_groups = pdb_default_search_groups;
2049         (*methods)->search_aliases = pdb_default_search_aliases;
2050
2051         return NT_STATUS_OK;
2052 }