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