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