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