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