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