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