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