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