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