s3: Rename server_messaging_context() to global_messaging_context()
[bbaumbach/samba-autobuild/.git] / source3 / passdb / pdb_interface.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Password and authentication handling
4    Copyright (C) Andrew Bartlett                        2002
5    Copyright (C) Jelmer Vernooij                        2002
6    Copyright (C) Simo Sorce                             2003
7    Copyright (C) Volker Lendecke                        2006
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "system/passwd.h"
25 #include "passdb.h"
26 #include "secrets.h"
27 #include "messages.h"
28 #include "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(NULL);
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, 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, 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         messaging_send_all(global_messaging_context(),
652                            ID_CACHE_DELETE,
653                            msg_data,
654                            strlen(msg_data) + 1);
655
656         TALLOC_FREE(msg_data);
657         return status;
658 }
659
660 NTSTATUS pdb_add_sam_account(struct samu *sam_acct) 
661 {
662         struct pdb_methods *pdb = pdb_get_methods();
663         return pdb->add_sam_account(pdb, sam_acct);
664 }
665
666 NTSTATUS pdb_update_sam_account(struct samu *sam_acct) 
667 {
668         struct pdb_methods *pdb = pdb_get_methods();
669
670         memcache_flush(NULL, PDB_GETPWSID_CACHE);
671
672         return pdb->update_sam_account(pdb, sam_acct);
673 }
674
675 NTSTATUS pdb_delete_sam_account(struct samu *sam_acct) 
676 {
677         struct pdb_methods *pdb = pdb_get_methods();
678         const struct dom_sid *user_sid = pdb_get_user_sid(sam_acct);
679
680         memcache_delete(NULL,
681                         PDB_GETPWSID_CACHE,
682                         data_blob_const(user_sid, sizeof(*user_sid)));
683
684         return pdb->delete_sam_account(pdb, sam_acct);
685 }
686
687 NTSTATUS pdb_rename_sam_account(struct samu *oldname, const char *newname)
688 {
689         struct pdb_methods *pdb = pdb_get_methods();
690         uid_t uid;
691         NTSTATUS status;
692
693         memcache_flush(NULL, PDB_GETPWSID_CACHE);
694
695         /* sanity check to make sure we don't rename root */
696
697         if ( !sid_to_uid( pdb_get_user_sid(oldname), &uid ) ) {
698                 return NT_STATUS_NO_SUCH_USER;
699         }
700
701         if ( uid == 0 ) {
702                 return NT_STATUS_ACCESS_DENIED;
703         }
704
705         status = pdb->rename_sam_account(pdb, oldname, newname);
706
707         /* always flush the cache here just to be safe */
708         flush_pwnam_cache();
709
710         return status;
711 }
712
713 NTSTATUS pdb_update_login_attempts(struct samu *sam_acct, bool success)
714 {
715         struct pdb_methods *pdb = pdb_get_methods();
716         return pdb->update_login_attempts(pdb, sam_acct, success);
717 }
718
719 bool pdb_getgrsid(GROUP_MAP *map, struct dom_sid sid)
720 {
721         struct pdb_methods *pdb = pdb_get_methods();
722         return NT_STATUS_IS_OK(pdb->getgrsid(pdb, map, sid));
723 }
724
725 bool pdb_getgrgid(GROUP_MAP *map, gid_t gid)
726 {
727         struct pdb_methods *pdb = pdb_get_methods();
728         return NT_STATUS_IS_OK(pdb->getgrgid(pdb, map, gid));
729 }
730
731 bool pdb_getgrnam(GROUP_MAP *map, const char *name)
732 {
733         struct pdb_methods *pdb = pdb_get_methods();
734         return NT_STATUS_IS_OK(pdb->getgrnam(pdb, map, name));
735 }
736
737 static NTSTATUS pdb_default_create_dom_group(struct pdb_methods *methods,
738                                              TALLOC_CTX *mem_ctx,
739                                              const char *name,
740                                              uint32_t *rid)
741 {
742         struct dom_sid group_sid;
743         struct group *grp;
744         fstring tmp;
745
746         grp = getgrnam(name);
747
748         if (grp == NULL) {
749                 gid_t gid;
750
751                 if (smb_create_group(name, &gid) != 0) {
752                         return NT_STATUS_ACCESS_DENIED;
753                 }
754
755                 grp = getgrgid(gid);
756         }
757
758         if (grp == NULL) {
759                 return NT_STATUS_ACCESS_DENIED;
760         }
761
762         if (pdb_capabilities() & PDB_CAP_STORE_RIDS) {
763                 if (!pdb_new_rid(rid)) {
764                         return NT_STATUS_ACCESS_DENIED;
765                 }
766         } else {
767                 *rid = algorithmic_pdb_gid_to_group_rid( grp->gr_gid );
768         }
769
770         sid_compose(&group_sid, get_global_sam_sid(), *rid);
771
772         return add_initial_entry(grp->gr_gid, sid_to_fstring(tmp, &group_sid),
773                                  SID_NAME_DOM_GRP, name, NULL);
774 }
775
776 NTSTATUS pdb_create_dom_group(TALLOC_CTX *mem_ctx, const char *name,
777                               uint32_t *rid)
778 {
779         struct pdb_methods *pdb = pdb_get_methods();
780         return pdb->create_dom_group(pdb, mem_ctx, name, rid);
781 }
782
783 static NTSTATUS pdb_default_delete_dom_group(struct pdb_methods *methods,
784                                              TALLOC_CTX *mem_ctx,
785                                              uint32_t rid)
786 {
787         struct dom_sid group_sid;
788         GROUP_MAP *map;
789         NTSTATUS status;
790         struct group *grp;
791         const char *grp_name;
792
793         map = talloc_zero(mem_ctx, GROUP_MAP);
794         if (!map) {
795                 return NT_STATUS_NO_MEMORY;
796         }
797
798         /* coverity */
799         map->gid = (gid_t) -1;
800
801         sid_compose(&group_sid, get_global_sam_sid(), rid);
802
803         if (!get_domain_group_from_sid(group_sid, map)) {
804                 DEBUG(10, ("Could not find group for rid %d\n", rid));
805                 return NT_STATUS_NO_SUCH_GROUP;
806         }
807
808         /* We need the group name for the smb_delete_group later on */
809
810         if (map->gid == (gid_t)-1) {
811                 return NT_STATUS_NO_SUCH_GROUP;
812         }
813
814         grp = getgrgid(map->gid);
815         if (grp == NULL) {
816                 return NT_STATUS_NO_SUCH_GROUP;
817         }
818
819         TALLOC_FREE(map);
820
821         /* Copy the name, no idea what pdb_delete_group_mapping_entry does.. */
822
823         grp_name = talloc_strdup(mem_ctx, grp->gr_name);
824         if (grp_name == NULL) {
825                 return NT_STATUS_NO_MEMORY;
826         }
827
828         status = pdb_delete_group_mapping_entry(group_sid);
829
830         if (!NT_STATUS_IS_OK(status)) {
831                 return status;
832         }
833
834         /* Don't check the result of smb_delete_group */
835
836         smb_delete_group(grp_name);
837
838         return NT_STATUS_OK;
839 }
840
841 NTSTATUS pdb_delete_dom_group(TALLOC_CTX *mem_ctx, uint32_t rid)
842 {
843         struct pdb_methods *pdb = pdb_get_methods();
844         return pdb->delete_dom_group(pdb, mem_ctx, rid);
845 }
846
847 NTSTATUS pdb_add_group_mapping_entry(GROUP_MAP *map)
848 {
849         struct pdb_methods *pdb = pdb_get_methods();
850         return pdb->add_group_mapping_entry(pdb, map);
851 }
852
853 NTSTATUS pdb_update_group_mapping_entry(GROUP_MAP *map)
854 {
855         struct pdb_methods *pdb = pdb_get_methods();
856         return pdb->update_group_mapping_entry(pdb, map);
857 }
858
859 NTSTATUS pdb_delete_group_mapping_entry(struct dom_sid sid)
860 {
861         struct pdb_methods *pdb = pdb_get_methods();
862         return pdb->delete_group_mapping_entry(pdb, sid);
863 }
864
865 bool pdb_enum_group_mapping(const struct dom_sid *sid,
866                             enum lsa_SidType sid_name_use,
867                             GROUP_MAP ***pp_rmap,
868                             size_t *p_num_entries,
869                             bool unix_only)
870 {
871         struct pdb_methods *pdb = pdb_get_methods();
872         return NT_STATUS_IS_OK(pdb-> enum_group_mapping(pdb, sid, sid_name_use,
873                 pp_rmap, p_num_entries, unix_only));
874 }
875
876 NTSTATUS pdb_enum_group_members(TALLOC_CTX *mem_ctx,
877                                 const struct dom_sid *sid,
878                                 uint32_t **pp_member_rids,
879                                 size_t *p_num_members)
880 {
881         struct pdb_methods *pdb = pdb_get_methods();
882         NTSTATUS result;
883
884         result = pdb->enum_group_members(pdb, mem_ctx, 
885                         sid, pp_member_rids, p_num_members);
886
887         /* special check for rid 513 */
888
889         if ( !NT_STATUS_IS_OK( result ) ) {
890                 uint32_t rid;
891
892                 sid_peek_rid( sid, &rid );
893
894                 if ( rid == DOMAIN_RID_USERS ) {
895                         *p_num_members = 0;
896                         *pp_member_rids = NULL;
897
898                         return NT_STATUS_OK;
899                 }
900         }
901
902         return result;
903 }
904
905 NTSTATUS pdb_enum_group_memberships(TALLOC_CTX *mem_ctx, struct samu *user,
906                                     struct dom_sid **pp_sids, gid_t **pp_gids,
907                                     uint32_t *p_num_groups)
908 {
909         struct pdb_methods *pdb = pdb_get_methods();
910         return pdb->enum_group_memberships(
911                 pdb, mem_ctx, user,
912                 pp_sids, pp_gids, p_num_groups);
913 }
914
915 static NTSTATUS pdb_default_set_unix_primary_group(struct pdb_methods *methods,
916                                                    TALLOC_CTX *mem_ctx,
917                                                    struct samu *sampass)
918 {
919         struct group *grp;
920         gid_t gid;
921
922         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid) ||
923             (grp = getgrgid(gid)) == NULL) {
924                 return NT_STATUS_INVALID_PRIMARY_GROUP;
925         }
926
927         if (smb_set_primary_group(grp->gr_name,
928                                   pdb_get_username(sampass)) != 0) {
929                 return NT_STATUS_ACCESS_DENIED;
930         }
931
932         return NT_STATUS_OK;
933 }
934
935 NTSTATUS pdb_set_unix_primary_group(TALLOC_CTX *mem_ctx, struct samu *user)
936 {
937         struct pdb_methods *pdb = pdb_get_methods();
938         return pdb->set_unix_primary_group(pdb, mem_ctx, user);
939 }
940
941 /*
942  * Helper function to see whether a user is in a group. We can't use
943  * user_in_group_sid here because this creates dependencies only smbd can
944  * fulfil.
945  */
946
947 static bool pdb_user_in_group(TALLOC_CTX *mem_ctx, struct samu *account,
948                               const struct dom_sid *group_sid)
949 {
950         struct dom_sid *sids;
951         gid_t *gids;
952         uint32_t i, num_groups;
953
954         if (!NT_STATUS_IS_OK(pdb_enum_group_memberships(mem_ctx, account,
955                                                         &sids, &gids,
956                                                         &num_groups))) {
957                 return False;
958         }
959
960         for (i=0; i<num_groups; i++) {
961                 if (dom_sid_equal(group_sid, &sids[i])) {
962                         return True;
963                 }
964         }
965         return False;
966 }
967
968 static NTSTATUS pdb_default_add_groupmem(struct pdb_methods *methods,
969                                          TALLOC_CTX *mem_ctx,
970                                          uint32_t group_rid,
971                                          uint32_t member_rid)
972 {
973         struct dom_sid group_sid, member_sid;
974         struct samu *account = NULL;
975         GROUP_MAP *map;
976         struct group *grp;
977         struct passwd *pwd;
978         const char *group_name;
979         uid_t uid;
980
981         map = talloc_zero(mem_ctx, GROUP_MAP);
982         if (!map) {
983                 return NT_STATUS_NO_MEMORY;
984         }
985
986         /* coverity */
987         map->gid = (gid_t) -1;
988
989         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
990         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
991
992         if (!get_domain_group_from_sid(group_sid, map) ||
993             (map->gid == (gid_t)-1) ||
994             ((grp = getgrgid(map->gid)) == NULL)) {
995                 return NT_STATUS_NO_SUCH_GROUP;
996         }
997
998         TALLOC_FREE(map);
999
1000         group_name = talloc_strdup(mem_ctx, grp->gr_name);
1001         if (group_name == NULL) {
1002                 return NT_STATUS_NO_MEMORY;
1003         }
1004
1005         if ( !(account = samu_new( NULL )) ) {
1006                 return NT_STATUS_NO_MEMORY;
1007         }
1008
1009         if (!pdb_getsampwsid(account, &member_sid) ||
1010             !sid_to_uid(&member_sid, &uid) ||
1011             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
1012                 return NT_STATUS_NO_SUCH_USER;
1013         }
1014
1015         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
1016                 return NT_STATUS_MEMBER_IN_GROUP;
1017         }
1018
1019         /* 
1020          * ok, the group exist, the user exist, the user is not in the group,
1021          * we can (finally) add it to the group !
1022          */
1023
1024         smb_add_user_group(group_name, pwd->pw_name);
1025
1026         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
1027                 return NT_STATUS_ACCESS_DENIED;
1028         }
1029
1030         return NT_STATUS_OK;
1031 }
1032
1033 NTSTATUS pdb_add_groupmem(TALLOC_CTX *mem_ctx, uint32_t group_rid,
1034                           uint32_t member_rid)
1035 {
1036         struct pdb_methods *pdb = pdb_get_methods();
1037         return pdb->add_groupmem(pdb, mem_ctx, group_rid, member_rid);
1038 }
1039
1040 static NTSTATUS pdb_default_del_groupmem(struct pdb_methods *methods,
1041                                          TALLOC_CTX *mem_ctx,
1042                                          uint32_t group_rid,
1043                                          uint32_t member_rid)
1044 {
1045         struct dom_sid group_sid, member_sid;
1046         struct samu *account = NULL;
1047         GROUP_MAP *map;
1048         struct group *grp;
1049         struct passwd *pwd;
1050         const char *group_name;
1051         uid_t uid;
1052
1053         map = talloc_zero(mem_ctx, GROUP_MAP);
1054         if (!map) {
1055                 return NT_STATUS_NO_MEMORY;
1056         }
1057
1058         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
1059         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
1060
1061         if (!get_domain_group_from_sid(group_sid, map) ||
1062             (map->gid == (gid_t)-1) ||
1063             ((grp = getgrgid(map->gid)) == NULL)) {
1064                 return NT_STATUS_NO_SUCH_GROUP;
1065         }
1066
1067         TALLOC_FREE(map);
1068
1069         group_name = talloc_strdup(mem_ctx, grp->gr_name);
1070         if (group_name == NULL) {
1071                 return NT_STATUS_NO_MEMORY;
1072         }
1073
1074         if ( !(account = samu_new( NULL )) ) {
1075                 return NT_STATUS_NO_MEMORY;
1076         }
1077
1078         if (!pdb_getsampwsid(account, &member_sid) ||
1079             !sid_to_uid(&member_sid, &uid) ||
1080             ((pwd = getpwuid_alloc(mem_ctx, uid)) == NULL)) {
1081                 return NT_STATUS_NO_SUCH_USER;
1082         }
1083
1084         if (!pdb_user_in_group(mem_ctx, account, &group_sid)) {
1085                 return NT_STATUS_MEMBER_NOT_IN_GROUP;
1086         }
1087
1088         /* 
1089          * ok, the group exist, the user exist, the user is in the group,
1090          * we can (finally) delete it from the group!
1091          */
1092
1093         smb_delete_user_group(group_name, pwd->pw_name);
1094
1095         if (pdb_user_in_group(mem_ctx, account, &group_sid)) {
1096                 return NT_STATUS_ACCESS_DENIED;
1097         }
1098
1099         return NT_STATUS_OK;
1100 }
1101
1102 NTSTATUS pdb_del_groupmem(TALLOC_CTX *mem_ctx, uint32_t group_rid,
1103                           uint32_t member_rid)
1104 {
1105         struct pdb_methods *pdb = pdb_get_methods();
1106         return pdb->del_groupmem(pdb, mem_ctx, group_rid, member_rid);
1107 }
1108
1109 NTSTATUS pdb_create_alias(const char *name, uint32_t *rid)
1110 {
1111         struct pdb_methods *pdb = pdb_get_methods();
1112         return pdb->create_alias(pdb, name, rid);
1113 }
1114
1115 NTSTATUS pdb_delete_alias(const struct dom_sid *sid)
1116 {
1117         struct pdb_methods *pdb = pdb_get_methods();
1118         return pdb->delete_alias(pdb, sid);
1119 }
1120
1121 NTSTATUS pdb_get_aliasinfo(const struct dom_sid *sid, struct acct_info *info)
1122 {
1123         struct pdb_methods *pdb = pdb_get_methods();
1124         return pdb->get_aliasinfo(pdb, sid, info);
1125 }
1126
1127 NTSTATUS pdb_set_aliasinfo(const struct dom_sid *sid, struct acct_info *info)
1128 {
1129         struct pdb_methods *pdb = pdb_get_methods();
1130         return pdb->set_aliasinfo(pdb, sid, info);
1131 }
1132
1133 NTSTATUS pdb_add_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
1134 {
1135         struct pdb_methods *pdb = pdb_get_methods();
1136         return pdb->add_aliasmem(pdb, alias, member);
1137 }
1138
1139 NTSTATUS pdb_del_aliasmem(const struct dom_sid *alias, const struct dom_sid *member)
1140 {
1141         struct pdb_methods *pdb = pdb_get_methods();
1142         return pdb->del_aliasmem(pdb, alias, member);
1143 }
1144
1145 NTSTATUS pdb_enum_aliasmem(const struct dom_sid *alias, TALLOC_CTX *mem_ctx,
1146                            struct dom_sid **pp_members, size_t *p_num_members)
1147 {
1148         struct pdb_methods *pdb = pdb_get_methods();
1149         return pdb->enum_aliasmem(pdb, alias, mem_ctx, pp_members,
1150                                   p_num_members);
1151 }
1152
1153 NTSTATUS pdb_enum_alias_memberships(TALLOC_CTX *mem_ctx,
1154                                     const struct dom_sid *domain_sid,
1155                                     const struct dom_sid *members, size_t num_members,
1156                                     uint32_t **pp_alias_rids,
1157                                     size_t *p_num_alias_rids)
1158 {
1159         struct pdb_methods *pdb = pdb_get_methods();
1160         return pdb->enum_alias_memberships(pdb, mem_ctx,
1161                                                        domain_sid,
1162                                                        members, num_members,
1163                                                        pp_alias_rids,
1164                                                        p_num_alias_rids);
1165 }
1166
1167 NTSTATUS pdb_lookup_rids(const struct dom_sid *domain_sid,
1168                          int num_rids,
1169                          uint32_t *rids,
1170                          const char **names,
1171                          enum lsa_SidType *attrs)
1172 {
1173         struct pdb_methods *pdb = pdb_get_methods();
1174         return pdb->lookup_rids(pdb, domain_sid, num_rids, rids, names, attrs);
1175 }
1176
1177 bool pdb_get_account_policy(enum pdb_policy_type type, uint32_t *value)
1178 {
1179         struct pdb_methods *pdb = pdb_get_methods();
1180         NTSTATUS status;
1181
1182         become_root();
1183         status = pdb->get_account_policy(pdb, type, value);
1184         unbecome_root();
1185
1186         return NT_STATUS_IS_OK(status); 
1187 }
1188
1189 bool pdb_set_account_policy(enum pdb_policy_type type, uint32_t value)
1190 {
1191         struct pdb_methods *pdb = pdb_get_methods();
1192         NTSTATUS status;
1193
1194         become_root();
1195         status = pdb->set_account_policy(pdb, type, value);
1196         unbecome_root();
1197
1198         return NT_STATUS_IS_OK(status);
1199 }
1200
1201 bool pdb_get_seq_num(time_t *seq_num)
1202 {
1203         struct pdb_methods *pdb = pdb_get_methods();
1204         return NT_STATUS_IS_OK(pdb->get_seq_num(pdb, seq_num));
1205 }
1206
1207 /* 
1208  * Instead of passing down a gid or uid, this function sends down a pointer
1209  * to a unixid. 
1210  *
1211  * This acts as an in-out variable so that the idmap functions can correctly
1212  * receive ID_TYPE_BOTH, filling in cache details correctly rather than forcing
1213  * the cache to store ID_TYPE_UID or ID_TYPE_GID. 
1214  */
1215 bool pdb_id_to_sid(struct unixid *id, struct dom_sid *sid)
1216 {
1217         struct pdb_methods *pdb = pdb_get_methods();
1218         bool ret;
1219
1220         ret = pdb->id_to_sid(pdb, id, sid);
1221
1222         if (ret) {
1223                 idmap_cache_set_sid2unixid(sid, id);
1224         }
1225
1226         return ret;
1227 }
1228
1229 bool pdb_sid_to_id(const struct dom_sid *sid, struct unixid *id)
1230 {
1231         struct pdb_methods *pdb = pdb_get_methods();
1232         bool ret;
1233
1234         /* only ask the backend if it is responsible */
1235         if (!sid_check_object_is_for_passdb(sid)) {
1236                 return false;
1237         }
1238
1239         ret = pdb->sid_to_id(pdb, sid, id);
1240
1241         if (ret == true) {
1242                 idmap_cache_set_sid2unixid(sid, id);
1243         }
1244
1245         return ret;
1246 }
1247
1248 uint32_t pdb_capabilities(void)
1249 {
1250         struct pdb_methods *pdb = pdb_get_methods();
1251         return pdb->capabilities(pdb);
1252 }
1253
1254 /********************************************************************
1255  Allocate a new RID from the passdb backend.  Verify that it is free
1256  by calling lookup_global_sam_rid() to verify that the RID is not
1257  in use.  This handles servers that have existing users or groups
1258  with add RIDs (assigned from previous algorithmic mappings)
1259 ********************************************************************/
1260
1261 bool pdb_new_rid(uint32_t *rid)
1262 {
1263         struct pdb_methods *pdb = pdb_get_methods();
1264         const char *name = NULL;
1265         enum lsa_SidType type;
1266         uint32_t allocated_rid = 0;
1267         int i;
1268         TALLOC_CTX *ctx;
1269
1270         if ((pdb_capabilities() & PDB_CAP_STORE_RIDS) == 0) {
1271                 DEBUG(0, ("Trying to allocate a RID when algorithmic RIDs "
1272                           "are active\n"));
1273                 return False;
1274         }
1275
1276         if (algorithmic_rid_base() != BASE_RID) {
1277                 DEBUG(0, ("'algorithmic rid base' is set but a passdb backend "
1278                           "without algorithmic RIDs is chosen.\n"));
1279                 DEBUGADD(0, ("Please map all used groups using 'net groupmap "
1280                              "add', set the maximum used RID\n"));
1281                 DEBUGADD(0, ("and remove the parameter\n"));
1282                 return False;
1283         }
1284
1285         if ( (ctx = talloc_init("pdb_new_rid")) == NULL ) {
1286                 DEBUG(0,("pdb_new_rid: Talloc initialization failure\n"));
1287                 return False;
1288         }
1289
1290         /* Attempt to get an unused RID (max tires is 250...yes that it is 
1291            and arbitrary number I pulkled out of my head).   -- jerry */
1292
1293         for ( i=0; allocated_rid==0 && i<250; i++ ) {
1294                 /* get a new RID */
1295
1296                 if ( !pdb->new_rid(pdb, &allocated_rid) ) {
1297                         return False;
1298                 }
1299
1300                 /* validate that the RID is not in use */
1301
1302                 if (lookup_global_sam_rid(ctx, allocated_rid, &name, &type, NULL, NULL)) {
1303                         allocated_rid = 0;
1304                 }
1305         }
1306
1307         TALLOC_FREE( ctx );
1308
1309         if ( allocated_rid == 0 ) {
1310                 DEBUG(0,("pdb_new_rid: Failed to find unused RID\n"));
1311                 return False;
1312         }
1313
1314         *rid = allocated_rid;
1315
1316         return True;
1317 }
1318
1319 /***************************************************************
1320   Initialize the static context (at smbd startup etc). 
1321
1322   If uninitialised, context will auto-init on first use.
1323  ***************************************************************/
1324
1325 bool initialize_password_db(bool reload, struct tevent_context *tevent_ctx)
1326 {
1327         if (tevent_ctx) {
1328                 pdb_tevent_ctx = tevent_ctx;
1329         }
1330         return (pdb_get_methods_reload(reload) != NULL);
1331 }
1332
1333 /***************************************************************************
1334   Default implementations of some functions.
1335  ****************************************************************************/
1336
1337 static NTSTATUS pdb_default_getsampwnam (struct pdb_methods *methods, struct samu *user, const char *sname)
1338 {
1339         return NT_STATUS_NO_SUCH_USER;
1340 }
1341
1342 static NTSTATUS pdb_default_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1343 {
1344         return NT_STATUS_NO_SUCH_USER;
1345 }
1346
1347 static NTSTATUS pdb_default_add_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1348 {
1349         return NT_STATUS_NOT_IMPLEMENTED;
1350 }
1351
1352 static NTSTATUS pdb_default_update_sam_account (struct pdb_methods *methods, struct samu *newpwd)
1353 {
1354         return NT_STATUS_NOT_IMPLEMENTED;
1355 }
1356
1357 static NTSTATUS pdb_default_delete_sam_account (struct pdb_methods *methods, struct samu *pwd)
1358 {
1359         return NT_STATUS_NOT_IMPLEMENTED;
1360 }
1361
1362 static NTSTATUS pdb_default_rename_sam_account (struct pdb_methods *methods, struct samu *pwd, const char *newname)
1363 {
1364         return NT_STATUS_NOT_IMPLEMENTED;
1365 }
1366
1367 static NTSTATUS pdb_default_update_login_attempts (struct pdb_methods *methods, struct samu *newpwd, bool success)
1368 {
1369         /* Only the pdb_nds backend implements this, by
1370          * default just return ok. */
1371         return NT_STATUS_OK;
1372 }
1373
1374 static NTSTATUS pdb_default_get_account_policy(struct pdb_methods *methods, enum pdb_policy_type type, uint32_t *value)
1375 {
1376         return account_policy_get(type, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1377 }
1378
1379 static NTSTATUS pdb_default_set_account_policy(struct pdb_methods *methods, enum pdb_policy_type type, uint32_t value)
1380 {
1381         return account_policy_set(type, value) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1382 }
1383
1384 static NTSTATUS pdb_default_get_seq_num(struct pdb_methods *methods, time_t *seq_num)
1385 {
1386         *seq_num = time(NULL);
1387         return NT_STATUS_OK;
1388 }
1389
1390 static bool pdb_default_uid_to_sid(struct pdb_methods *methods, uid_t uid,
1391                                    struct dom_sid *sid)
1392 {
1393         struct samu *sampw = NULL;
1394         struct passwd *unix_pw;
1395         bool ret;
1396
1397         unix_pw = getpwuid( uid );
1398
1399         if ( !unix_pw ) {
1400                 DEBUG(4,("pdb_default_uid_to_sid: host has no idea of uid "
1401                          "%lu\n", (unsigned long)uid));
1402                 return False;
1403         }
1404
1405         if ( !(sampw = samu_new( NULL )) ) {
1406                 DEBUG(0,("pdb_default_uid_to_sid: samu_new() failed!\n"));
1407                 return False;
1408         }
1409
1410         become_root();
1411         ret = NT_STATUS_IS_OK(
1412                 methods->getsampwnam(methods, sampw, unix_pw->pw_name ));
1413         unbecome_root();
1414
1415         if (!ret) {
1416                 DEBUG(5, ("pdb_default_uid_to_sid: Did not find user "
1417                           "%s (%u)\n", unix_pw->pw_name, (unsigned int)uid));
1418                 TALLOC_FREE(sampw);
1419                 return False;
1420         }
1421
1422         sid_copy(sid, pdb_get_user_sid(sampw));
1423
1424         TALLOC_FREE(sampw);
1425
1426         return True;
1427 }
1428
1429 static bool pdb_default_gid_to_sid(struct pdb_methods *methods, gid_t gid,
1430                                    struct dom_sid *sid)
1431 {
1432         GROUP_MAP *map;
1433
1434         map = talloc_zero(NULL, GROUP_MAP);
1435         if (!map) {
1436                 return false;
1437         }
1438
1439         if (!NT_STATUS_IS_OK(methods->getgrgid(methods, map, gid))) {
1440                 TALLOC_FREE(map);
1441                 return false;
1442         }
1443
1444         sid_copy(sid, &map->sid);
1445         TALLOC_FREE(map);
1446         return true;
1447 }
1448
1449 static bool pdb_default_id_to_sid(struct pdb_methods *methods, struct unixid *id,
1450                                    struct dom_sid *sid)
1451 {
1452         switch (id->type) {
1453         case ID_TYPE_UID:
1454                 return pdb_default_uid_to_sid(methods, id->id, sid);
1455
1456         case ID_TYPE_GID:
1457                 return pdb_default_gid_to_sid(methods, id->id, sid);
1458
1459         default:
1460                 return false;
1461         }
1462 }
1463 /**
1464  * The "Unix User" and "Unix Group" domains have a special
1465  * id mapping that is a rid-algorithm with range starting at 0.
1466  */
1467 bool pdb_sid_to_id_unix_users_and_groups(const struct dom_sid *sid,
1468                                          struct unixid *id)
1469 {
1470         uint32_t rid;
1471
1472         id->id = -1;
1473
1474         if (sid_peek_check_rid(&global_sid_Unix_Users, sid, &rid)) {
1475                 id->id = rid;
1476                 id->type = ID_TYPE_UID;
1477                 return true;
1478         }
1479
1480         if (sid_peek_check_rid(&global_sid_Unix_Groups, sid, &rid)) {
1481                 id->id = rid;
1482                 id->type = ID_TYPE_GID;
1483                 return true;
1484         }
1485
1486         return false;
1487 }
1488
1489 static bool pdb_default_sid_to_id(struct pdb_methods *methods,
1490                                   const struct dom_sid *sid,
1491                                   struct unixid *id)
1492 {
1493         TALLOC_CTX *mem_ctx;
1494         bool ret = False;
1495         uint32_t rid;
1496         id->id = -1;
1497
1498         mem_ctx = talloc_new(NULL);
1499
1500         if (mem_ctx == NULL) {
1501                 DEBUG(0, ("talloc_new failed\n"));
1502                 return False;
1503         }
1504
1505         if (sid_peek_check_rid(get_global_sam_sid(), sid, &rid)) {
1506                 const char *name;
1507                 enum lsa_SidType type;
1508                 uid_t uid = (uid_t)-1;
1509                 gid_t gid = (gid_t)-1;
1510                 /* Here we might have users as well as groups and aliases */
1511                 ret = lookup_global_sam_rid(mem_ctx, rid, &name, &type, &uid, &gid);
1512                 if (ret) {
1513                         switch (type) {
1514                         case SID_NAME_DOM_GRP:
1515                         case SID_NAME_ALIAS:
1516                                 id->type = ID_TYPE_GID;
1517                                 id->id = gid;
1518                                 break;
1519                         case SID_NAME_USER:
1520                                 id->type = ID_TYPE_UID;
1521                                 id->id = uid;
1522                                 break;
1523                         default:
1524                                 DEBUG(5, ("SID %s belongs to our domain, and "
1525                                           "an object exists in the database, "
1526                                            "but it is neither a user nor a "
1527                                            "group (got type %d).\n",
1528                                           sid_string_dbg(sid), type));
1529                                 ret = false;
1530                         }
1531                 } else {
1532                         DEBUG(5, ("SID %s belongs to our domain, but there is "
1533                                   "no corresponding object in the database.\n",
1534                                   sid_string_dbg(sid)));
1535                 }
1536                 goto done;
1537         }
1538
1539         /*
1540          * "Unix User" and "Unix Group"
1541          */
1542         ret = pdb_sid_to_id_unix_users_and_groups(sid, id);
1543         if (ret == true) {
1544                 goto done;
1545         }
1546
1547         /* BUILTIN */
1548
1549         if (sid_check_is_in_builtin(sid) ||
1550             sid_check_is_in_wellknown_domain(sid)) {
1551                 /* Here we only have aliases */
1552                 GROUP_MAP *map;
1553
1554                 map = talloc_zero(mem_ctx, GROUP_MAP);
1555                 if (!map) {
1556                         ret = false;
1557                         goto done;
1558                 }
1559
1560                 if (!NT_STATUS_IS_OK(methods->getgrsid(methods, map, *sid))) {
1561                         DEBUG(10, ("Could not find map for sid %s\n",
1562                                    sid_string_dbg(sid)));
1563                         goto done;
1564                 }
1565                 if ((map->sid_name_use != SID_NAME_ALIAS) &&
1566                     (map->sid_name_use != SID_NAME_WKN_GRP)) {
1567                         DEBUG(10, ("Map for sid %s is a %s, expected an "
1568                                    "alias\n", sid_string_dbg(sid),
1569                                    sid_type_lookup(map->sid_name_use)));
1570                         goto done;
1571                 }
1572
1573                 id->id = map->gid;
1574                 id->type = ID_TYPE_GID;
1575                 ret = True;
1576                 goto done;
1577         }
1578
1579         DEBUG(5, ("Sid %s is neither ours, a Unix SID, nor builtin\n",
1580                   sid_string_dbg(sid)));
1581
1582  done:
1583
1584         TALLOC_FREE(mem_ctx);
1585         return ret;
1586 }
1587
1588 static bool get_memberuids(TALLOC_CTX *mem_ctx, gid_t gid, uid_t **pp_uids, uint32_t *p_num)
1589 {
1590         struct group *grp;
1591         char **gr;
1592         struct passwd *pwd;
1593         bool winbind_env;
1594         bool ret = False;
1595  
1596         *pp_uids = NULL;
1597         *p_num = 0;
1598
1599         /* We only look at our own sam, so don't care about imported stuff */
1600         winbind_env = winbind_env_set();
1601         (void)winbind_off();
1602
1603         if ((grp = getgrgid(gid)) == NULL) {
1604                 /* allow winbindd lookups, but only if they weren't already disabled */
1605                 goto done;
1606         }
1607
1608         /* Primary group members */
1609         setpwent();
1610         while ((pwd = getpwent()) != NULL) {
1611                 if (pwd->pw_gid == gid) {
1612                         if (!add_uid_to_array_unique(mem_ctx, pwd->pw_uid,
1613                                                 pp_uids, p_num)) {
1614                                 goto done;
1615                         }
1616                 }
1617         }
1618         endpwent();
1619
1620         /* Secondary group members */
1621         for (gr = grp->gr_mem; (*gr != NULL) && ((*gr)[0] != '\0'); gr += 1) {
1622                 struct passwd *pw = getpwnam(*gr);
1623
1624                 if (pw == NULL)
1625                         continue;
1626                 if (!add_uid_to_array_unique(mem_ctx, pw->pw_uid, pp_uids, p_num)) {
1627                         goto done;
1628                 }
1629         }
1630
1631         ret = True;
1632
1633   done:
1634
1635         /* allow winbindd lookups, but only if they weren't already disabled */
1636         if (!winbind_env) {
1637                 (void)winbind_on();
1638         }
1639
1640         return ret;
1641 }
1642
1643 static NTSTATUS pdb_default_enum_group_members(struct pdb_methods *methods,
1644                                                TALLOC_CTX *mem_ctx,
1645                                                const struct dom_sid *group,
1646                                                uint32_t **pp_member_rids,
1647                                                size_t *p_num_members)
1648 {
1649         gid_t gid;
1650         uid_t *uids;
1651         uint32_t i, num_uids;
1652
1653         *pp_member_rids = NULL;
1654         *p_num_members = 0;
1655
1656         if (!sid_to_gid(group, &gid))
1657                 return NT_STATUS_NO_SUCH_GROUP;
1658
1659         if(!get_memberuids(mem_ctx, gid, &uids, &num_uids))
1660                 return NT_STATUS_NO_SUCH_GROUP;
1661
1662         if (num_uids == 0)
1663                 return NT_STATUS_OK;
1664
1665         *pp_member_rids = talloc_zero_array(mem_ctx, uint32_t, num_uids);
1666
1667         for (i=0; i<num_uids; i++) {
1668                 struct dom_sid sid;
1669
1670                 uid_to_sid(&sid, uids[i]);
1671
1672                 if (!sid_check_is_in_our_sam(&sid)) {
1673                         DEBUG(5, ("Inconsistent SAM -- group member uid not "
1674                                   "in our domain\n"));
1675                         continue;
1676                 }
1677
1678                 sid_peek_rid(&sid, &(*pp_member_rids)[*p_num_members]);
1679                 *p_num_members += 1;
1680         }
1681
1682         return NT_STATUS_OK;
1683 }
1684
1685 static NTSTATUS pdb_default_enum_group_memberships(struct pdb_methods *methods,
1686                                                    TALLOC_CTX *mem_ctx,
1687                                                    struct samu *user,
1688                                                    struct dom_sid **pp_sids,
1689                                                    gid_t **pp_gids,
1690                                                    uint32_t *p_num_groups)
1691 {
1692         size_t i;
1693         gid_t gid;
1694         struct passwd *pw;
1695         const char *username = pdb_get_username(user);
1696
1697
1698         /* Ignore the primary group SID.  Honor the real Unix primary group.
1699            The primary group SID is only of real use to Windows clients */
1700
1701         if ( !(pw = Get_Pwnam_alloc(mem_ctx, username)) ) {
1702                 return NT_STATUS_NO_SUCH_USER;
1703         }
1704
1705         gid = pw->pw_gid;
1706
1707         TALLOC_FREE( pw );
1708
1709         if (!getgroups_unix_user(mem_ctx, username, gid, pp_gids, p_num_groups)) {
1710                 return NT_STATUS_NO_SUCH_USER;
1711         }
1712
1713         if (*p_num_groups == 0) {
1714                 smb_panic("primary group missing");
1715         }
1716
1717         *pp_sids = talloc_array(mem_ctx, struct dom_sid, *p_num_groups);
1718
1719         if (*pp_sids == NULL) {
1720                 TALLOC_FREE(*pp_gids);
1721                 return NT_STATUS_NO_MEMORY;
1722         }
1723
1724         for (i=0; i<*p_num_groups; i++) {
1725                 gid_to_sid(&(*pp_sids)[i], (*pp_gids)[i]);
1726         }
1727
1728         return NT_STATUS_OK;
1729 }
1730
1731 /*******************************************************************
1732  Look up a rid in the SAM we're responsible for (i.e. passdb)
1733  ********************************************************************/
1734
1735 static bool lookup_global_sam_rid(TALLOC_CTX *mem_ctx, uint32_t rid,
1736                                   const char **name,
1737                                   enum lsa_SidType *psid_name_use,
1738                                   uid_t *uid, gid_t *gid)
1739 {
1740         struct samu *sam_account = NULL;
1741         GROUP_MAP *map = NULL;
1742         bool ret;
1743         struct dom_sid sid;
1744
1745         *psid_name_use = SID_NAME_UNKNOWN;
1746
1747         DEBUG(5,("lookup_global_sam_rid: looking up RID %u.\n",
1748                  (unsigned int)rid));
1749
1750         sid_compose(&sid, get_global_sam_sid(), rid);
1751
1752         /* see if the passdb can help us with the name of the user */
1753
1754         if ( !(sam_account = samu_new( NULL )) ) {
1755                 return False;
1756         }
1757
1758         map = talloc_zero(mem_ctx, GROUP_MAP);
1759         if (!map) {
1760                 return false;
1761         }
1762
1763         /* BEING ROOT BLOCK */
1764         become_root();
1765         ret = pdb_getsampwsid(sam_account, &sid);
1766         if (!ret) {
1767                 TALLOC_FREE(sam_account);
1768                 ret = pdb_getgrsid(map, sid);
1769         }
1770         unbecome_root();
1771         /* END BECOME_ROOT BLOCK */
1772
1773         if (sam_account || !ret) {
1774                 TALLOC_FREE(map);
1775         }
1776
1777         if (sam_account) {
1778                 struct passwd *pw;
1779
1780                 *name = talloc_strdup(mem_ctx, pdb_get_username(sam_account));
1781                 if (!*name) {
1782                         TALLOC_FREE(sam_account);
1783                         return False;
1784                 }
1785
1786                 *psid_name_use = SID_NAME_USER;
1787
1788                 TALLOC_FREE(sam_account);
1789
1790                 if (uid == NULL) {
1791                         return True;
1792                 }
1793
1794                 pw = Get_Pwnam_alloc(talloc_tos(), *name);
1795                 if (pw == NULL) {
1796                         return False;
1797                 }
1798                 *uid = pw->pw_uid;
1799                 TALLOC_FREE(pw);
1800                 return True;
1801
1802         } else if (map && (map->gid != (gid_t)-1)) {
1803
1804                 /* do not resolve SIDs to a name unless there is a valid
1805                    gid associated with it */
1806
1807                 *name = talloc_steal(mem_ctx, map->nt_name);
1808                 *psid_name_use = map->sid_name_use;
1809
1810                 if (gid) {
1811                         *gid = map->gid;
1812                 }
1813
1814                 TALLOC_FREE(map);
1815                 return True;
1816         }
1817
1818         TALLOC_FREE(map);
1819
1820         /* Windows will always map RID 513 to something.  On a non-domain 
1821            controller, this gets mapped to SERVER\None. */
1822
1823         if (uid || gid) {
1824                 DEBUG(5, ("Can't find a unix id for an unmapped group\n"));
1825                 return False;
1826         }
1827
1828         if ( rid == DOMAIN_RID_USERS ) {
1829                 *name = talloc_strdup(mem_ctx, "None" );
1830                 *psid_name_use = SID_NAME_DOM_GRP;
1831
1832                 return True;
1833         }
1834
1835         return False;
1836 }
1837
1838 static NTSTATUS pdb_default_lookup_rids(struct pdb_methods *methods,
1839                                         const struct dom_sid *domain_sid,
1840                                         int num_rids,
1841                                         uint32_t *rids,
1842                                         const char **names,
1843                                         enum lsa_SidType *attrs)
1844 {
1845         int i;
1846         NTSTATUS result;
1847         bool have_mapped = False;
1848         bool have_unmapped = False;
1849
1850         if (sid_check_is_builtin(domain_sid)) {
1851
1852                 for (i=0; i<num_rids; i++) {
1853                         const char *name;
1854
1855                         if (lookup_builtin_rid(names, rids[i], &name)) {
1856                                 attrs[i] = SID_NAME_ALIAS;
1857                                 names[i] = name;
1858                                 DEBUG(5,("lookup_rids: %s:%d\n",
1859                                          names[i], attrs[i]));
1860                                 have_mapped = True;
1861                         } else {
1862                                 have_unmapped = True;
1863                                 attrs[i] = SID_NAME_UNKNOWN;
1864                         }
1865                 }
1866                 goto done;
1867         }
1868
1869         /* Should not happen, but better check once too many */
1870         if (!sid_check_is_our_sam(domain_sid)) {
1871                 return NT_STATUS_INVALID_HANDLE;
1872         }
1873
1874         for (i = 0; i < num_rids; i++) {
1875                 const char *name;
1876
1877                 if (lookup_global_sam_rid(names, rids[i], &name, &attrs[i],
1878                                           NULL, NULL)) {
1879                         if (name == NULL) {
1880                                 return NT_STATUS_NO_MEMORY;
1881                         }
1882                         names[i] = name;
1883                         DEBUG(5,("lookup_rids: %s:%d\n", names[i], attrs[i]));
1884                         have_mapped = True;
1885                 } else {
1886                         have_unmapped = True;
1887                         attrs[i] = SID_NAME_UNKNOWN;
1888                 }
1889         }
1890
1891  done:
1892
1893         result = NT_STATUS_NONE_MAPPED;
1894
1895         if (have_mapped)
1896                 result = have_unmapped ? STATUS_SOME_UNMAPPED : NT_STATUS_OK;
1897
1898         return result;
1899 }
1900
1901 static int pdb_search_destructor(struct pdb_search *search)
1902 {
1903         if ((!search->search_ended) && (search->search_end != NULL)) {
1904                 search->search_end(search);
1905         }
1906         return 0;
1907 }
1908
1909 struct pdb_search *pdb_search_init(TALLOC_CTX *mem_ctx,
1910                                    enum pdb_search_type type)
1911 {
1912         struct pdb_search *result;
1913
1914         result = talloc(mem_ctx, struct pdb_search);
1915         if (result == NULL) {
1916                 DEBUG(0, ("talloc failed\n"));
1917                 return NULL;
1918         }
1919
1920         result->type = type;
1921         result->cache = NULL;
1922         result->num_entries = 0;
1923         result->cache_size = 0;
1924         result->search_ended = False;
1925         result->search_end = NULL;
1926
1927         /* Segfault appropriately if not initialized */
1928         result->next_entry = NULL;
1929         result->search_end = NULL;
1930
1931         talloc_set_destructor(result, pdb_search_destructor);
1932
1933         return result;
1934 }
1935
1936 static void fill_displayentry(TALLOC_CTX *mem_ctx, uint32_t rid,
1937                               uint16_t acct_flags,
1938                               const char *account_name,
1939                               const char *fullname,
1940                               const char *description,
1941                               struct samr_displayentry *entry)
1942 {
1943         entry->rid = rid;
1944         entry->acct_flags = acct_flags;
1945
1946         if (account_name != NULL)
1947                 entry->account_name = talloc_strdup(mem_ctx, account_name);
1948         else
1949                 entry->account_name = "";
1950
1951         if (fullname != NULL)
1952                 entry->fullname = talloc_strdup(mem_ctx, fullname);
1953         else
1954                 entry->fullname = "";
1955
1956         if (description != NULL)
1957                 entry->description = talloc_strdup(mem_ctx, description);
1958         else
1959                 entry->description = "";
1960 }
1961
1962 struct group_search {
1963         GROUP_MAP **groups;
1964         size_t num_groups, current_group;
1965 };
1966
1967 static bool next_entry_groups(struct pdb_search *s,
1968                               struct samr_displayentry *entry)
1969 {
1970         struct group_search *state = (struct group_search *)s->private_data;
1971         uint32_t rid;
1972         GROUP_MAP *map;
1973
1974         if (state->current_group == state->num_groups)
1975                 return False;
1976
1977         map = state->groups[state->current_group];
1978
1979         sid_peek_rid(&map->sid, &rid);
1980
1981         fill_displayentry(s, rid, 0, map->nt_name, NULL, map->comment, entry);
1982
1983         state->current_group += 1;
1984         return True;
1985 }
1986
1987 static void search_end_groups(struct pdb_search *search)
1988 {
1989         struct group_search *state =
1990                 (struct group_search *)search->private_data;
1991         TALLOC_FREE(state->groups);
1992 }
1993
1994 static bool pdb_search_grouptype(struct pdb_methods *methods,
1995                                  struct pdb_search *search,
1996                                  const struct dom_sid *sid, enum lsa_SidType type)
1997 {
1998         struct group_search *state;
1999
2000         state = talloc_zero(search, struct group_search);
2001         if (state == NULL) {
2002                 DEBUG(0, ("talloc failed\n"));
2003                 return False;
2004         }
2005
2006         if (!NT_STATUS_IS_OK(methods->enum_group_mapping(methods, sid, type, 
2007                                                          &state->groups, &state->num_groups,
2008                                                          True))) {
2009                 DEBUG(0, ("Could not enum groups\n"));
2010                 return False;
2011         }
2012
2013         state->current_group = 0;
2014         search->private_data = state;
2015         search->next_entry = next_entry_groups;
2016         search->search_end = search_end_groups;
2017         return True;
2018 }
2019
2020 static bool pdb_default_search_groups(struct pdb_methods *methods,
2021                                       struct pdb_search *search)
2022 {
2023         return pdb_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
2024 }
2025
2026 static bool pdb_default_search_aliases(struct pdb_methods *methods,
2027                                        struct pdb_search *search,
2028                                        const struct dom_sid *sid)
2029 {
2030
2031         return pdb_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
2032 }
2033
2034 static struct samr_displayentry *pdb_search_getentry(struct pdb_search *search,
2035                                                      uint32_t idx)
2036 {
2037         if (idx < search->num_entries)
2038                 return &search->cache[idx];
2039
2040         if (search->search_ended)
2041                 return NULL;
2042
2043         while (idx >= search->num_entries) {
2044                 struct samr_displayentry entry;
2045
2046                 if (!search->next_entry(search, &entry)) {
2047                         search->search_end(search);
2048                         search->search_ended = True;
2049                         break;
2050                 }
2051
2052                 ADD_TO_LARGE_ARRAY(search, struct samr_displayentry,
2053                                    entry, &search->cache, &search->num_entries,
2054                                    &search->cache_size);
2055         }
2056
2057         return (search->num_entries > idx) ? &search->cache[idx] : NULL;
2058 }
2059
2060 struct pdb_search *pdb_search_users(TALLOC_CTX *mem_ctx, uint32_t acct_flags)
2061 {
2062         struct pdb_methods *pdb = pdb_get_methods();
2063         struct pdb_search *result;
2064
2065         result = pdb_search_init(mem_ctx, PDB_USER_SEARCH);
2066         if (result == NULL) {
2067                 return NULL;
2068         }
2069
2070         if (!pdb->search_users(pdb, result, acct_flags)) {
2071                 TALLOC_FREE(result);
2072                 return NULL;
2073         }
2074         return result;
2075 }
2076
2077 struct pdb_search *pdb_search_groups(TALLOC_CTX *mem_ctx)
2078 {
2079         struct pdb_methods *pdb = pdb_get_methods();
2080         struct pdb_search *result;
2081
2082         result = pdb_search_init(mem_ctx, PDB_GROUP_SEARCH);
2083         if (result == NULL) {
2084                  return NULL;
2085         }
2086
2087         if (!pdb->search_groups(pdb, result)) {
2088                 TALLOC_FREE(result);
2089                 return NULL;
2090         }
2091         return result;
2092 }
2093
2094 struct pdb_search *pdb_search_aliases(TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
2095 {
2096         struct pdb_methods *pdb = pdb_get_methods();
2097         struct pdb_search *result;
2098
2099         if (pdb == NULL) return NULL;
2100
2101         result = pdb_search_init(mem_ctx, PDB_ALIAS_SEARCH);
2102         if (result == NULL) {
2103                 return NULL;
2104         }
2105
2106         if (!pdb->search_aliases(pdb, result, sid)) {
2107                 TALLOC_FREE(result);
2108                 return NULL;
2109         }
2110         return result;
2111 }
2112
2113 uint32_t pdb_search_entries(struct pdb_search *search,
2114                           uint32_t start_idx, uint32_t max_entries,
2115                           struct samr_displayentry **result)
2116 {
2117         struct samr_displayentry *end_entry;
2118         uint32_t end_idx = start_idx+max_entries-1;
2119
2120         /* The first entry needs to be searched after the last. Otherwise the
2121          * first entry might have moved due to a realloc during the search for
2122          * the last entry. */
2123
2124         end_entry = pdb_search_getentry(search, end_idx);
2125         *result = pdb_search_getentry(search, start_idx);
2126
2127         if (end_entry != NULL)
2128                 return max_entries;
2129
2130         if (start_idx >= search->num_entries)
2131                 return 0;
2132
2133         return search->num_entries - start_idx;
2134 }
2135
2136 /*******************************************************************
2137  trustdom methods
2138  *******************************************************************/
2139
2140 bool pdb_get_trusteddom_pw(const char *domain, char** pwd, struct dom_sid *sid,
2141                            time_t *pass_last_set_time)
2142 {
2143         struct pdb_methods *pdb = pdb_get_methods();
2144         return pdb->get_trusteddom_pw(pdb, domain, pwd, sid, 
2145                         pass_last_set_time);
2146 }
2147
2148 NTSTATUS pdb_get_trusteddom_creds(const char *domain, TALLOC_CTX *mem_ctx,
2149                                   struct cli_credentials **creds)
2150 {
2151         struct pdb_methods *pdb = pdb_get_methods();
2152         return pdb->get_trusteddom_creds(pdb, domain, mem_ctx, creds);
2153 }
2154
2155 bool pdb_set_trusteddom_pw(const char* domain, const char* pwd,
2156                            const struct dom_sid *sid)
2157 {
2158         struct pdb_methods *pdb = pdb_get_methods();
2159         return pdb->set_trusteddom_pw(pdb, domain, pwd, sid);
2160 }
2161
2162 bool pdb_del_trusteddom_pw(const char *domain)
2163 {
2164         struct pdb_methods *pdb = pdb_get_methods();
2165         return pdb->del_trusteddom_pw(pdb, domain);
2166 }
2167
2168 NTSTATUS pdb_enum_trusteddoms(TALLOC_CTX *mem_ctx, uint32_t *num_domains,
2169                               struct trustdom_info ***domains)
2170 {
2171         struct pdb_methods *pdb = pdb_get_methods();
2172         return pdb->enum_trusteddoms(pdb, mem_ctx, num_domains, domains);
2173 }
2174
2175 /*******************************************************************
2176  the defaults for trustdom methods: 
2177  these simply call the original passdb/secrets.c actions,
2178  to be replaced by pdb_ldap.
2179  *******************************************************************/
2180
2181 static bool pdb_default_get_trusteddom_pw(struct pdb_methods *methods,
2182                                           const char *domain, 
2183                                           char** pwd, 
2184                                           struct dom_sid *sid,
2185                                           time_t *pass_last_set_time)
2186 {
2187         return secrets_fetch_trusted_domain_password(domain, pwd,
2188                                 sid, pass_last_set_time);
2189
2190 }
2191
2192 static NTSTATUS pdb_default_get_trusteddom_creds(struct pdb_methods *methods,
2193                                                  const char *domain,
2194                                                  TALLOC_CTX *mem_ctx,
2195                                                  struct cli_credentials **creds)
2196 {
2197         *creds = NULL;
2198         return NT_STATUS_NOT_IMPLEMENTED;
2199 }
2200
2201 static bool pdb_default_set_trusteddom_pw(struct pdb_methods *methods, 
2202                                           const char* domain, 
2203                                           const char* pwd,
2204                                           const struct dom_sid *sid)
2205 {
2206         return secrets_store_trusted_domain_password(domain, pwd, sid);
2207 }
2208
2209 static bool pdb_default_del_trusteddom_pw(struct pdb_methods *methods, 
2210                                           const char *domain)
2211 {
2212         return trusted_domain_password_delete(domain);
2213 }
2214
2215 static NTSTATUS pdb_default_enum_trusteddoms(struct pdb_methods *methods,
2216                                              TALLOC_CTX *mem_ctx, 
2217                                              uint32_t *num_domains,
2218                                              struct trustdom_info ***domains)
2219 {
2220         return secrets_trusted_domains(mem_ctx, num_domains, domains);
2221 }
2222
2223 /*******************************************************************
2224  trusted_domain methods
2225  *******************************************************************/
2226
2227 NTSTATUS pdb_get_trusted_domain(TALLOC_CTX *mem_ctx, const char *domain,
2228                                 struct pdb_trusted_domain **td)
2229 {
2230         struct pdb_methods *pdb = pdb_get_methods();
2231         return pdb->get_trusted_domain(pdb, mem_ctx, domain, td);
2232 }
2233
2234 NTSTATUS pdb_get_trusted_domain_by_sid(TALLOC_CTX *mem_ctx, struct dom_sid *sid,
2235                                 struct pdb_trusted_domain **td)
2236 {
2237         struct pdb_methods *pdb = pdb_get_methods();
2238         return pdb->get_trusted_domain_by_sid(pdb, mem_ctx, sid, td);
2239 }
2240
2241 NTSTATUS pdb_set_trusted_domain(const char* domain,
2242                                 const struct pdb_trusted_domain *td)
2243 {
2244         struct pdb_methods *pdb = pdb_get_methods();
2245         return pdb->set_trusted_domain(pdb, domain, td);
2246 }
2247
2248 NTSTATUS pdb_del_trusted_domain(const char *domain)
2249 {
2250         struct pdb_methods *pdb = pdb_get_methods();
2251         return pdb->del_trusted_domain(pdb, domain);
2252 }
2253
2254 NTSTATUS pdb_enum_trusted_domains(TALLOC_CTX *mem_ctx, uint32_t *num_domains,
2255                                   struct pdb_trusted_domain ***domains)
2256 {
2257         struct pdb_methods *pdb = pdb_get_methods();
2258         return pdb->enum_trusted_domains(pdb, mem_ctx, num_domains, domains);
2259 }
2260
2261 static NTSTATUS pdb_default_get_trusted_domain(struct pdb_methods *methods,
2262                                                TALLOC_CTX *mem_ctx,
2263                                                const char *domain,
2264                                                struct pdb_trusted_domain **td)
2265 {
2266         struct trustAuthInOutBlob taiob;
2267         struct AuthenticationInformation aia;
2268         struct pdb_trusted_domain *tdom;
2269         enum ndr_err_code ndr_err;
2270         time_t last_set_time;
2271         char *pwd;
2272         bool ok;
2273
2274         tdom = talloc(mem_ctx, struct pdb_trusted_domain);
2275         if (!tdom) {
2276                 return NT_STATUS_NO_MEMORY;
2277         }
2278
2279         tdom->domain_name = talloc_strdup(tdom, domain);
2280         tdom->netbios_name = talloc_strdup(tdom, domain);
2281         if (!tdom->domain_name || !tdom->netbios_name) {
2282                 talloc_free(tdom);
2283                 return NT_STATUS_NO_MEMORY;
2284         }
2285
2286         tdom->trust_auth_incoming = data_blob_null;
2287
2288         ok = pdb_get_trusteddom_pw(domain, &pwd, &tdom->security_identifier,
2289                                    &last_set_time);
2290         if (!ok) {
2291                 talloc_free(tdom);
2292                 return NT_STATUS_UNSUCCESSFUL;
2293         }
2294
2295         ZERO_STRUCT(taiob);
2296         ZERO_STRUCT(aia);
2297         taiob.count = 1;
2298         taiob.current.count = 1;
2299         taiob.current.array = &aia;
2300         unix_to_nt_time(&aia.LastUpdateTime, last_set_time);
2301
2302         aia.AuthType = TRUST_AUTH_TYPE_CLEAR;
2303         aia.AuthInfo.clear.size = strlen(pwd);
2304         aia.AuthInfo.clear.password = (uint8_t *)talloc_memdup(tdom, pwd,
2305                                                                aia.AuthInfo.clear.size);
2306         SAFE_FREE(pwd);
2307         if (aia.AuthInfo.clear.password == NULL) {
2308                 talloc_free(tdom);
2309                 return NT_STATUS_NO_MEMORY;
2310         }
2311
2312         taiob.previous.count = 0;
2313         taiob.previous.array = NULL;
2314
2315         ndr_err = ndr_push_struct_blob(&tdom->trust_auth_outgoing,
2316                                         tdom, &taiob,
2317                         (ndr_push_flags_fn_t)ndr_push_trustAuthInOutBlob);
2318         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2319                 talloc_free(tdom);
2320                 return NT_STATUS_UNSUCCESSFUL;
2321         }
2322
2323         tdom->trust_direction = LSA_TRUST_DIRECTION_OUTBOUND;
2324         tdom->trust_type = LSA_TRUST_TYPE_DOWNLEVEL;
2325         tdom->trust_attributes = 0;
2326         tdom->trust_forest_trust_info = data_blob_null;
2327
2328         *td = tdom;
2329         return NT_STATUS_OK;
2330 }
2331
2332 static NTSTATUS pdb_default_get_trusted_domain_by_sid(struct pdb_methods *methods,
2333                                                       TALLOC_CTX *mem_ctx,
2334                                                       struct dom_sid *sid,
2335                                                       struct pdb_trusted_domain **td)
2336 {
2337         return NT_STATUS_NOT_IMPLEMENTED;
2338 }
2339
2340 #define IS_NULL_DATA_BLOB(d) ((d).data == NULL && (d).length == 0)
2341
2342 static NTSTATUS pdb_default_set_trusted_domain(struct pdb_methods *methods,
2343                                                const char* domain,
2344                                                const struct pdb_trusted_domain *td)
2345 {
2346         struct trustAuthInOutBlob taiob;
2347         struct AuthenticationInformation *aia;
2348         enum ndr_err_code ndr_err;
2349         char *pwd;
2350         bool ok;
2351
2352         if (td->trust_attributes != 0 ||
2353             td->trust_type != LSA_TRUST_TYPE_DOWNLEVEL ||
2354             td->trust_direction != LSA_TRUST_DIRECTION_OUTBOUND ||
2355             !IS_NULL_DATA_BLOB(td->trust_auth_incoming) ||
2356             !IS_NULL_DATA_BLOB(td->trust_forest_trust_info)) {
2357             return NT_STATUS_NOT_IMPLEMENTED;
2358         }
2359
2360         ZERO_STRUCT(taiob);
2361         ndr_err = ndr_pull_struct_blob(&td->trust_auth_outgoing, talloc_tos(),
2362                               &taiob,
2363                               (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2364         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2365                 return NT_STATUS_UNSUCCESSFUL;
2366         }
2367
2368         aia = (struct AuthenticationInformation *) taiob.current.array;
2369
2370         if (taiob.count != 1 || taiob.current.count != 1 ||
2371             taiob.previous.count != 0 ||
2372             aia->AuthType != TRUST_AUTH_TYPE_CLEAR) {
2373             return NT_STATUS_NOT_IMPLEMENTED;
2374         }
2375
2376         pwd = talloc_strndup(talloc_tos(), (char *) aia->AuthInfo.clear.password,
2377                              aia->AuthInfo.clear.size);
2378         if (!pwd) {
2379                 return NT_STATUS_NO_MEMORY;
2380         }
2381
2382         ok = pdb_set_trusteddom_pw(domain, pwd, &td->security_identifier);
2383         if (!ok) {
2384                 return NT_STATUS_UNSUCCESSFUL;
2385         }
2386
2387         return NT_STATUS_OK;
2388 }
2389
2390 static NTSTATUS pdb_default_del_trusted_domain(struct pdb_methods *methods,
2391                                                const char *domain)
2392 {
2393         return NT_STATUS_NOT_IMPLEMENTED;
2394 }
2395
2396 static NTSTATUS pdb_default_enum_trusted_domains(struct pdb_methods *methods,
2397                                                  TALLOC_CTX *mem_ctx,
2398                                                  uint32_t *num_domains,
2399                                                  struct pdb_trusted_domain ***domains)
2400 {
2401         return NT_STATUS_NOT_IMPLEMENTED;
2402 }
2403
2404 static struct pdb_domain_info *pdb_default_get_domain_info(
2405         struct pdb_methods *m, TALLOC_CTX *mem_ctx)
2406 {
2407         return NULL;
2408 }
2409
2410 /*****************************************************************
2411  UPN suffixes
2412  *****************************************************************/
2413 static NTSTATUS pdb_default_enum_upn_suffixes(struct pdb_methods *pdb,
2414                                               TALLOC_CTX *mem_ctx,
2415                                               uint32_t *num_suffixes,
2416                                               char ***suffixes)
2417 {
2418         return NT_STATUS_NOT_IMPLEMENTED;
2419 }
2420
2421 static NTSTATUS pdb_default_set_upn_suffixes(struct pdb_methods *pdb,
2422                                              uint32_t num_suffixes,
2423                                              const char **suffixes)
2424 {
2425         return NT_STATUS_NOT_IMPLEMENTED;
2426 }
2427
2428 NTSTATUS pdb_enum_upn_suffixes(TALLOC_CTX *mem_ctx,
2429                                uint32_t *num_suffixes,
2430                                char ***suffixes)
2431 {
2432         struct pdb_methods *pdb = pdb_get_methods();
2433         return pdb->enum_upn_suffixes(pdb, mem_ctx, num_suffixes, suffixes);
2434 }
2435
2436 NTSTATUS pdb_set_upn_suffixes(uint32_t num_suffixes,
2437                               const char **suffixes)
2438 {
2439         struct pdb_methods *pdb = pdb_get_methods();
2440         return pdb->set_upn_suffixes(pdb, num_suffixes, suffixes);
2441 }
2442
2443 /*******************************************************************
2444  idmap control methods
2445  *******************************************************************/
2446 static bool pdb_default_is_responsible_for_our_sam(
2447                                         struct pdb_methods *methods)
2448 {
2449         return true;
2450 }
2451
2452 static bool pdb_default_is_responsible_for_builtin(
2453                                         struct pdb_methods *methods)
2454 {
2455         return true;
2456 }
2457
2458 static bool pdb_default_is_responsible_for_wellknown(
2459                                         struct pdb_methods *methods)
2460 {
2461         return false;
2462 }
2463
2464 static bool pdb_default_is_responsible_for_unix_users(
2465                                         struct pdb_methods *methods)
2466 {
2467         return true;
2468 }
2469
2470 static bool pdb_default_is_responsible_for_unix_groups(
2471                                         struct pdb_methods *methods)
2472 {
2473         return true;
2474 }
2475
2476 static bool pdb_default_is_responsible_for_everything_else(
2477                                         struct pdb_methods *methods)
2478 {
2479         return false;
2480 }
2481
2482 bool pdb_is_responsible_for_our_sam(void)
2483 {
2484         struct pdb_methods *pdb = pdb_get_methods();
2485         return pdb->is_responsible_for_our_sam(pdb);
2486 }
2487
2488 bool pdb_is_responsible_for_builtin(void)
2489 {
2490         struct pdb_methods *pdb = pdb_get_methods();
2491         return pdb->is_responsible_for_builtin(pdb);
2492 }
2493
2494 bool pdb_is_responsible_for_wellknown(void)
2495 {
2496         struct pdb_methods *pdb = pdb_get_methods();
2497         return pdb->is_responsible_for_wellknown(pdb);
2498 }
2499
2500 bool pdb_is_responsible_for_unix_users(void)
2501 {
2502         struct pdb_methods *pdb = pdb_get_methods();
2503         return pdb->is_responsible_for_unix_users(pdb);
2504 }
2505
2506 bool pdb_is_responsible_for_unix_groups(void)
2507 {
2508         struct pdb_methods *pdb = pdb_get_methods();
2509         return pdb->is_responsible_for_unix_groups(pdb);
2510 }
2511
2512 bool pdb_is_responsible_for_everything_else(void)
2513 {
2514         struct pdb_methods *pdb = pdb_get_methods();
2515         return pdb->is_responsible_for_everything_else(pdb);
2516 }
2517
2518 /*******************************************************************
2519  secret methods
2520  *******************************************************************/
2521
2522 NTSTATUS pdb_get_secret(TALLOC_CTX *mem_ctx,
2523                         const char *secret_name,
2524                         DATA_BLOB *secret_current,
2525                         NTTIME *secret_current_lastchange,
2526                         DATA_BLOB *secret_old,
2527                         NTTIME *secret_old_lastchange,
2528                         struct security_descriptor **sd)
2529 {
2530         struct pdb_methods *pdb = pdb_get_methods();
2531         return pdb->get_secret(pdb, mem_ctx, secret_name,
2532                                secret_current, secret_current_lastchange,
2533                                secret_old, secret_old_lastchange,
2534                                sd);
2535 }
2536
2537 NTSTATUS pdb_set_secret(const char *secret_name,
2538                         DATA_BLOB *secret_current,
2539                         DATA_BLOB *secret_old,
2540                         struct security_descriptor *sd)
2541 {
2542         struct pdb_methods *pdb = pdb_get_methods();
2543         return pdb->set_secret(pdb, secret_name,
2544                                secret_current,
2545                                secret_old,
2546                                sd);
2547 }
2548
2549 NTSTATUS pdb_delete_secret(const char *secret_name)
2550 {
2551         struct pdb_methods *pdb = pdb_get_methods();
2552         return pdb->delete_secret(pdb, secret_name);
2553 }
2554
2555 static NTSTATUS pdb_default_get_secret(struct pdb_methods *methods,
2556                                        TALLOC_CTX *mem_ctx,
2557                                        const char *secret_name,
2558                                        DATA_BLOB *secret_current,
2559                                        NTTIME *secret_current_lastchange,
2560                                        DATA_BLOB *secret_old,
2561                                        NTTIME *secret_old_lastchange,
2562                                        struct security_descriptor **sd)
2563 {
2564         return lsa_secret_get(mem_ctx, secret_name,
2565                               secret_current,
2566                               secret_current_lastchange,
2567                               secret_old,
2568                               secret_old_lastchange,
2569                               sd);
2570 }
2571
2572 static NTSTATUS pdb_default_set_secret(struct pdb_methods *methods,
2573                                        const char *secret_name,
2574                                        DATA_BLOB *secret_current,
2575                                        DATA_BLOB *secret_old,
2576                                        struct security_descriptor *sd)
2577 {
2578         return lsa_secret_set(secret_name,
2579                               secret_current,
2580                               secret_old,
2581                               sd);
2582 }
2583
2584 static NTSTATUS pdb_default_delete_secret(struct pdb_methods *methods,
2585                                           const char *secret_name)
2586 {
2587         return lsa_secret_delete(secret_name);
2588 }
2589
2590 /*******************************************************************
2591  Create a pdb_methods structure and initialize it with the default
2592  operations.  In this way a passdb module can simply implement
2593  the functionality it cares about.  However, normally this is done 
2594  in groups of related functions.
2595 *******************************************************************/
2596
2597 NTSTATUS make_pdb_method( struct pdb_methods **methods ) 
2598 {
2599         /* allocate memory for the structure as its own talloc CTX */
2600
2601         *methods = talloc_zero(NULL, struct pdb_methods);
2602         if (*methods == NULL) {
2603                 return NT_STATUS_NO_MEMORY;
2604         }
2605
2606         (*methods)->get_domain_info = pdb_default_get_domain_info;
2607         (*methods)->getsampwnam = pdb_default_getsampwnam;
2608         (*methods)->getsampwsid = pdb_default_getsampwsid;
2609         (*methods)->create_user = pdb_default_create_user;
2610         (*methods)->delete_user = pdb_default_delete_user;
2611         (*methods)->add_sam_account = pdb_default_add_sam_account;
2612         (*methods)->update_sam_account = pdb_default_update_sam_account;
2613         (*methods)->delete_sam_account = pdb_default_delete_sam_account;
2614         (*methods)->rename_sam_account = pdb_default_rename_sam_account;
2615         (*methods)->update_login_attempts = pdb_default_update_login_attempts;
2616
2617         (*methods)->getgrsid = pdb_default_getgrsid;
2618         (*methods)->getgrgid = pdb_default_getgrgid;
2619         (*methods)->getgrnam = pdb_default_getgrnam;
2620         (*methods)->create_dom_group = pdb_default_create_dom_group;
2621         (*methods)->delete_dom_group = pdb_default_delete_dom_group;
2622         (*methods)->add_group_mapping_entry = pdb_default_add_group_mapping_entry;
2623         (*methods)->update_group_mapping_entry = pdb_default_update_group_mapping_entry;
2624         (*methods)->delete_group_mapping_entry = pdb_default_delete_group_mapping_entry;
2625         (*methods)->enum_group_mapping = pdb_default_enum_group_mapping;
2626         (*methods)->enum_group_members = pdb_default_enum_group_members;
2627         (*methods)->enum_group_memberships = pdb_default_enum_group_memberships;
2628         (*methods)->set_unix_primary_group = pdb_default_set_unix_primary_group;
2629         (*methods)->add_groupmem = pdb_default_add_groupmem;
2630         (*methods)->del_groupmem = pdb_default_del_groupmem;
2631         (*methods)->create_alias = pdb_default_create_alias;
2632         (*methods)->delete_alias = pdb_default_delete_alias;
2633         (*methods)->get_aliasinfo = pdb_default_get_aliasinfo;
2634         (*methods)->set_aliasinfo = pdb_default_set_aliasinfo;
2635         (*methods)->add_aliasmem = pdb_default_add_aliasmem;
2636         (*methods)->del_aliasmem = pdb_default_del_aliasmem;
2637         (*methods)->enum_aliasmem = pdb_default_enum_aliasmem;
2638         (*methods)->enum_alias_memberships = pdb_default_alias_memberships;
2639         (*methods)->lookup_rids = pdb_default_lookup_rids;
2640         (*methods)->get_account_policy = pdb_default_get_account_policy;
2641         (*methods)->set_account_policy = pdb_default_set_account_policy;
2642         (*methods)->get_seq_num = pdb_default_get_seq_num;
2643         (*methods)->id_to_sid = pdb_default_id_to_sid;
2644         (*methods)->sid_to_id = pdb_default_sid_to_id;
2645
2646         (*methods)->search_groups = pdb_default_search_groups;
2647         (*methods)->search_aliases = pdb_default_search_aliases;
2648
2649         (*methods)->get_trusteddom_pw = pdb_default_get_trusteddom_pw;
2650         (*methods)->get_trusteddom_creds = pdb_default_get_trusteddom_creds;
2651         (*methods)->set_trusteddom_pw = pdb_default_set_trusteddom_pw;
2652         (*methods)->del_trusteddom_pw = pdb_default_del_trusteddom_pw;
2653         (*methods)->enum_trusteddoms  = pdb_default_enum_trusteddoms;
2654
2655         (*methods)->get_trusted_domain = pdb_default_get_trusted_domain;
2656         (*methods)->get_trusted_domain_by_sid = pdb_default_get_trusted_domain_by_sid;
2657         (*methods)->set_trusted_domain = pdb_default_set_trusted_domain;
2658         (*methods)->del_trusted_domain = pdb_default_del_trusted_domain;
2659         (*methods)->enum_trusted_domains = pdb_default_enum_trusted_domains;
2660
2661         (*methods)->get_secret = pdb_default_get_secret;
2662         (*methods)->set_secret = pdb_default_set_secret;
2663         (*methods)->delete_secret = pdb_default_delete_secret;
2664
2665         (*methods)->enum_upn_suffixes = pdb_default_enum_upn_suffixes;
2666         (*methods)->set_upn_suffixes  = pdb_default_set_upn_suffixes;
2667
2668         (*methods)->is_responsible_for_our_sam =
2669                                 pdb_default_is_responsible_for_our_sam;
2670         (*methods)->is_responsible_for_builtin =
2671                                 pdb_default_is_responsible_for_builtin;
2672         (*methods)->is_responsible_for_wellknown =
2673                                 pdb_default_is_responsible_for_wellknown;
2674         (*methods)->is_responsible_for_unix_users =
2675                                 pdb_default_is_responsible_for_unix_users;
2676         (*methods)->is_responsible_for_unix_groups =
2677                                 pdb_default_is_responsible_for_unix_groups;
2678         (*methods)->is_responsible_for_everything_else =
2679                                 pdb_default_is_responsible_for_everything_else;
2680
2681         return NT_STATUS_OK;
2682 }