s3-passdb Use supplied pdb_methods in default passdb search handlers
[amitay/samba.git] / source3 / passdb / pdb_interface.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Bartlett                        2002
5    Copyright (C) Jelmer Vernooij                        2002
6    Copyright (C) Simo Sorce                             2003
7    Copyright (C) Volker Lendecke                        2006
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #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(methods, 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 = methods->add_sam_account(methods, 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         memcache_flush(NULL, PDB_GETPWSID_CACHE);
583
584         status = methods->delete_sam_account(methods, sam_acct);
585         if (!NT_STATUS_IS_OK(status)) {
586                 return status;
587         }
588
589         /*
590          * Now delete the unix side ....
591          * note: we don't check if the delete really happened as the script is
592          * not necessary present and maybe the sysadmin doesn't want to delete
593          * the unix side
594          */
595
596         /* always lower case the username before handing it off to 
597            external scripts */
598
599         fstrcpy( username, pdb_get_username(sam_acct) );
600         strlower_m( username );
601
602         smb_delete_user( username );
603
604         return status;
605 }
606
607 NTSTATUS pdb_delete_user(TALLOC_CTX *mem_ctx, struct samu *sam_acct)
608 {
609         struct pdb_methods *pdb = pdb_get_methods();
610         uid_t uid = -1;
611
612         /* sanity check to make sure we don't delete root */
613
614         if ( !sid_to_uid( pdb_get_user_sid(sam_acct), &uid ) ) {
615                 return NT_STATUS_NO_SUCH_USER;
616         }
617
618         if ( uid == 0 ) {
619                 return NT_STATUS_ACCESS_DENIED;
620         }
621
622         return pdb->delete_user(pdb, mem_ctx, sam_acct);
623 }
624
625 NTSTATUS pdb_add_sam_account(struct samu *sam_acct) 
626 {
627         struct pdb_methods *pdb = pdb_get_methods();
628         return pdb->add_sam_account(pdb, sam_acct);
629 }
630
631 NTSTATUS pdb_update_sam_account(struct samu *sam_acct) 
632 {
633         struct pdb_methods *pdb = pdb_get_methods();
634
635         memcache_flush(NULL, PDB_GETPWSID_CACHE);
636
637         return pdb->update_sam_account(pdb, sam_acct);
638 }
639
640 NTSTATUS pdb_delete_sam_account(struct samu *sam_acct) 
641 {
642         struct pdb_methods *pdb = pdb_get_methods();
643
644         memcache_flush(NULL, PDB_GETPWSID_CACHE);
645
646         return pdb->delete_sam_account(pdb, sam_acct);
647 }
648
649 NTSTATUS pdb_rename_sam_account(struct samu *oldname, const char *newname)
650 {
651         struct pdb_methods *pdb = pdb_get_methods();
652         uid_t uid;
653         NTSTATUS status;
654
655         memcache_flush(NULL, PDB_GETPWSID_CACHE);
656
657         /* sanity check to make sure we don't rename root */
658
659         if ( !sid_to_uid( pdb_get_user_sid(oldname), &uid ) ) {
660                 return NT_STATUS_NO_SUCH_USER;
661         }
662
663         if ( uid == 0 ) {
664                 return NT_STATUS_ACCESS_DENIED;
665         }
666
667         status = pdb->rename_sam_account(pdb, oldname, newname);
668
669         /* always flush the cache here just to be safe */
670         flush_pwnam_cache();
671
672         return status;
673 }
674
675 NTSTATUS pdb_update_login_attempts(struct samu *sam_acct, bool success)
676 {
677         struct pdb_methods *pdb = pdb_get_methods();
678         return pdb->update_login_attempts(pdb, sam_acct, success);
679 }
680
681 bool pdb_getgrsid(GROUP_MAP *map, struct dom_sid sid)
682 {
683         struct pdb_methods *pdb = pdb_get_methods();
684         return NT_STATUS_IS_OK(pdb->getgrsid(pdb, map, sid));
685 }
686
687 bool pdb_getgrgid(GROUP_MAP *map, gid_t gid)
688 {
689         struct pdb_methods *pdb = pdb_get_methods();
690         return NT_STATUS_IS_OK(pdb->getgrgid(pdb, map, gid));
691 }
692
693 bool pdb_getgrnam(GROUP_MAP *map, const char *name)
694 {
695         struct pdb_methods *pdb = pdb_get_methods();
696         return NT_STATUS_IS_OK(pdb->getgrnam(pdb, map, name));
697 }
698
699 static NTSTATUS pdb_default_create_dom_group(struct pdb_methods *methods,
700                                              TALLOC_CTX *mem_ctx,
701                                              const char *name,
702                                              uint32_t *rid)
703 {
704         struct dom_sid group_sid;
705         struct group *grp;
706         fstring tmp;
707
708         grp = getgrnam(name);
709
710         if (grp == NULL) {
711                 gid_t gid;
712
713                 if (smb_create_group(name, &gid) != 0) {
714                         return NT_STATUS_ACCESS_DENIED;
715                 }
716
717                 grp = getgrgid(gid);
718         }
719
720         if (grp == NULL) {
721                 return NT_STATUS_ACCESS_DENIED;
722         }
723
724         if (pdb_capabilities() & PDB_CAP_STORE_RIDS) {
725                 if (!pdb_new_rid(rid)) {
726                         return NT_STATUS_ACCESS_DENIED;
727                 }
728         } else {
729                 *rid = algorithmic_pdb_gid_to_group_rid( grp->gr_gid );
730         }
731
732         sid_compose(&group_sid, get_global_sam_sid(), *rid);
733
734         return add_initial_entry(grp->gr_gid, sid_to_fstring(tmp, &group_sid),
735                                  SID_NAME_DOM_GRP, name, NULL);
736 }
737
738 NTSTATUS pdb_create_dom_group(TALLOC_CTX *mem_ctx, const char *name,
739                               uint32_t *rid)
740 {
741         struct pdb_methods *pdb = pdb_get_methods();
742         return pdb->create_dom_group(pdb, mem_ctx, name, rid);
743 }
744
745 static NTSTATUS pdb_default_delete_dom_group(struct pdb_methods *methods,
746                                              TALLOC_CTX *mem_ctx,
747                                              uint32_t rid)
748 {
749         struct dom_sid group_sid;
750         GROUP_MAP map;
751         NTSTATUS status;
752         struct group *grp;
753         const char *grp_name;
754
755         /* coverity */
756         map.gid = (gid_t) -1;
757
758         sid_compose(&group_sid, get_global_sam_sid(), rid);
759
760         if (!get_domain_group_from_sid(group_sid, &map)) {
761                 DEBUG(10, ("Could not find group for rid %d\n", rid));
762                 return NT_STATUS_NO_SUCH_GROUP;
763         }
764
765         /* We need the group name for the smb_delete_group later on */
766
767         if (map.gid == (gid_t)-1) {
768                 return NT_STATUS_NO_SUCH_GROUP;
769         }
770
771         grp = getgrgid(map.gid);
772         if (grp == NULL) {
773                 return NT_STATUS_NO_SUCH_GROUP;
774         }
775
776         /* Copy the name, no idea what pdb_delete_group_mapping_entry does.. */
777
778         grp_name = talloc_strdup(mem_ctx, grp->gr_name);
779         if (grp_name == NULL) {
780                 return NT_STATUS_NO_MEMORY;
781         }
782
783         status = pdb_delete_group_mapping_entry(group_sid);
784
785         if (!NT_STATUS_IS_OK(status)) {
786                 return status;
787         }
788
789         /* Don't check the result of smb_delete_group */
790
791         smb_delete_group(grp_name);
792
793         return NT_STATUS_OK;
794 }
795
796 NTSTATUS pdb_delete_dom_group(TALLOC_CTX *mem_ctx, uint32_t rid)
797 {
798         struct pdb_methods *pdb = pdb_get_methods();
799         return pdb->delete_dom_group(pdb, mem_ctx, rid);
800 }
801
802 NTSTATUS pdb_add_group_mapping_entry(GROUP_MAP *map)
803 {
804         struct pdb_methods *pdb = pdb_get_methods();
805         return pdb->add_group_mapping_entry(pdb, map);
806 }
807
808 NTSTATUS pdb_update_group_mapping_entry(GROUP_MAP *map)
809 {
810         struct pdb_methods *pdb = pdb_get_methods();
811         return pdb->update_group_mapping_entry(pdb, map);
812 }
813
814 NTSTATUS pdb_delete_group_mapping_entry(struct dom_sid sid)
815 {
816         struct pdb_methods *pdb = pdb_get_methods();
817         return pdb->delete_group_mapping_entry(pdb, sid);
818 }
819
820 bool pdb_enum_group_mapping(const struct dom_sid *sid, enum lsa_SidType sid_name_use, GROUP_MAP **pp_rmap,
821                             size_t *p_num_entries, bool unix_only)
822 {
823         struct pdb_methods *pdb = pdb_get_methods();
824         return NT_STATUS_IS_OK(pdb-> enum_group_mapping(pdb, sid, sid_name_use,
825                 pp_rmap, p_num_entries, unix_only));
826 }
827
828 NTSTATUS pdb_enum_group_members(TALLOC_CTX *mem_ctx,
829                                 const struct dom_sid *sid,
830                                 uint32_t **pp_member_rids,
831                                 size_t *p_num_members)
832 {
833         struct pdb_methods *pdb = pdb_get_methods();
834         NTSTATUS result;
835
836         result = pdb->enum_group_members(pdb, mem_ctx, 
837                         sid, pp_member_rids, p_num_members);
838
839         /* special check for rid 513 */
840
841         if ( !NT_STATUS_IS_OK( result ) ) {
842                 uint32_t rid;
843
844                 sid_peek_rid( sid, &rid );
845
846                 if ( rid == DOMAIN_RID_USERS ) {
847                         *p_num_members = 0;
848                         *pp_member_rids = NULL;
849
850                         return NT_STATUS_OK;
851                 }
852         }
853
854         return result;
855 }
856
857 NTSTATUS pdb_enum_group_memberships(TALLOC_CTX *mem_ctx, struct samu *user,
858                                     struct dom_sid **pp_sids, gid_t **pp_gids,
859                                     uint32_t *p_num_groups)
860 {
861         struct pdb_methods *pdb = pdb_get_methods();
862         return pdb->enum_group_memberships(
863                 pdb, mem_ctx, user,
864                 pp_sids, pp_gids, p_num_groups);
865 }
866
867 static NTSTATUS pdb_default_set_unix_primary_group(struct pdb_methods *methods,
868                                                    TALLOC_CTX *mem_ctx,
869                                                    struct samu *sampass)
870 {
871         struct group *grp;
872         gid_t gid;
873
874         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid) ||
875             (grp = getgrgid(gid)) == NULL) {
876                 return NT_STATUS_INVALID_PRIMARY_GROUP;
877         }
878
879         if (smb_set_primary_group(grp->gr_name,
880                                   pdb_get_username(sampass)) != 0) {
881                 return NT_STATUS_ACCESS_DENIED;
882         }
883
884         return NT_STATUS_OK;
885 }
886
887 NTSTATUS pdb_set_unix_primary_group(TALLOC_CTX *mem_ctx, struct samu *user)
888 {
889         struct pdb_methods *pdb = pdb_get_methods();
890         return pdb->set_unix_primary_group(pdb, mem_ctx, user);
891 }
892
893 /*
894  * Helper function to see whether a user is in a group. We can't use
895  * user_in_group_sid here because this creates dependencies only smbd can
896  * fulfil.
897  */
898
899 static bool pdb_user_in_group(TALLOC_CTX *mem_ctx, struct samu *account,
900                               const struct dom_sid *group_sid)
901 {
902         struct dom_sid *sids;
903         gid_t *gids;
904         uint32_t i, num_groups;
905
906         if (!NT_STATUS_IS_OK(pdb_enum_group_memberships(mem_ctx, account,
907                                                         &sids, &gids,
908                                                         &num_groups))) {
909                 return False;
910         }
911
912         for (i=0; i<num_groups; i++) {
913                 if (dom_sid_equal(group_sid, &sids[i])) {
914                         return True;
915                 }
916         }
917         return False;
918 }
919
920 static NTSTATUS pdb_default_add_groupmem(struct pdb_methods *methods,
921                                          TALLOC_CTX *mem_ctx,
922                                          uint32_t group_rid,
923                                          uint32_t member_rid)
924 {
925         struct dom_sid group_sid, member_sid;
926         struct samu *account = NULL;
927         GROUP_MAP map;
928         struct group *grp;
929         struct passwd *pwd;
930         const char *group_name;
931         uid_t uid;
932
933         /* coverity */
934         map.gid = (gid_t) -1;
935
936         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
937         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
938
939         if (!get_domain_group_from_sid(group_sid, &map) ||
940             (map.gid == (gid_t)-1) ||
941             ((grp = getgrgid(map.gid)) == NULL)) {
942                 return NT_STATUS_NO_SUCH_GROUP;
943         }
944
945         group_name = talloc_strdup(mem_ctx, grp->gr_name);
946         if (group_name == NULL) {
947                 return NT_STATUS_NO_MEMORY;
948         }
949
950         if ( !(account = samu_new( NULL )) ) {
951                 return NT_STATUS_NO_MEMORY;
952         }
953
954         if (!pdb_getsampwsid(account, &member_sid) ||
955             !sid_to_uid(&member_sid, &uid) ||
956             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
957                 return NT_STATUS_NO_SUCH_USER;
958         }
959
960         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
961                 return NT_STATUS_MEMBER_IN_GROUP;
962         }
963
964         /* 
965          * ok, the group exist, the user exist, the user is not in the group,
966          * we can (finally) add it to the group !
967          */
968
969         smb_add_user_group(group_name, pwd->pw_name);
970
971         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
972                 return NT_STATUS_ACCESS_DENIED;
973         }
974
975         return NT_STATUS_OK;
976 }
977
978 NTSTATUS pdb_add_groupmem(TALLOC_CTX *mem_ctx, uint32_t group_rid,
979                           uint32_t member_rid)
980 {
981         struct pdb_methods *pdb = pdb_get_methods();
982         return pdb->add_groupmem(pdb, mem_ctx, group_rid, member_rid);
983 }
984
985 static NTSTATUS pdb_default_del_groupmem(struct pdb_methods *methods,
986                                          TALLOC_CTX *mem_ctx,
987                                          uint32_t group_rid,
988                                          uint32_t member_rid)
989 {
990         struct dom_sid group_sid, member_sid;
991         struct samu *account = NULL;
992         GROUP_MAP map;
993         struct group *grp;
994         struct passwd *pwd;
995         const char *group_name;
996         uid_t uid;
997
998         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
999         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
1000
1001         if (!get_domain_group_from_sid(group_sid, &map) ||
1002             (map.gid == (gid_t)-1) ||
1003             ((grp = getgrgid(map.gid)) == NULL)) {
1004                 return NT_STATUS_NO_SUCH_GROUP;
1005         }
1006
1007         group_name = talloc_strdup(mem_ctx, grp->gr_name);
1008         if (group_name == NULL) {
1009                 return NT_STATUS_NO_MEMORY;
1010         }
1011
1012         if ( !(account = samu_new( NULL )) ) {
1013                 return NT_STATUS_NO_MEMORY;
1014         }
1015
1016         if (!pdb_getsampwsid(account, &member_sid) ||
1017             !sid_to_uid(&member_sid, &uid) ||
1018             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
1019                 return NT_STATUS_NO_SUCH_USER;
1020         }
1021
1022         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
1023                 return NT_STATUS_MEMBER_NOT_IN_GROUP;
1024         }
1025
1026         /* 
1027          * ok, the group exist, the user exist, the user is in the group,
1028          * we can (finally) delete it from the group!
1029          */
1030
1031         smb_delete_user_group(group_name, pwd->pw_name);
1032
1033         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
1034                 return NT_STATUS_ACCESS_DENIED;
1035         }
1036
1037         return NT_STATUS_OK;
1038 }
1039
1040 NTSTATUS pdb_del_groupmem(TALLOC_CTX *mem_ctx, uint32_t group_rid,
1041                           uint32_t member_rid)
1042 {
1043         struct pdb_methods *pdb = pdb_get_methods();
1044         return pdb->del_groupmem(pdb, mem_ctx, group_rid, member_rid);
1045 }
1046
1047 NTSTATUS pdb_create_alias(const char *name, uint32_t *rid)
1048 {
1049         struct pdb_methods *pdb = pdb_get_methods();
1050         return pdb->create_alias(pdb, name, rid);
1051 }
1052
1053 NTSTATUS pdb_delete_alias(const struct dom_sid *sid)
1054 {
1055         struct pdb_methods *pdb = pdb_get_methods();
1056         return pdb->delete_alias(pdb, sid);
1057 }
1058
1059 NTSTATUS pdb_get_aliasinfo(const struct dom_sid *sid, struct acct_info *info)
1060 {
1061         struct pdb_methods *pdb = pdb_get_methods();
1062         return pdb->get_aliasinfo(pdb, sid, info);
1063 }
1064
1065 NTSTATUS pdb_set_aliasinfo(const struct dom_sid *sid, struct acct_info *info)
1066 {
1067         struct pdb_methods *pdb = pdb_get_methods();
1068         return pdb->set_aliasinfo(pdb, sid, info);
1069 }
1070
1071 NTSTATUS pdb_add_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
1072 {
1073         struct pdb_methods *pdb = pdb_get_methods();
1074         return pdb->add_aliasmem(pdb, alias, member);
1075 }
1076
1077 NTSTATUS pdb_del_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
1078 {
1079         struct pdb_methods *pdb = pdb_get_methods();
1080         return pdb->del_aliasmem(pdb, alias, member);
1081 }
1082
1083 NTSTATUS pdb_enum_aliasmem(const struct dom_sid *alias, TALLOC_CTX *mem_ctx,
1084                            struct dom_sid **pp_members, size_t *p_num_members)
1085 {
1086         struct pdb_methods *pdb = pdb_get_methods();
1087         return pdb->enum_aliasmem(pdb, alias, mem_ctx, pp_members,
1088                                   p_num_members);
1089 }
1090
1091 NTSTATUS pdb_enum_alias_memberships(TALLOC_CTX *mem_ctx,
1092                                     const struct dom_sid *domain_sid,
1093                                     const struct dom_sid *members, size_t num_members,
1094                                     uint32_t **pp_alias_rids,
1095                                     size_t *p_num_alias_rids)
1096 {
1097         struct pdb_methods *pdb = pdb_get_methods();
1098         return pdb->enum_alias_memberships(pdb, mem_ctx,
1099                                                        domain_sid,
1100                                                        members, num_members,
1101                                                        pp_alias_rids,
1102                                                        p_num_alias_rids);
1103 }
1104
1105 NTSTATUS pdb_lookup_rids(const struct dom_sid *domain_sid,
1106                          int num_rids,
1107                          uint32_t *rids,
1108                          const char **names,
1109                          enum lsa_SidType *attrs)
1110 {
1111         struct pdb_methods *pdb = pdb_get_methods();
1112         return pdb->lookup_rids(pdb, domain_sid, num_rids, rids, names, attrs);
1113 }
1114
1115 /* 
1116  * NOTE: pdb_lookup_names is currently (2007-01-12) not used anywhere 
1117  *       in the samba code.
1118  *       Unlike _lsa_lookup_sids and _samr_lookup_rids, which eventually 
1119  *       also ask pdb_lookup_rids, thus looking up a bunch of rids at a time, 
1120  *       the pdb_ calls _lsa_lookup_names and _samr_lookup_names come
1121  *       down to are pdb_getsampwnam and pdb_getgrnam instead of
1122  *       pdb_lookup_names.
1123  *       But in principle, it the call belongs to the API and might get
1124  *       used in this context some day. 
1125  */
1126 #if 0
1127 NTSTATUS pdb_lookup_names(const struct dom_sid *domain_sid,
1128                           int num_names,
1129                           const char **names,
1130                           uint32_t *rids,
1131                           enum lsa_SidType *attrs)
1132 {
1133         struct pdb_methods *pdb = pdb_get_methods();
1134         return pdb->lookup_names(pdb, domain_sid, num_names, names, rids, attrs);
1135 }
1136 #endif
1137
1138 bool pdb_get_account_policy(enum pdb_policy_type type, uint32_t *value)
1139 {
1140         struct pdb_methods *pdb = pdb_get_methods();
1141         NTSTATUS status;
1142
1143         become_root();
1144         status = pdb->get_account_policy(pdb, type, value);
1145         unbecome_root();
1146
1147         return NT_STATUS_IS_OK(status); 
1148 }
1149
1150 bool pdb_set_account_policy(enum pdb_policy_type type, uint32_t value)
1151 {
1152         struct pdb_methods *pdb = pdb_get_methods();
1153         NTSTATUS status;
1154
1155         become_root();
1156         status = pdb->set_account_policy(pdb, type, value);
1157         unbecome_root();
1158
1159         return NT_STATUS_IS_OK(status);
1160 }
1161
1162 bool pdb_get_seq_num(time_t *seq_num)
1163 {
1164         struct pdb_methods *pdb = pdb_get_methods();
1165         return NT_STATUS_IS_OK(pdb->get_seq_num(pdb, seq_num));
1166 }
1167
1168 bool pdb_uid_to_sid(uid_t uid, struct dom_sid *sid)
1169 {
1170         struct pdb_methods *pdb = pdb_get_methods();
1171         return pdb->uid_to_sid(pdb, uid, sid);
1172 }
1173
1174 bool pdb_gid_to_sid(gid_t gid, struct dom_sid *sid)
1175 {
1176         struct pdb_methods *pdb = pdb_get_methods();
1177         return pdb->gid_to_sid(pdb, gid, sid);
1178 }
1179
1180 bool pdb_sid_to_id(const struct dom_sid *sid, union unid_t *id,
1181                    enum lsa_SidType *type)
1182 {
1183         struct pdb_methods *pdb = pdb_get_methods();
1184         return pdb->sid_to_id(pdb, sid, id, type);
1185 }
1186
1187 uint32_t pdb_capabilities(void)
1188 {
1189         struct pdb_methods *pdb = pdb_get_methods();
1190         return pdb->capabilities(pdb);
1191 }
1192
1193 /********************************************************************
1194  Allocate a new RID from the passdb backend.  Verify that it is free
1195  by calling lookup_global_sam_rid() to verify that the RID is not
1196  in use.  This handles servers that have existing users or groups
1197  with add RIDs (assigned from previous algorithmic mappings)
1198 ********************************************************************/
1199
1200 bool pdb_new_rid(uint32_t *rid)
1201 {
1202         struct pdb_methods *pdb = pdb_get_methods();
1203         const char *name = NULL;
1204         enum lsa_SidType type;
1205         uint32_t allocated_rid = 0;
1206         int i;
1207         TALLOC_CTX *ctx;
1208
1209         if ((pdb_capabilities() & PDB_CAP_STORE_RIDS) == 0) {
1210                 DEBUG(0, ("Trying to allocate a RID when algorithmic RIDs "
1211                           "are active\n"));
1212                 return False;
1213         }
1214
1215         if (algorithmic_rid_base() != BASE_RID) {
1216                 DEBUG(0, ("'algorithmic rid base' is set but a passdb backend "
1217                           "without algorithmic RIDs is chosen.\n"));
1218                 DEBUGADD(0, ("Please map all used groups using 'net groupmap "
1219                              "add', set the maximum used RID\n"));
1220                 DEBUGADD(0, ("and remove the parameter\n"));
1221                 return False;
1222         }
1223
1224         if ( (ctx = talloc_init("pdb_new_rid")) == NULL ) {
1225                 DEBUG(0,("pdb_new_rid: Talloc initialization failure\n"));
1226                 return False;
1227         }
1228
1229         /* Attempt to get an unused RID (max tires is 250...yes that it is 
1230            and arbitrary number I pulkled out of my head).   -- jerry */
1231
1232         for ( i=0; allocated_rid==0 && i<250; i++ ) {
1233                 /* get a new RID */
1234
1235                 if ( !pdb->new_rid(pdb, &allocated_rid) ) {
1236                         return False;
1237                 }
1238
1239                 /* validate that the RID is not in use */
1240
1241                 if ( lookup_global_sam_rid( ctx, allocated_rid, &name, &type, NULL ) ) {
1242                         allocated_rid = 0;
1243                 }
1244         }
1245
1246         TALLOC_FREE( ctx );
1247
1248         if ( allocated_rid == 0 ) {
1249                 DEBUG(0,("pdb_new_rid: Failed to find unused RID\n"));
1250                 return False;
1251         }
1252
1253         *rid = allocated_rid;
1254
1255         return True;
1256 }
1257
1258 /***************************************************************
1259   Initialize the static context (at smbd startup etc). 
1260
1261   If uninitialised, context will auto-init on first use.
1262  ***************************************************************/
1263
1264 bool initialize_password_db(bool reload, struct event_context *event_ctx)
1265 {
1266         pdb_event_ctx = event_ctx;
1267         return (pdb_get_methods_reload(reload) != NULL);
1268 }
1269
1270
1271 /***************************************************************************
1272   Default implementations of some functions.
1273  ****************************************************************************/
1274
1275 static NTSTATUS pdb_default_getsampwnam (struct pdb_methods *methods, struct samu *user, const char *sname)
1276 {
1277         return NT_STATUS_NO_SUCH_USER;
1278 }
1279
1280 static NTSTATUS pdb_default_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1281 {
1282         return NT_STATUS_NO_SUCH_USER;
1283 }
1284
1285 static NTSTATUS pdb_default_add_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1286 {
1287         return NT_STATUS_NOT_IMPLEMENTED;
1288 }
1289
1290 static NTSTATUS pdb_default_update_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1291 {
1292         return NT_STATUS_NOT_IMPLEMENTED;
1293 }
1294
1295 static NTSTATUS pdb_default_delete_sam_account (struct pdb_methods *methods, struct samu *pwd)
1296 {
1297         return NT_STATUS_NOT_IMPLEMENTED;
1298 }
1299
1300 static NTSTATUS pdb_default_rename_sam_account (struct pdb_methods *methods, struct samu *pwd, const char *newname)
1301 {
1302         return NT_STATUS_NOT_IMPLEMENTED;
1303 }
1304
1305 static NTSTATUS pdb_default_update_login_attempts (struct pdb_methods *methods, struct samu *newpwd, bool success)
1306 {
1307         /* Only the pdb_nds backend implements this, by
1308          * default just return ok. */
1309         return NT_STATUS_OK;
1310 }
1311
1312 static NTSTATUS pdb_default_get_account_policy(struct pdb_methods *methods, enum pdb_policy_type type, uint32_t *value)
1313 {
1314         return account_policy_get(type, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1315 }
1316
1317 static NTSTATUS pdb_default_set_account_policy(struct pdb_methods *methods, enum pdb_policy_type type, uint32_t value)
1318 {
1319         return account_policy_set(type, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1320 }
1321
1322 static NTSTATUS pdb_default_get_seq_num(struct pdb_methods *methods, time_t *seq_num)
1323 {
1324         *seq_num = time(NULL);
1325         return NT_STATUS_OK;
1326 }
1327
1328 static bool pdb_default_uid_to_sid(struct pdb_methods *methods, uid_t uid,
1329                                    struct dom_sid *sid)
1330 {
1331         struct samu *sampw = NULL;
1332         struct passwd *unix_pw;
1333         bool ret;
1334
1335         unix_pw = sys_getpwuid( uid );
1336
1337         if ( !unix_pw ) {
1338                 DEBUG(4,("pdb_default_uid_to_sid: host has no idea of uid "
1339                          "%lu\n", (unsigned long)uid));
1340                 return False;
1341         }
1342
1343         if ( !(sampw = samu_new( NULL )) ) {
1344                 DEBUG(0,("pdb_default_uid_to_sid: samu_new() failed!\n"));
1345                 return False;
1346         }
1347
1348         become_root();
1349         ret = NT_STATUS_IS_OK(
1350                 methods->getsampwnam(methods, sampw, unix_pw->pw_name ));
1351         unbecome_root();
1352
1353         if (!ret) {
1354                 DEBUG(5, ("pdb_default_uid_to_sid: Did not find user "
1355                           "%s (%u)\n", unix_pw->pw_name, (unsigned int)uid));
1356                 TALLOC_FREE(sampw);
1357                 return False;
1358         }
1359
1360         sid_copy(sid, pdb_get_user_sid(sampw));
1361
1362         TALLOC_FREE(sampw);
1363
1364         return True;
1365 }
1366
1367 static bool pdb_default_gid_to_sid(struct pdb_methods *methods, gid_t gid,
1368                                    struct dom_sid *sid)
1369 {
1370         GROUP_MAP map;
1371
1372         if (!NT_STATUS_IS_OK(methods->getgrgid(methods, &map, gid))) {
1373                 return False;
1374         }
1375
1376         sid_copy(sid, &map.sid);
1377         return True;
1378 }
1379
1380 static bool pdb_default_sid_to_id(struct pdb_methods *methods,
1381                                   const struct dom_sid *sid,
1382                                   union unid_t *id, enum lsa_SidType *type)
1383 {
1384         TALLOC_CTX *mem_ctx;
1385         bool ret = False;
1386         const char *name;
1387         uint32_t rid;
1388
1389         mem_ctx = talloc_new(NULL);
1390
1391         if (mem_ctx == NULL) {
1392                 DEBUG(0, ("talloc_new failed\n"));
1393                 return False;
1394         }
1395
1396         if (sid_peek_check_rid(get_global_sam_sid(), sid, &rid)) {
1397                 /* Here we might have users as well as groups and aliases */
1398                 ret = lookup_global_sam_rid(mem_ctx, rid, &name, type, id);
1399                 goto done;
1400         }
1401
1402         /* check for "Unix User" */
1403
1404         if ( sid_peek_check_rid(&global_sid_Unix_Users, sid, &rid) ) {
1405                 id->uid = rid;
1406                 *type = SID_NAME_USER;
1407                 ret = True;             
1408                 goto done;              
1409         }
1410
1411         /* check for "Unix Group" */
1412
1413         if ( sid_peek_check_rid(&global_sid_Unix_Groups, sid, &rid) ) {
1414                 id->gid = rid;
1415                 *type = SID_NAME_ALIAS;
1416                 ret = True;             
1417                 goto done;              
1418         }
1419
1420         /* BUILTIN */
1421
1422         if (sid_check_is_in_builtin(sid) ||
1423             sid_check_is_in_wellknown_domain(sid)) {
1424                 /* Here we only have aliases */
1425                 GROUP_MAP map;
1426                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, &map, *sid))) {
1427                         DEBUG(10, ("Could not find map for sid %s\n",
1428                                    sid_string_dbg(sid)));
1429                         goto done;
1430                 }
1431                 if ((map.sid_name_use != SID_NAME_ALIAS) &&
1432                     (map.sid_name_use != SID_NAME_WKN_GRP)) {
1433                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1434                                    "alias\n", sid_string_dbg(sid),
1435                                    sid_type_lookup(map.sid_name_use)));
1436                         goto done;
1437                 }
1438
1439                 id->gid = map.gid;
1440                 *type = SID_NAME_ALIAS;
1441                 ret = True;
1442                 goto done;
1443         }
1444
1445         DEBUG(5, ("Sid %s is neither ours, a Unix SID, nor builtin\n",
1446                   sid_string_dbg(sid)));
1447
1448  done:
1449
1450         TALLOC_FREE(mem_ctx);
1451         return ret;
1452 }
1453
1454 static bool get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, uint32_t *p_num)
1455 {
1456         struct group *grp;
1457         char **gr;
1458         struct passwd *pwd;
1459         bool winbind_env;
1460         bool ret = False;
1461  
1462         *pp_uids = NULL;
1463         *p_num = 0;
1464
1465         /* We only look at our own sam, so don't care about imported stuff */
1466         winbind_env = winbind_env_set();
1467         (void)winbind_off();
1468
1469         if ((grp = getgrgid(gid)) == NULL) {
1470                 /* allow winbindd lookups, but only if they weren't already disabled */
1471                 goto done;
1472         }
1473
1474         /* Primary group members */
1475         setpwent();
1476         while ((pwd = getpwent()) != NULL) {
1477                 if (pwd->pw_gid == gid) {
1478                         if (!add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1479                                                 pp_uids, p_num)) {
1480                                 goto done;
1481                         }
1482                 }
1483         }
1484         endpwent();
1485
1486         /* Secondary group members */
1487         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1488                 struct passwd *pw = getpwnam(*gr);
1489
1490                 if (pw == NULL)
1491                         continue;
1492                 if (!add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num)) {
1493                         goto done;
1494                 }
1495         }
1496
1497         ret = True;
1498
1499   done:
1500
1501         /* allow winbindd lookups, but only if they weren't already disabled */
1502         if (!winbind_env) {
1503                 (void)winbind_on();
1504         }
1505
1506         return ret;
1507 }
1508
1509 static NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1510                                                TALLOC_CTX *mem_ctx,
1511                                                const struct dom_sid *group,
1512                                                uint32_t **pp_member_rids,
1513                                                size_t *p_num_members)
1514 {
1515         gid_t gid;
1516         uid_t *uids;
1517         uint32_t i, num_uids;
1518
1519         *pp_member_rids = NULL;
1520         *p_num_members = 0;
1521
1522         if (!sid_to_gid(group, &gid))
1523                 return NT_STATUS_NO_SUCH_GROUP;
1524
1525         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1526                 return NT_STATUS_NO_SUCH_GROUP;
1527
1528         if (num_uids == 0)
1529                 return NT_STATUS_OK;
1530
1531         *pp_member_rids = talloc_zero_array(mem_ctx, uint32_t, num_uids);
1532
1533         for (i=0; i<num_uids; i++) {
1534                 struct dom_sid sid;
1535
1536                 uid_to_sid(&sid, uids[i]);
1537
1538                 if (!sid_check_is_in_our_domain(&sid)) {
1539                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1540                                   "in our domain\n"));
1541                         continue;
1542                 }
1543
1544                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1545                 *p_num_members += 1;
1546         }
1547
1548         return NT_STATUS_OK;
1549 }
1550
1551 static NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1552                                                    TALLOC_CTX *mem_ctx,
1553                                                    struct samu *user,
1554                                                    struct dom_sid **pp_sids,
1555                                                    gid_t **pp_gids,
1556                                                    uint32_t *p_num_groups)
1557 {
1558         size_t i;
1559         gid_t gid;
1560         struct passwd *pw;
1561         const char *username = pdb_get_username(user);
1562
1563
1564         /* Ignore the primary group SID.  Honor the real Unix primary group.
1565            The primary group SID is only of real use to Windows clients */
1566
1567         if ( !(pw = Get_Pwnam_alloc(mem_ctx, username)) ) {
1568                 return NT_STATUS_NO_SUCH_USER;
1569         }
1570
1571         gid = pw->pw_gid;
1572
1573         TALLOC_FREE( pw );
1574
1575         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1576                 return NT_STATUS_NO_SUCH_USER;
1577         }
1578
1579         if (*p_num_groups == 0) {
1580                 smb_panic("primary group missing");
1581         }
1582
1583         *pp_sids = talloc_array(mem_ctx, struct dom_sid, *p_num_groups);
1584
1585         if (*pp_sids == NULL) {
1586                 TALLOC_FREE(*pp_gids);
1587                 return NT_STATUS_NO_MEMORY;
1588         }
1589
1590         for (i=0; i<*p_num_groups; i++) {
1591                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1592         }
1593
1594         return NT_STATUS_OK;
1595 }
1596
1597 /*******************************************************************
1598  Look up a rid in the SAM we're responsible for (i.e. passdb)
1599  ********************************************************************/
1600
1601 static bool lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32_t rid,
1602                                   const char **name,
1603                                   enum lsa_SidType *psid_name_use,
1604                                   union unid_t *unix_id)
1605 {
1606         struct samu *sam_account = NULL;
1607         GROUP_MAP map;
1608         bool ret;
1609         struct dom_sid sid;
1610
1611         *psid_name_use = SID_NAME_UNKNOWN;
1612
1613         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1614                  (unsigned int)rid));
1615
1616         sid_compose(&sid, get_global_sam_sid(), rid);
1617
1618         /* see if the passdb can help us with the name of the user */
1619
1620         if ( !(sam_account = samu_new( NULL )) ) {
1621                 return False;
1622         }
1623
1624         /* BEING ROOT BLOCK */
1625         become_root();
1626         if (pdb_getsampwsid(sam_account, &sid)) {
1627                 struct passwd *pw;
1628
1629                 unbecome_root();                /* -----> EXIT BECOME_ROOT() */
1630                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1631                 if (!*name) {
1632                         TALLOC_FREE(sam_account);
1633                         return False;
1634                 }
1635
1636                 *psid_name_use = SID_NAME_USER;
1637
1638                 TALLOC_FREE(sam_account);
1639
1640                 if (unix_id == NULL) {
1641                         return True;
1642                 }
1643
1644                 pw = Get_Pwnam_alloc(talloc_tos(), *name);
1645                 if (pw == NULL) {
1646                         return False;
1647                 }
1648                 unix_id->uid = pw->pw_uid;
1649                 TALLOC_FREE(pw);
1650                 return True;
1651         }
1652         TALLOC_FREE(sam_account);
1653
1654         ret = pdb_getgrsid(&map, sid);
1655         unbecome_root();
1656         /* END BECOME_ROOT BLOCK */
1657
1658         /* do not resolve SIDs to a name unless there is a valid 
1659            gid associated with it */
1660
1661         if ( ret && (map.gid != (gid_t)-1) ) {
1662                 *name = talloc_strdup(mem_ctx, map.nt_name);
1663                 *psid_name_use = map.sid_name_use;
1664
1665                 if ( unix_id ) {
1666                         unix_id->gid = map.gid;
1667                 }
1668
1669                 return True;
1670         }
1671
1672         /* Windows will always map RID 513 to something.  On a non-domain 
1673            controller, this gets mapped to SERVER\None. */
1674
1675         if ( unix_id ) {
1676                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1677                 return False;
1678         }
1679
1680         if ( rid == DOMAIN_RID_USERS ) {
1681                 *name = talloc_strdup(mem_ctx, "None" );
1682                 *psid_name_use = SID_NAME_DOM_GRP;
1683
1684                 return True;
1685         }
1686
1687         return False;
1688 }
1689
1690 static NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1691                                         const struct dom_sid *domain_sid,
1692                                         int num_rids,
1693                                         uint32_t *rids,
1694                                         const char **names,
1695                                         enum lsa_SidType *attrs)
1696 {
1697         int i;
1698         NTSTATUS result;
1699         bool have_mapped = False;
1700         bool have_unmapped = False;
1701
1702         if (sid_check_is_builtin(domain_sid)) {
1703
1704                 for (i=0; i<num_rids; i++) {
1705                         const char *name;
1706
1707                         if (lookup_builtin_rid(names, rids[i], &name)) {
1708                                 attrs[i] = SID_NAME_ALIAS;
1709                                 names[i] = name;
1710                                 DEBUG(5,("lookup_rids: %s:%d\n",
1711                                          names[i], attrs[i]));
1712                                 have_mapped = True;
1713                         } else {
1714                                 have_unmapped = True;
1715                                 attrs[i] = SID_NAME_UNKNOWN;
1716                         }
1717                 }
1718                 goto done;
1719         }
1720
1721         /* Should not happen, but better check once too many */
1722         if (!sid_check_is_domain(domain_sid)) {
1723                 return NT_STATUS_INVALID_HANDLE;
1724         }
1725
1726         for (i = 0; i < num_rids; i++) {
1727                 const char *name;
1728
1729                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1730                                           NULL)) {
1731                         if (name == NULL) {
1732                                 return NT_STATUS_NO_MEMORY;
1733                         }
1734                         names[i] = name;
1735                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1736                         have_mapped = True;
1737                 } else {
1738                         have_unmapped = True;
1739                         attrs[i] = SID_NAME_UNKNOWN;
1740                 }
1741         }
1742
1743  done:
1744
1745         result = NT_STATUS_NONE_MAPPED;
1746
1747         if (have_mapped)
1748                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1749
1750         return result;
1751 }
1752
1753 #if 0
1754 static NTSTATUS pdb_default_lookup_names(struct pdb_methods *methods,
1755                                          const struct dom_sid *domain_sid,
1756                                          int num_names,
1757                                          const char **names,
1758                                          uint32_t *rids,
1759                                          enum lsa_SidType *attrs)
1760 {
1761         int i;
1762         NTSTATUS result;
1763         bool have_mapped = False;
1764         bool have_unmapped = False;
1765
1766         if (sid_check_is_builtin(domain_sid)) {
1767
1768                 for (i=0; i<num_names; i++) {
1769                         uint32_t rid;
1770
1771                         if (lookup_builtin_name(names[i], &rid)) {
1772                                 attrs[i] = SID_NAME_ALIAS;
1773                                 rids[i] = rid;
1774                                 DEBUG(5,("lookup_rids: %s:%d\n",
1775                                          names[i], attrs[i]));
1776                                 have_mapped = True;
1777                         } else {
1778                                 have_unmapped = True;
1779                                 attrs[i] = SID_NAME_UNKNOWN;
1780                         }
1781                 }
1782                 goto done;
1783         }
1784
1785         /* Should not happen, but better check once too many */
1786         if (!sid_check_is_domain(domain_sid)) {
1787                 return NT_STATUS_INVALID_HANDLE;
1788         }
1789
1790         for (i = 0; i < num_names; i++) {
1791                 if (lookup_global_sam_name(names[i], 0, &rids[i], &attrs[i])) {
1792                         DEBUG(5,("lookup_names: %s-> %d:%d\n", names[i],
1793                                  rids[i], attrs[i]));
1794                         have_mapped = True;
1795                 } else {
1796                         have_unmapped = True;
1797                         attrs[i] = SID_NAME_UNKNOWN;
1798                 }
1799         }
1800
1801  done:
1802
1803         result = NT_STATUS_NONE_MAPPED;
1804
1805         if (have_mapped)
1806                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1807
1808         return result;
1809 }
1810 #endif
1811
1812 static int pdb_search_destructor(struct pdb_search *search)
1813 {
1814         if ((!search->search_ended) && (search->search_end != NULL)) {
1815                 search->search_end(search);
1816         }
1817         return 0;
1818 }
1819
1820 struct pdb_search *pdb_search_init(TALLOC_CTX *mem_ctx,
1821                                    enum pdb_search_type type)
1822 {
1823         struct pdb_search *result;
1824
1825         result = talloc(mem_ctx, struct pdb_search);
1826         if (result == NULL) {
1827                 DEBUG(0, ("talloc failed\n"));
1828                 return NULL;
1829         }
1830
1831         result->type = type;
1832         result->cache = NULL;
1833         result->num_entries = 0;
1834         result->cache_size = 0;
1835         result->search_ended = False;
1836         result->search_end = NULL;
1837
1838         /* Segfault appropriately if not initialized */
1839         result->next_entry = NULL;
1840         result->search_end = NULL;
1841
1842         talloc_set_destructor(result, pdb_search_destructor);
1843
1844         return result;
1845 }
1846
1847 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32_t rid,
1848                               uint16_t acct_flags,
1849                               const char *account_name,
1850                               const char *fullname,
1851                               const char *description,
1852                               struct samr_displayentry *entry)
1853 {
1854         entry->rid = rid;
1855         entry->acct_flags = acct_flags;
1856
1857         if (account_name != NULL)
1858                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1859         else
1860                 entry->account_name = "";
1861
1862         if (fullname != NULL)
1863                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1864         else
1865                 entry->fullname = "";
1866
1867         if (description != NULL)
1868                 entry->description = talloc_strdup(mem_ctx, description);
1869         else
1870                 entry->description = "";
1871 }
1872
1873 struct group_search {
1874         GROUP_MAP *groups;
1875         size_t num_groups, current_group;
1876 };
1877
1878 static bool next_entry_groups(struct pdb_search *s,
1879                               struct samr_displayentry *entry)
1880 {
1881         struct group_search *state = (struct group_search *)s->private_data;
1882         uint32_t rid;
1883         GROUP_MAP *map = &state->groups[state->current_group];
1884
1885         if (state->current_group == state->num_groups)
1886                 return False;
1887
1888         sid_peek_rid(&map->sid, &rid);
1889
1890         fill_displayentry(s, rid, 0, map->nt_name, NULL, map->comment, entry);
1891
1892         state->current_group += 1;
1893         return True;
1894 }
1895
1896 static void search_end_groups(struct pdb_search *search)
1897 {
1898         struct group_search *state =
1899                 (struct group_search *)search->private_data;
1900         SAFE_FREE(state->groups);
1901 }
1902
1903 static bool pdb_search_grouptype(struct pdb_methods *methods,
1904                                  struct pdb_search *search,
1905                                  const struct dom_sid *sid, enum lsa_SidType type)
1906 {
1907         struct group_search *state;
1908
1909         state = talloc(search, struct group_search);
1910         if (state == NULL) {
1911                 DEBUG(0, ("talloc failed\n"));
1912                 return False;
1913         }
1914
1915         if (!NT_STATUS_IS_OK(methods->enum_group_mapping(methods, sid, type, 
1916                                                          &state->groups, &state->num_groups,
1917                                                          True))) {
1918                 DEBUG(0, ("Could not enum groups\n"));
1919                 return False;
1920         }
1921
1922         state->current_group = 0;
1923         search->private_data = state;
1924         search->next_entry = next_entry_groups;
1925         search->search_end = search_end_groups;
1926         return True;
1927 }
1928
1929 static bool pdb_default_search_groups(struct pdb_methods *methods,
1930                                       struct pdb_search *search)
1931 {
1932         return pdb_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
1933 }
1934
1935 static bool pdb_default_search_aliases(struct pdb_methods *methods,
1936                                        struct pdb_search *search,
1937                                        const struct dom_sid *sid)
1938 {
1939
1940         return pdb_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
1941 }
1942
1943 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
1944                                                      uint32_t idx)
1945 {
1946         if (idx < search->num_entries)
1947                 return &search->cache[idx];
1948
1949         if (search->search_ended)
1950                 return NULL;
1951
1952         while (idx >= search->num_entries) {
1953                 struct samr_displayentry entry;
1954
1955                 if (!search->next_entry(search, &entry)) {
1956                         search->search_end(search);
1957                         search->search_ended = True;
1958                         break;
1959                 }
1960
1961                 ADD_TO_LARGE_ARRAY(search, struct samr_displayentry,
1962                                    entry, &search->cache, &search->num_entries,
1963                                    &search->cache_size);
1964         }
1965
1966         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
1967 }
1968
1969 struct pdb_search *pdb_search_users(TALLOC_CTX *mem_ctx, uint32_t acct_flags)
1970 {
1971         struct pdb_methods *pdb = pdb_get_methods();
1972         struct pdb_search *result;
1973
1974         result = pdb_search_init(mem_ctx, PDB_USER_SEARCH);
1975         if (result == NULL) {
1976                 return NULL;
1977         }
1978
1979         if (!pdb->search_users(pdb, result, acct_flags)) {
1980                 TALLOC_FREE(result);
1981                 return NULL;
1982         }
1983         return result;
1984 }
1985
1986 struct pdb_search *pdb_search_groups(TALLOC_CTX *mem_ctx)
1987 {
1988         struct pdb_methods *pdb = pdb_get_methods();
1989         struct pdb_search *result;
1990
1991         result = pdb_search_init(mem_ctx, PDB_GROUP_SEARCH);
1992         if (result == NULL) {
1993                  return NULL;
1994         }
1995
1996         if (!pdb->search_groups(pdb, result)) {
1997                 TALLOC_FREE(result);
1998                 return NULL;
1999         }
2000         return result;
2001 }
2002
2003 struct pdb_search *pdb_search_aliases(TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
2004 {
2005         struct pdb_methods *pdb = pdb_get_methods();
2006         struct pdb_search *result;
2007
2008         if (pdb == NULL) return NULL;
2009
2010         result = pdb_search_init(mem_ctx, PDB_ALIAS_SEARCH);
2011         if (result == NULL) {
2012                 return NULL;
2013         }
2014
2015         if (!pdb->search_aliases(pdb, result, sid)) {
2016                 TALLOC_FREE(result);
2017                 return NULL;
2018         }
2019         return result;
2020 }
2021
2022 uint32_t pdb_search_entries(struct pdb_search *search,
2023                           uint32_t start_idx, uint32_t max_entries,
2024                           struct samr_displayentry **result)
2025 {
2026         struct samr_displayentry *end_entry;
2027         uint32_t end_idx = start_idx+max_entries-1;
2028
2029         /* The first entry needs to be searched after the last. Otherwise the
2030          * first entry might have moved due to a realloc during the search for
2031          * the last entry. */
2032
2033         end_entry = pdb_search_getentry(search, end_idx);
2034         *result = pdb_search_getentry(search, start_idx);
2035
2036         if (end_entry != NULL)
2037                 return max_entries;
2038
2039         if (start_idx >= search->num_entries)
2040                 return 0;
2041
2042         return search->num_entries - start_idx;
2043 }
2044
2045 /*******************************************************************
2046  trustdom methods
2047  *******************************************************************/
2048
2049 bool pdb_get_trusteddom_pw(const char *domain, char** pwd, struct dom_sid *sid,
2050                            time_t *pass_last_set_time)
2051 {
2052         struct pdb_methods *pdb = pdb_get_methods();
2053         return pdb->get_trusteddom_pw(pdb, domain, pwd, sid, 
2054                         pass_last_set_time);
2055 }
2056
2057 bool pdb_set_trusteddom_pw(const char* domain, const char* pwd,
2058                            const struct dom_sid *sid)
2059 {
2060         struct pdb_methods *pdb = pdb_get_methods();
2061         return pdb->set_trusteddom_pw(pdb, domain, pwd, sid);
2062 }
2063
2064 bool pdb_del_trusteddom_pw(const char *domain)
2065 {
2066         struct pdb_methods *pdb = pdb_get_methods();
2067         return pdb->del_trusteddom_pw(pdb, domain);
2068 }
2069
2070 NTSTATUS pdb_enum_trusteddoms(TALLOC_CTX *mem_ctx, uint32_t *num_domains,
2071                               struct trustdom_info ***domains)
2072 {
2073         struct pdb_methods *pdb = pdb_get_methods();
2074         return pdb->enum_trusteddoms(pdb, mem_ctx, num_domains, domains);
2075 }
2076
2077 /*******************************************************************
2078  the defaults for trustdom methods: 
2079  these simply call the original passdb/secrets.c actions,
2080  to be replaced by pdb_ldap.
2081  *******************************************************************/
2082
2083 static bool pdb_default_get_trusteddom_pw(struct pdb_methods *methods,
2084                                           const char *domain, 
2085                                           char** pwd, 
2086                                           struct dom_sid *sid,
2087                                           time_t *pass_last_set_time)
2088 {
2089         return secrets_fetch_trusted_domain_password(domain, pwd,
2090                                 sid, pass_last_set_time);
2091
2092 }
2093
2094 static bool pdb_default_set_trusteddom_pw(struct pdb_methods *methods, 
2095                                           const char* domain, 
2096                                           const char* pwd,
2097                                           const struct dom_sid *sid)
2098 {
2099         return secrets_store_trusted_domain_password(domain, pwd, sid);
2100 }
2101
2102 static bool pdb_default_del_trusteddom_pw(struct pdb_methods *methods, 
2103                                           const char *domain)
2104 {
2105         return trusted_domain_password_delete(domain);
2106 }
2107
2108 static NTSTATUS pdb_default_enum_trusteddoms(struct pdb_methods *methods,
2109                                              TALLOC_CTX *mem_ctx, 
2110                                              uint32_t *num_domains,
2111                                              struct trustdom_info ***domains)
2112 {
2113         return secrets_trusted_domains(mem_ctx, num_domains, domains);
2114 }
2115
2116 /*******************************************************************
2117  trusted_domain methods
2118  *******************************************************************/
2119
2120 NTSTATUS pdb_get_trusted_domain(TALLOC_CTX *mem_ctx, const char *domain,
2121                                 struct pdb_trusted_domain **td)
2122 {
2123         struct pdb_methods *pdb = pdb_get_methods();
2124         return pdb->get_trusted_domain(pdb, mem_ctx, domain, td);
2125 }
2126
2127 NTSTATUS pdb_get_trusted_domain_by_sid(TALLOC_CTX *mem_ctx, struct dom_sid *sid,
2128                                 struct pdb_trusted_domain **td)
2129 {
2130         struct pdb_methods *pdb = pdb_get_methods();
2131         return pdb->get_trusted_domain_by_sid(pdb, mem_ctx, sid, td);
2132 }
2133
2134 NTSTATUS pdb_set_trusted_domain(const char* domain,
2135                                 const struct pdb_trusted_domain *td)
2136 {
2137         struct pdb_methods *pdb = pdb_get_methods();
2138         return pdb->set_trusted_domain(pdb, domain, td);
2139 }
2140
2141 NTSTATUS pdb_del_trusted_domain(const char *domain)
2142 {
2143         struct pdb_methods *pdb = pdb_get_methods();
2144         return pdb->del_trusted_domain(pdb, domain);
2145 }
2146
2147 NTSTATUS pdb_enum_trusted_domains(TALLOC_CTX *mem_ctx, uint32_t *num_domains,
2148                                   struct pdb_trusted_domain ***domains)
2149 {
2150         struct pdb_methods *pdb = pdb_get_methods();
2151         return pdb->enum_trusted_domains(pdb, mem_ctx, num_domains, domains);
2152 }
2153
2154 static NTSTATUS pdb_default_get_trusted_domain(struct pdb_methods *methods,
2155                                                TALLOC_CTX *mem_ctx,
2156                                                const char *domain,
2157                                                struct pdb_trusted_domain **td)
2158 {
2159         struct trustAuthInOutBlob taiob;
2160         struct AuthenticationInformation aia;
2161         struct pdb_trusted_domain *tdom;
2162         enum ndr_err_code ndr_err;
2163         time_t last_set_time;
2164         char *pwd;
2165         bool ok;
2166
2167         tdom = talloc(mem_ctx, struct pdb_trusted_domain);
2168         if (!tdom) {
2169                 return NT_STATUS_NO_MEMORY;
2170         }
2171
2172         tdom->domain_name = talloc_strdup(tdom, domain);
2173         tdom->netbios_name = talloc_strdup(tdom, domain);
2174         if (!tdom->domain_name || !tdom->netbios_name) {
2175                 talloc_free(tdom);
2176                 return NT_STATUS_NO_MEMORY;
2177         }
2178
2179         tdom->trust_auth_incoming = data_blob_null;
2180
2181         ok = pdb_get_trusteddom_pw(domain, &pwd, &tdom->security_identifier,
2182                                    &last_set_time);
2183         if (!ok) {
2184                 talloc_free(tdom);
2185                 return NT_STATUS_UNSUCCESSFUL;
2186         }
2187
2188         ZERO_STRUCT(taiob);
2189         ZERO_STRUCT(aia);
2190         taiob.count = 1;
2191         taiob.current.count = 1;
2192         taiob.current.array = &aia;
2193         unix_to_nt_time(&aia.LastUpdateTime, last_set_time);
2194         aia.AuthType = TRUST_AUTH_TYPE_CLEAR;
2195         aia.AuthInfo.clear.password = (uint8_t *) pwd;
2196         aia.AuthInfo.clear.size = strlen(pwd);
2197         taiob.previous.count = 0;
2198         taiob.previous.array = NULL;
2199
2200         ndr_err = ndr_push_struct_blob(&tdom->trust_auth_outgoing,
2201                                         tdom, &taiob,
2202                         (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2203         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2204                 talloc_free(tdom);
2205                 return NT_STATUS_UNSUCCESSFUL;
2206         }
2207
2208         tdom->trust_direction = LSA_TRUST_DIRECTION_OUTBOUND;
2209         tdom->trust_type = LSA_TRUST_TYPE_DOWNLEVEL;
2210         tdom->trust_attributes = 0;
2211         tdom->trust_forest_trust_info = data_blob_null;
2212
2213         *td = tdom;
2214         return NT_STATUS_OK;
2215 }
2216
2217 static NTSTATUS pdb_default_get_trusted_domain_by_sid(struct pdb_methods *methods,
2218                                                       TALLOC_CTX *mem_ctx,
2219                                                       struct dom_sid *sid,
2220                                                       struct pdb_trusted_domain **td)
2221 {
2222         return NT_STATUS_NOT_IMPLEMENTED;
2223 }
2224
2225 #define IS_NULL_DATA_BLOB(d) ((d).data == NULL && (d).length == 0)
2226
2227 static NTSTATUS pdb_default_set_trusted_domain(struct pdb_methods *methods,
2228                                                const char* domain,
2229                                                const struct pdb_trusted_domain *td)
2230 {
2231         struct trustAuthInOutBlob taiob;
2232         struct AuthenticationInformation *aia;
2233         enum ndr_err_code ndr_err;
2234         char *pwd;
2235         bool ok;
2236
2237         if (td->trust_attributes != 0 ||
2238             td->trust_type != LSA_TRUST_TYPE_DOWNLEVEL ||
2239             td->trust_direction != LSA_TRUST_DIRECTION_OUTBOUND ||
2240             !IS_NULL_DATA_BLOB(td->trust_auth_incoming) ||
2241             !IS_NULL_DATA_BLOB(td->trust_forest_trust_info)) {
2242             return NT_STATUS_NOT_IMPLEMENTED;
2243         }
2244
2245         ZERO_STRUCT(taiob);
2246         ndr_err = ndr_pull_struct_blob(&td->trust_auth_outgoing, talloc_tos(),
2247                               &taiob,
2248                               (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2249         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2250                 return NT_STATUS_UNSUCCESSFUL;
2251         }
2252
2253         aia = (struct AuthenticationInformation *) taiob.current.array;
2254
2255         if (taiob.count != 1 || taiob.current.count != 1 ||
2256             taiob.previous.count != 0 ||
2257             aia->AuthType != TRUST_AUTH_TYPE_CLEAR) {
2258             return NT_STATUS_NOT_IMPLEMENTED;
2259         }
2260
2261         pwd = talloc_strndup(talloc_tos(), (char *) aia->AuthInfo.clear.password,
2262                              aia->AuthInfo.clear.size);
2263         if (!pwd) {
2264                 return NT_STATUS_NO_MEMORY;
2265         }
2266
2267         ok = pdb_set_trusteddom_pw(domain, pwd, &td->security_identifier);
2268         if (!ok) {
2269                 return NT_STATUS_UNSUCCESSFUL;
2270         }
2271
2272         return NT_STATUS_OK;
2273 }
2274
2275 static NTSTATUS pdb_default_del_trusted_domain(struct pdb_methods *methods,
2276                                                const char *domain)
2277 {
2278         return NT_STATUS_NOT_IMPLEMENTED;
2279 }
2280
2281 static NTSTATUS pdb_default_enum_trusted_domains(struct pdb_methods *methods,
2282                                                  TALLOC_CTX *mem_ctx,
2283                                                  uint32_t *num_domains,
2284                                                  struct pdb_trusted_domain ***domains)
2285 {
2286         return NT_STATUS_NOT_IMPLEMENTED;
2287 }
2288
2289 static struct pdb_domain_info *pdb_default_get_domain_info(
2290         struct pdb_methods *m, TALLOC_CTX *mem_ctx)
2291 {
2292         return NULL;
2293 }
2294
2295 /*******************************************************************
2296  secret methods
2297  *******************************************************************/
2298
2299 NTSTATUS pdb_get_secret(TALLOC_CTX *mem_ctx,
2300                         const char *secret_name,
2301                         DATA_BLOB *secret_current,
2302                         NTTIME *secret_current_lastchange,
2303                         DATA_BLOB *secret_old,
2304                         NTTIME *secret_old_lastchange,
2305                         struct security_descriptor **sd)
2306 {
2307         struct pdb_methods *pdb = pdb_get_methods();
2308         return pdb->get_secret(pdb, mem_ctx, secret_name,
2309                                secret_current, secret_current_lastchange,
2310                                secret_old, secret_old_lastchange,
2311                                sd);
2312 }
2313
2314 NTSTATUS pdb_set_secret(const char *secret_name,
2315                         DATA_BLOB *secret_current,
2316                         DATA_BLOB *secret_old,
2317                         struct security_descriptor *sd)
2318 {
2319         struct pdb_methods *pdb = pdb_get_methods();
2320         return pdb->set_secret(pdb, secret_name,
2321                                secret_current,
2322                                secret_old,
2323                                sd);
2324 }
2325
2326 NTSTATUS pdb_delete_secret(const char *secret_name)
2327 {
2328         struct pdb_methods *pdb = pdb_get_methods();
2329         return pdb->delete_secret(pdb, secret_name);
2330 }
2331
2332 static NTSTATUS pdb_default_get_secret(struct pdb_methods *methods,
2333                                        TALLOC_CTX *mem_ctx,
2334                                        const char *secret_name,
2335                                        DATA_BLOB *secret_current,
2336                                        NTTIME *secret_current_lastchange,
2337                                        DATA_BLOB *secret_old,
2338                                        NTTIME *secret_old_lastchange,
2339                                        struct security_descriptor **sd)
2340 {
2341         return lsa_secret_get(mem_ctx, secret_name,
2342                               secret_current,
2343                               secret_current_lastchange,
2344                               secret_old,
2345                               secret_old_lastchange,
2346                               sd);
2347 }
2348
2349 static NTSTATUS pdb_default_set_secret(struct pdb_methods *methods,
2350                                        const char *secret_name,
2351                                        DATA_BLOB *secret_current,
2352                                        DATA_BLOB *secret_old,
2353                                        struct security_descriptor *sd)
2354 {
2355         return lsa_secret_set(secret_name,
2356                               secret_current,
2357                               secret_old,
2358                               sd);
2359 }
2360
2361 static NTSTATUS pdb_default_delete_secret(struct pdb_methods *methods,
2362                                           const char *secret_name)
2363 {
2364         return lsa_secret_delete(secret_name);
2365 }
2366
2367 /*******************************************************************
2368  Create a pdb_methods structure and initialize it with the default
2369  operations.  In this way a passdb module can simply implement
2370  the functionality it cares about.  However, normally this is done 
2371  in groups of related functions.
2372 *******************************************************************/
2373
2374 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
2375 {
2376         /* allocate memory for the structure as its own talloc CTX */
2377
2378         *methods = talloc_zero(NULL, struct pdb_methods);
2379         if (*methods == NULL) {
2380                 return NT_STATUS_NO_MEMORY;
2381         }
2382
2383         (*methods)->get_domain_info = pdb_default_get_domain_info;
2384         (*methods)->getsampwnam = pdb_default_getsampwnam;
2385         (*methods)->getsampwsid = pdb_default_getsampwsid;
2386         (*methods)->create_user = pdb_default_create_user;
2387         (*methods)->delete_user = pdb_default_delete_user;
2388         (*methods)->add_sam_account = pdb_default_add_sam_account;
2389         (*methods)->update_sam_account = pdb_default_update_sam_account;
2390         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
2391         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
2392         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
2393
2394         (*methods)->getgrsid = pdb_default_getgrsid;
2395         (*methods)->getgrgid = pdb_default_getgrgid;
2396         (*methods)->getgrnam = pdb_default_getgrnam;
2397         (*methods)->create_dom_group = pdb_default_create_dom_group;
2398         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
2399         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
2400         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
2401         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
2402         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
2403         (*methods)->enum_group_members = pdb_default_enum_group_members;
2404         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
2405         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2406         (*methods)->add_groupmem = pdb_default_add_groupmem;
2407         (*methods)->del_groupmem = pdb_default_del_groupmem;
2408         (*methods)->create_alias = pdb_default_create_alias;
2409         (*methods)->delete_alias = pdb_default_delete_alias;
2410         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2411         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2412         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2413         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2414         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2415         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2416         (*methods)->lookup_rids = pdb_default_lookup_rids;
2417         (*methods)->get_account_policy = pdb_default_get_account_policy;
2418         (*methods)->set_account_policy = pdb_default_set_account_policy;
2419         (*methods)->get_seq_num = pdb_default_get_seq_num;
2420         (*methods)->uid_to_sid = pdb_default_uid_to_sid;
2421         (*methods)->gid_to_sid = pdb_default_gid_to_sid;
2422         (*methods)->sid_to_id = pdb_default_sid_to_id;
2423
2424         (*methods)->search_groups = pdb_default_search_groups;
2425         (*methods)->search_aliases = pdb_default_search_aliases;
2426
2427         (*methods)->get_trusteddom_pw = pdb_default_get_trusteddom_pw;
2428         (*methods)->set_trusteddom_pw = pdb_default_set_trusteddom_pw;
2429         (*methods)->del_trusteddom_pw = pdb_default_del_trusteddom_pw;
2430         (*methods)->enum_trusteddoms  = pdb_default_enum_trusteddoms;
2431
2432         (*methods)->get_trusted_domain = pdb_default_get_trusted_domain;
2433         (*methods)->get_trusted_domain_by_sid = pdb_default_get_trusted_domain_by_sid;
2434         (*methods)->set_trusted_domain = pdb_default_set_trusted_domain;
2435         (*methods)->del_trusted_domain = pdb_default_del_trusted_domain;
2436         (*methods)->enum_trusted_domains = pdb_default_enum_trusted_domains;
2437
2438         (*methods)->get_secret = pdb_default_get_secret;
2439         (*methods)->set_secret = pdb_default_set_secret;
2440         (*methods)->delete_secret = pdb_default_delete_secret;
2441
2442         return NT_STATUS_OK;
2443 }