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