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