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