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