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