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