Rename pdb_ldap to pdb_ldapsam
[Samba.git] / source3 / passdb / pdb_ldap.c
blob7ae9056d181752dfeca1ab9a75b8f2a5042a9329
1 /*
2 Unix SMB/CIFS implementation.
3 LDAP protocol helper functions for SAMBA
4 Copyright (C) Jean François Micouleau 1998
5 Copyright (C) Gerald Carter 2001-2003
6 Copyright (C) Shahms King 2001
7 Copyright (C) Andrew Bartlett 2002-2003
8 Copyright (C) Stefan (metze) Metzmacher 2002-2003
9 Copyright (C) Simo Sorce 2006
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 /* TODO:
27 * persistent connections: if using NSS LDAP, many connections are made
28 * however, using only one within Samba would be nice
30 * Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
32 * Other LDAP based login attributes: accountExpires, etc.
33 * (should be the domain of Samba proper, but the sam_password/struct samu
34 * structures don't have fields for some of these attributes)
36 * SSL is done, but can't get the certificate based authentication to work
37 * against on my test platform (Linux 2.4, OpenLDAP 2.x)
40 /* NOTE: this will NOT work against an Active Directory server
41 * due to the fact that the two password fields cannot be retrieved
42 * from a server; recommend using security = domain in this situation
43 * and/or winbind
46 #include "includes.h"
47 #include "passdb.h"
48 #include "../libcli/auth/libcli_auth.h"
49 #include "secrets.h"
50 #include "idmap_cache.h"
51 #include "../libcli/security/security.h"
52 #include "../lib/util/util_pw.h"
53 #include "lib/winbind_util.h"
54 #include "librpc/gen_ndr/idmap.h"
55 #include "lib/param/loadparm.h"
56 #include "lib/util_sid_passdb.h"
58 #undef DBGC_CLASS
59 #define DBGC_CLASS DBGC_PASSDB
61 #include <lber.h>
62 #include <ldap.h>
65 #include "smbldap.h"
66 #include "passdb/pdb_ldap.h"
67 #include "passdb/pdb_nds.h"
68 #include "passdb/pdb_ipa.h"
69 #include "passdb/pdb_ldap_util.h"
70 #include "passdb/pdb_ldap_schema.h"
72 /**********************************************************************
73 Simple helper function to make stuff better readable
74 **********************************************************************/
76 LDAP *priv2ld(struct ldapsam_privates *priv)
78 return priv->smbldap_state->ldap_struct;
81 /**********************************************************************
82 Get the attribute name given a user schame version.
83 **********************************************************************/
85 static const char* get_userattr_key2string( int schema_ver, int key )
87 switch ( schema_ver ) {
88 case SCHEMAVER_SAMBASAMACCOUNT:
89 return get_attr_key2string( attrib_map_v30, key );
91 default:
92 DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
93 break;
95 return NULL;
98 /**********************************************************************
99 Return the list of attribute names given a user schema version.
100 **********************************************************************/
102 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
104 switch ( schema_ver ) {
105 case SCHEMAVER_SAMBASAMACCOUNT:
106 return get_attr_list( mem_ctx, attrib_map_v30 );
107 default:
108 DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
109 break;
112 return NULL;
115 /**************************************************************************
116 Return the list of attribute names to delete given a user schema version.
117 **************************************************************************/
119 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
120 int schema_ver )
122 switch ( schema_ver ) {
123 case SCHEMAVER_SAMBASAMACCOUNT:
124 return get_attr_list( mem_ctx,
125 attrib_map_to_delete_v30 );
126 default:
127 DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
128 break;
131 return NULL;
135 /*******************************************************************
136 Generate the LDAP search filter for the objectclass based on the
137 version of the schema we are using.
138 ******************************************************************/
140 static const char* get_objclass_filter( int schema_ver )
142 fstring objclass_filter;
143 char *result;
145 switch( schema_ver ) {
146 case SCHEMAVER_SAMBASAMACCOUNT:
147 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
148 break;
149 default:
150 DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
151 objclass_filter[0] = '\0';
152 break;
155 result = talloc_strdup(talloc_tos(), objclass_filter);
156 SMB_ASSERT(result != NULL);
157 return result;
160 /*****************************************************************
161 Scan a sequence number off OpenLDAP's syncrepl contextCSN
162 ******************************************************************/
164 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
166 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
167 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
168 LDAPMessage *msg = NULL;
169 LDAPMessage *entry = NULL;
170 TALLOC_CTX *mem_ctx;
171 char **values = NULL;
172 int rc, num_result, num_values, rid;
173 char *suffix = NULL;
174 char *tok;
175 const char *p;
176 const char **attrs;
178 /* Unfortunatly there is no proper way to detect syncrepl-support in
179 * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
180 * but do not show up in the root-DSE yet. Neither we can query the
181 * subschema-context for the syncProviderSubentry or syncConsumerSubentry
182 * objectclass. Currently we require lp_ldap_suffix() to show up as
183 * namingContext. - Guenther
186 if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
187 return ntstatus;
190 if (!seq_num) {
191 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
192 return ntstatus;
195 if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix(talloc_tos()))) {
196 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
197 "as top-level namingContext\n", lp_ldap_suffix(talloc_tos())));
198 return ntstatus;
201 mem_ctx = talloc_init("ldapsam_get_seq_num");
203 if (mem_ctx == NULL)
204 return NT_STATUS_NO_MEMORY;
206 if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
207 ntstatus = NT_STATUS_NO_MEMORY;
208 goto done;
211 /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
212 rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
213 if (rid > 0) {
215 /* consumer syncreplCookie: */
216 /* csn=20050126161620Z#0000001#00#00000 */
217 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
218 attrs[1] = NULL;
219 suffix = talloc_asprintf(mem_ctx,
220 "cn=syncrepl%d,%s", rid, lp_ldap_suffix(talloc_tos()));
221 if (!suffix) {
222 ntstatus = NT_STATUS_NO_MEMORY;
223 goto done;
225 } else {
227 /* provider contextCSN */
228 /* 20050126161620Z#000009#00#000000 */
229 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
230 attrs[1] = NULL;
231 suffix = talloc_asprintf(mem_ctx,
232 "cn=ldapsync,%s", lp_ldap_suffix(talloc_tos()));
234 if (!suffix) {
235 ntstatus = NT_STATUS_NO_MEMORY;
236 goto done;
240 rc = smbldap_search(ldap_state->smbldap_state, suffix,
241 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
243 if (rc != LDAP_SUCCESS) {
244 goto done;
247 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
248 if (num_result != 1) {
249 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
250 goto done;
253 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
254 if (entry == NULL) {
255 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
256 goto done;
259 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
260 if (values == NULL) {
261 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
262 goto done;
265 num_values = ldap_count_values(values);
266 if (num_values == 0) {
267 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
268 goto done;
271 p = values[0];
272 if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
273 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
274 goto done;
277 p = tok;
278 if (!strncmp(p, "csn=", strlen("csn=")))
279 p += strlen("csn=");
281 DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
283 *seq_num = generalized_to_unix_time(p);
285 /* very basic sanity check */
286 if (*seq_num <= 0) {
287 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n",
288 (int)*seq_num));
289 goto done;
292 ntstatus = NT_STATUS_OK;
294 done:
295 if (values != NULL)
296 ldap_value_free(values);
297 if (msg != NULL)
298 ldap_msgfree(msg);
299 if (mem_ctx)
300 talloc_destroy(mem_ctx);
302 return ntstatus;
305 /*******************************************************************
306 Run the search by name.
307 ******************************************************************/
309 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
310 const char *user,
311 LDAPMessage ** result,
312 const char **attr)
314 char *filter = NULL;
315 char *escape_user = escape_ldap_string(talloc_tos(), user);
316 int ret = -1;
318 if (!escape_user) {
319 return LDAP_NO_MEMORY;
323 * in the filter expression, replace %u with the real name
324 * so in ldap filter, %u MUST exist :-)
326 filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
327 get_objclass_filter(ldap_state->schema_ver));
328 if (!filter) {
329 TALLOC_FREE(escape_user);
330 return LDAP_NO_MEMORY;
333 * have to use this here because $ is filtered out
334 * in string_sub
337 filter = talloc_all_string_sub(talloc_tos(),
338 filter, "%u", escape_user);
339 TALLOC_FREE(escape_user);
340 if (!filter) {
341 return LDAP_NO_MEMORY;
344 ret = smbldap_search_suffix(ldap_state->smbldap_state,
345 filter, attr, result);
346 TALLOC_FREE(filter);
347 return ret;
350 /*******************************************************************
351 Run the search by rid.
352 ******************************************************************/
354 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
355 uint32_t rid, LDAPMessage ** result,
356 const char **attr)
358 char *filter = NULL;
359 int rc;
361 filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
362 get_objclass_filter(ldap_state->schema_ver));
363 if (!filter) {
364 return LDAP_NO_MEMORY;
367 rc = smbldap_search_suffix(ldap_state->smbldap_state,
368 filter, attr, result);
369 TALLOC_FREE(filter);
370 return rc;
373 /*******************************************************************
374 Run the search by SID.
375 ******************************************************************/
377 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
378 const struct dom_sid *sid, LDAPMessage ** result,
379 const char **attr)
381 char *filter = NULL;
382 int rc;
383 fstring sid_string;
385 filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
386 get_userattr_key2string(ldap_state->schema_ver,
387 LDAP_ATTR_USER_SID),
388 sid_to_fstring(sid_string, sid),
389 get_objclass_filter(ldap_state->schema_ver));
390 if (!filter) {
391 return LDAP_NO_MEMORY;
394 rc = smbldap_search_suffix(ldap_state->smbldap_state,
395 filter, attr, result);
397 TALLOC_FREE(filter);
398 return rc;
401 /*******************************************************************
402 Delete complete object or objectclass and attrs from
403 object found in search_result depending on lp_ldap_delete_dn
404 ******************************************************************/
406 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
407 TALLOC_CTX *mem_ctx,
408 LDAPMessage *entry,
409 const char *objectclass,
410 const char **attrs)
412 LDAPMod **mods = NULL;
413 char *name;
414 const char *dn;
415 BerElement *ptr = NULL;
417 dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
418 if (dn == NULL) {
419 return LDAP_NO_MEMORY;
422 if (lp_ldap_delete_dn()) {
423 return smbldap_delete(priv->smbldap_state, dn);
426 /* Ok, delete only the SAM attributes */
428 for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
429 name != NULL;
430 name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
431 const char **attrib;
433 /* We are only allowed to delete the attributes that
434 really exist. */
436 for (attrib = attrs; *attrib != NULL; attrib++) {
437 if (strequal(*attrib, name)) {
438 DEBUG(10, ("ldapsam_delete_entry: deleting "
439 "attribute %s\n", name));
440 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
441 NULL);
444 ldap_memfree(name);
447 if (ptr != NULL) {
448 ber_free(ptr, 0);
451 smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
452 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
454 return smbldap_modify(priv->smbldap_state, dn, mods);
457 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
459 char *temp;
460 struct tm tm;
462 temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
463 get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
464 talloc_tos());
465 if (!temp) {
466 return (time_t) 0;
469 if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
470 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
471 (char*)temp));
472 TALLOC_FREE(temp);
473 return (time_t) 0;
475 TALLOC_FREE(temp);
476 tzset();
477 return timegm(&tm);
480 /**********************************************************************
481 Initialize struct samu from an LDAP query.
482 (Based on init_sam_from_buffer in pdb_tdb.c)
483 *********************************************************************/
485 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
486 struct samu * sampass,
487 LDAPMessage * entry)
489 time_t logon_time,
490 logoff_time,
491 kickoff_time,
492 pass_last_set_time,
493 pass_can_change_time,
494 ldap_entry_time,
495 bad_password_time;
496 char *username = NULL,
497 *domain = NULL,
498 *nt_username = NULL,
499 *fullname = NULL,
500 *homedir = NULL,
501 *dir_drive = NULL,
502 *logon_script = NULL,
503 *profile_path = NULL,
504 *acct_desc = NULL,
505 *workstations = NULL,
506 *munged_dial = NULL;
507 uint32_t user_rid;
508 uint8 smblmpwd[LM_HASH_LEN],
509 smbntpwd[NT_HASH_LEN];
510 bool use_samba_attrs = True;
511 uint32_t acct_ctrl = 0;
512 uint16_t logon_divs;
513 uint16_t bad_password_count = 0,
514 logon_count = 0;
515 uint32_t hours_len;
516 uint8 hours[MAX_HOURS_LEN];
517 char *temp = NULL;
518 struct login_cache cache_entry;
519 uint32_t pwHistLen;
520 bool expand_explicit = lp_passdb_expand_explicit();
521 bool ret = false;
522 TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
524 if (!ctx) {
525 return false;
527 if (sampass == NULL || ldap_state == NULL || entry == NULL) {
528 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
529 goto fn_exit;
532 if (priv2ld(ldap_state) == NULL) {
533 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
534 "ldap_struct is NULL!\n"));
535 goto fn_exit;
538 if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
539 entry,
540 "uid",
541 ctx))) {
542 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
543 "this user!\n"));
544 goto fn_exit;
547 DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
549 nt_username = talloc_strdup(ctx, username);
550 if (!nt_username) {
551 goto fn_exit;
554 domain = talloc_strdup(ctx, ldap_state->domain_name);
555 if (!domain) {
556 goto fn_exit;
559 pdb_set_username(sampass, username, PDB_SET);
561 pdb_set_domain(sampass, domain, PDB_DEFAULT);
562 pdb_set_nt_username(sampass, nt_username, PDB_SET);
564 /* deal with different attributes between the schema first */
566 if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
567 if ((temp = smbldap_talloc_single_attribute(
568 ldap_state->smbldap_state->ldap_struct,
569 entry,
570 get_userattr_key2string(ldap_state->schema_ver,
571 LDAP_ATTR_USER_SID),
572 ctx))!=NULL) {
573 pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
575 } else {
576 if ((temp = smbldap_talloc_single_attribute(
577 ldap_state->smbldap_state->ldap_struct,
578 entry,
579 get_userattr_key2string(ldap_state->schema_ver,
580 LDAP_ATTR_USER_RID),
581 ctx))!=NULL) {
582 user_rid = (uint32_t)atol(temp);
583 pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
587 if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
588 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n",
589 get_userattr_key2string(ldap_state->schema_ver,
590 LDAP_ATTR_USER_SID),
591 get_userattr_key2string(ldap_state->schema_ver,
592 LDAP_ATTR_USER_RID),
593 username));
594 return False;
597 temp = smbldap_talloc_single_attribute(
598 ldap_state->smbldap_state->ldap_struct,
599 entry,
600 get_userattr_key2string(ldap_state->schema_ver,
601 LDAP_ATTR_PWD_LAST_SET),
602 ctx);
603 if (temp) {
604 pass_last_set_time = (time_t) atol(temp);
605 pdb_set_pass_last_set_time(sampass,
606 pass_last_set_time, PDB_SET);
609 temp = smbldap_talloc_single_attribute(
610 ldap_state->smbldap_state->ldap_struct,
611 entry,
612 get_userattr_key2string(ldap_state->schema_ver,
613 LDAP_ATTR_LOGON_TIME),
614 ctx);
615 if (temp) {
616 logon_time = (time_t) atol(temp);
617 pdb_set_logon_time(sampass, logon_time, PDB_SET);
620 temp = smbldap_talloc_single_attribute(
621 ldap_state->smbldap_state->ldap_struct,
622 entry,
623 get_userattr_key2string(ldap_state->schema_ver,
624 LDAP_ATTR_LOGOFF_TIME),
625 ctx);
626 if (temp) {
627 logoff_time = (time_t) atol(temp);
628 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
631 temp = smbldap_talloc_single_attribute(
632 ldap_state->smbldap_state->ldap_struct,
633 entry,
634 get_userattr_key2string(ldap_state->schema_ver,
635 LDAP_ATTR_KICKOFF_TIME),
636 ctx);
637 if (temp) {
638 kickoff_time = (time_t) atol(temp);
639 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
642 temp = smbldap_talloc_single_attribute(
643 ldap_state->smbldap_state->ldap_struct,
644 entry,
645 get_userattr_key2string(ldap_state->schema_ver,
646 LDAP_ATTR_PWD_CAN_CHANGE),
647 ctx);
648 if (temp) {
649 pass_can_change_time = (time_t) atol(temp);
650 pdb_set_pass_can_change_time(sampass,
651 pass_can_change_time, PDB_SET);
654 /* recommend that 'gecos' and 'displayName' should refer to the same
655 * attribute OID. userFullName depreciated, only used by Samba
656 * primary rules of LDAP: don't make a new attribute when one is already defined
657 * that fits your needs; using cn then displayName rather than 'userFullName'
660 fullname = smbldap_talloc_single_attribute(
661 ldap_state->smbldap_state->ldap_struct,
662 entry,
663 get_userattr_key2string(ldap_state->schema_ver,
664 LDAP_ATTR_DISPLAY_NAME),
665 ctx);
666 if (fullname) {
667 pdb_set_fullname(sampass, fullname, PDB_SET);
668 } else {
669 fullname = smbldap_talloc_single_attribute(
670 ldap_state->smbldap_state->ldap_struct,
671 entry,
672 get_userattr_key2string(ldap_state->schema_ver,
673 LDAP_ATTR_CN),
674 ctx);
675 if (fullname) {
676 pdb_set_fullname(sampass, fullname, PDB_SET);
680 dir_drive = smbldap_talloc_single_attribute(
681 ldap_state->smbldap_state->ldap_struct,
682 entry,
683 get_userattr_key2string(ldap_state->schema_ver,
684 LDAP_ATTR_HOME_DRIVE),
685 ctx);
686 if (dir_drive) {
687 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
688 } else {
689 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
692 homedir = smbldap_talloc_single_attribute(
693 ldap_state->smbldap_state->ldap_struct,
694 entry,
695 get_userattr_key2string(ldap_state->schema_ver,
696 LDAP_ATTR_HOME_PATH),
697 ctx);
698 if (homedir) {
699 if (expand_explicit) {
700 homedir = talloc_sub_basic(ctx,
701 username,
702 domain,
703 homedir);
704 if (!homedir) {
705 goto fn_exit;
708 pdb_set_homedir(sampass, homedir, PDB_SET);
709 } else {
710 pdb_set_homedir(sampass,
711 talloc_sub_basic(ctx, username, domain,
712 lp_logon_home()),
713 PDB_DEFAULT);
716 logon_script = smbldap_talloc_single_attribute(
717 ldap_state->smbldap_state->ldap_struct,
718 entry,
719 get_userattr_key2string(ldap_state->schema_ver,
720 LDAP_ATTR_LOGON_SCRIPT),
721 ctx);
722 if (logon_script) {
723 if (expand_explicit) {
724 logon_script = talloc_sub_basic(ctx,
725 username,
726 domain,
727 logon_script);
728 if (!logon_script) {
729 goto fn_exit;
732 pdb_set_logon_script(sampass, logon_script, PDB_SET);
733 } else {
734 pdb_set_logon_script(sampass,
735 talloc_sub_basic(ctx, username, domain,
736 lp_logon_script()),
737 PDB_DEFAULT );
740 profile_path = smbldap_talloc_single_attribute(
741 ldap_state->smbldap_state->ldap_struct,
742 entry,
743 get_userattr_key2string(ldap_state->schema_ver,
744 LDAP_ATTR_PROFILE_PATH),
745 ctx);
746 if (profile_path) {
747 if (expand_explicit) {
748 profile_path = talloc_sub_basic(ctx,
749 username,
750 domain,
751 profile_path);
752 if (!profile_path) {
753 goto fn_exit;
756 pdb_set_profile_path(sampass, profile_path, PDB_SET);
757 } else {
758 pdb_set_profile_path(sampass,
759 talloc_sub_basic(ctx, username, domain,
760 lp_logon_path()),
761 PDB_DEFAULT );
764 acct_desc = smbldap_talloc_single_attribute(
765 ldap_state->smbldap_state->ldap_struct,
766 entry,
767 get_userattr_key2string(ldap_state->schema_ver,
768 LDAP_ATTR_DESC),
769 ctx);
770 if (acct_desc) {
771 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
774 workstations = smbldap_talloc_single_attribute(
775 ldap_state->smbldap_state->ldap_struct,
776 entry,
777 get_userattr_key2string(ldap_state->schema_ver,
778 LDAP_ATTR_USER_WKS),
779 ctx);
780 if (workstations) {
781 pdb_set_workstations(sampass, workstations, PDB_SET);
784 munged_dial = smbldap_talloc_single_attribute(
785 ldap_state->smbldap_state->ldap_struct,
786 entry,
787 get_userattr_key2string(ldap_state->schema_ver,
788 LDAP_ATTR_MUNGED_DIAL),
789 ctx);
790 if (munged_dial) {
791 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
794 /* FIXME: hours stuff should be cleaner */
796 logon_divs = 168;
797 hours_len = 21;
798 memset(hours, 0xff, hours_len);
800 if (ldap_state->is_nds_ldap) {
801 char *user_dn;
802 size_t pwd_len;
803 char clear_text_pw[512];
805 /* Make call to Novell eDirectory ldap extension to get clear text password.
806 NOTE: This will only work if we have an SSL connection to eDirectory. */
807 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
808 if (user_dn != NULL) {
809 DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
811 pwd_len = sizeof(clear_text_pw);
812 if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
813 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
814 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
815 TALLOC_FREE(user_dn);
816 return False;
818 ZERO_STRUCT(smblmpwd);
819 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
820 TALLOC_FREE(user_dn);
821 return False;
823 ZERO_STRUCT(smbntpwd);
824 use_samba_attrs = False;
827 TALLOC_FREE(user_dn);
829 } else {
830 DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
834 if (use_samba_attrs) {
835 temp = smbldap_talloc_single_attribute(
836 ldap_state->smbldap_state->ldap_struct,
837 entry,
838 get_userattr_key2string(ldap_state->schema_ver,
839 LDAP_ATTR_LMPW),
840 ctx);
841 if (temp) {
842 pdb_gethexpwd(temp, smblmpwd);
843 memset((char *)temp, '\0', strlen(temp)+1);
844 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
845 goto fn_exit;
847 ZERO_STRUCT(smblmpwd);
850 temp = smbldap_talloc_single_attribute(
851 ldap_state->smbldap_state->ldap_struct,
852 entry,
853 get_userattr_key2string(ldap_state->schema_ver,
854 LDAP_ATTR_NTPW),
855 ctx);
856 if (temp) {
857 pdb_gethexpwd(temp, smbntpwd);
858 memset((char *)temp, '\0', strlen(temp)+1);
859 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
860 goto fn_exit;
862 ZERO_STRUCT(smbntpwd);
866 pwHistLen = 0;
868 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
869 if (pwHistLen > 0){
870 uint8 *pwhist = NULL;
871 int i;
872 char *history_string = talloc_array(ctx, char,
873 MAX_PW_HISTORY_LEN*64);
875 if (!history_string) {
876 goto fn_exit;
879 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
881 pwhist = talloc_array(ctx, uint8,
882 pwHistLen * PW_HISTORY_ENTRY_LEN);
883 if (pwhist == NULL) {
884 DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
885 goto fn_exit;
887 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
889 if (smbldap_get_single_attribute(
890 ldap_state->smbldap_state->ldap_struct,
891 entry,
892 get_userattr_key2string(ldap_state->schema_ver,
893 LDAP_ATTR_PWD_HISTORY),
894 history_string,
895 MAX_PW_HISTORY_LEN*64)) {
896 bool hex_failed = false;
897 for (i = 0; i < pwHistLen; i++){
898 /* Get the 16 byte salt. */
899 if (!pdb_gethexpwd(&history_string[i*64],
900 &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
901 hex_failed = true;
902 break;
904 /* Get the 16 byte MD5 hash of salt+passwd. */
905 if (!pdb_gethexpwd(&history_string[(i*64)+32],
906 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
907 PW_HISTORY_SALT_LEN])) {
908 hex_failed = True;
909 break;
912 if (hex_failed) {
913 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
914 username));
915 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
918 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
919 goto fn_exit;
923 temp = smbldap_talloc_single_attribute(
924 ldap_state->smbldap_state->ldap_struct,
925 entry,
926 get_userattr_key2string(ldap_state->schema_ver,
927 LDAP_ATTR_ACB_INFO),
928 ctx);
929 if (temp) {
930 acct_ctrl = pdb_decode_acct_ctrl(temp);
932 if (acct_ctrl == 0) {
933 acct_ctrl |= ACB_NORMAL;
936 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
937 } else {
938 acct_ctrl |= ACB_NORMAL;
941 pdb_set_hours_len(sampass, hours_len, PDB_SET);
942 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
944 temp = smbldap_talloc_single_attribute(
945 ldap_state->smbldap_state->ldap_struct,
946 entry,
947 get_userattr_key2string(ldap_state->schema_ver,
948 LDAP_ATTR_BAD_PASSWORD_COUNT),
949 ctx);
950 if (temp) {
951 bad_password_count = (uint32_t) atol(temp);
952 pdb_set_bad_password_count(sampass,
953 bad_password_count, PDB_SET);
956 temp = smbldap_talloc_single_attribute(
957 ldap_state->smbldap_state->ldap_struct,
958 entry,
959 get_userattr_key2string(ldap_state->schema_ver,
960 LDAP_ATTR_BAD_PASSWORD_TIME),
961 ctx);
962 if (temp) {
963 bad_password_time = (time_t) atol(temp);
964 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
968 temp = smbldap_talloc_single_attribute(
969 ldap_state->smbldap_state->ldap_struct,
970 entry,
971 get_userattr_key2string(ldap_state->schema_ver,
972 LDAP_ATTR_LOGON_COUNT),
973 ctx);
974 if (temp) {
975 logon_count = (uint32_t) atol(temp);
976 pdb_set_logon_count(sampass, logon_count, PDB_SET);
979 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
981 temp = smbldap_talloc_single_attribute(
982 ldap_state->smbldap_state->ldap_struct,
983 entry,
984 get_userattr_key2string(ldap_state->schema_ver,
985 LDAP_ATTR_LOGON_HOURS),
986 ctx);
987 if (temp) {
988 pdb_gethexhours(temp, hours);
989 memset((char *)temp, '\0', strlen(temp) +1);
990 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
991 ZERO_STRUCT(hours);
994 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
995 struct passwd unix_pw;
996 bool have_uid = false;
997 bool have_gid = false;
998 struct dom_sid mapped_gsid;
999 const struct dom_sid *primary_gsid;
1000 struct unixid id;
1002 ZERO_STRUCT(unix_pw);
1004 unix_pw.pw_name = username;
1005 unix_pw.pw_passwd = discard_const_p(char, "x");
1007 temp = smbldap_talloc_single_attribute(
1008 priv2ld(ldap_state),
1009 entry,
1010 "uidNumber",
1011 ctx);
1012 if (temp) {
1013 /* We've got a uid, feed the cache */
1014 unix_pw.pw_uid = strtoul(temp, NULL, 10);
1015 have_uid = true;
1017 temp = smbldap_talloc_single_attribute(
1018 priv2ld(ldap_state),
1019 entry,
1020 "gidNumber",
1021 ctx);
1022 if (temp) {
1023 /* We've got a uid, feed the cache */
1024 unix_pw.pw_gid = strtoul(temp, NULL, 10);
1025 have_gid = true;
1027 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1028 priv2ld(ldap_state),
1029 entry,
1030 "gecos",
1031 ctx);
1032 if (unix_pw.pw_gecos) {
1033 unix_pw.pw_gecos = fullname;
1035 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1036 priv2ld(ldap_state),
1037 entry,
1038 "homeDirectory",
1039 ctx);
1040 if (unix_pw.pw_dir) {
1041 unix_pw.pw_dir = discard_const_p(char, "");
1043 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1044 priv2ld(ldap_state),
1045 entry,
1046 "loginShell",
1047 ctx);
1048 if (unix_pw.pw_shell) {
1049 unix_pw.pw_shell = discard_const_p(char, "");
1052 if (have_uid && have_gid) {
1053 sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1054 } else {
1055 sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1058 if (sampass->unix_pw == NULL) {
1059 DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1060 pdb_get_username(sampass)));
1061 goto fn_exit;
1064 id.id = sampass->unix_pw->pw_uid;
1065 id.type = ID_TYPE_UID;
1067 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1069 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1070 primary_gsid = pdb_get_group_sid(sampass);
1071 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1072 id.id = sampass->unix_pw->pw_gid;
1073 id.type = ID_TYPE_GID;
1075 idmap_cache_set_sid2unixid(primary_gsid, &id);
1079 /* check the timestamp of the cache vs ldap entry */
1080 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1081 entry))) {
1082 ret = true;
1083 goto fn_exit;
1086 /* see if we have newer updates */
1087 if (!login_cache_read(sampass, &cache_entry)) {
1088 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1089 (unsigned int)pdb_get_bad_password_count(sampass),
1090 (unsigned int)pdb_get_bad_password_time(sampass)));
1091 ret = true;
1092 goto fn_exit;
1095 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1096 (unsigned int)ldap_entry_time,
1097 (unsigned int)cache_entry.entry_timestamp,
1098 (unsigned int)cache_entry.bad_password_time));
1100 if (ldap_entry_time > cache_entry.entry_timestamp) {
1101 /* cache is older than directory , so
1102 we need to delete the entry but allow the
1103 fields to be written out */
1104 login_cache_delentry(sampass);
1105 } else {
1106 /* read cache in */
1107 pdb_set_acct_ctrl(sampass,
1108 pdb_get_acct_ctrl(sampass) |
1109 (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1110 PDB_SET);
1111 pdb_set_bad_password_count(sampass,
1112 cache_entry.bad_password_count,
1113 PDB_SET);
1114 pdb_set_bad_password_time(sampass,
1115 cache_entry.bad_password_time,
1116 PDB_SET);
1119 ret = true;
1121 fn_exit:
1123 TALLOC_FREE(ctx);
1124 return ret;
1127 /**********************************************************************
1128 Initialize the ldap db from a struct samu. Called on update.
1129 (Based on init_buffer_from_sam in pdb_tdb.c)
1130 *********************************************************************/
1132 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1133 LDAPMessage *existing,
1134 LDAPMod *** mods, struct samu * sampass,
1135 bool (*need_update)(const struct samu *,
1136 enum pdb_elements))
1138 char *temp = NULL;
1140 if (mods == NULL || sampass == NULL) {
1141 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1142 return False;
1145 *mods = NULL;
1148 * took out adding "objectclass: sambaAccount"
1149 * do this on a per-mod basis
1151 if (need_update(sampass, PDB_USERNAME)) {
1152 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1153 "uid", pdb_get_username(sampass));
1154 if (ldap_state->is_nds_ldap) {
1155 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1156 "cn", pdb_get_username(sampass));
1157 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1158 "sn", pdb_get_username(sampass));
1162 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1164 /* only update the RID if we actually need to */
1165 if (need_update(sampass, PDB_USERSID)) {
1166 fstring sid_string;
1167 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1169 switch ( ldap_state->schema_ver ) {
1170 case SCHEMAVER_SAMBASAMACCOUNT:
1171 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1172 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1173 sid_to_fstring(sid_string, user_sid));
1174 break;
1176 default:
1177 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1178 break;
1182 /* we don't need to store the primary group RID - so leaving it
1183 'free' to hang off the unix primary group makes life easier */
1185 if (need_update(sampass, PDB_GROUPSID)) {
1186 fstring sid_string;
1187 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1189 switch ( ldap_state->schema_ver ) {
1190 case SCHEMAVER_SAMBASAMACCOUNT:
1191 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1192 get_userattr_key2string(ldap_state->schema_ver,
1193 LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1194 break;
1196 default:
1197 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1198 break;
1203 /* displayName, cn, and gecos should all be the same
1204 * most easily accomplished by giving them the same OID
1205 * gecos isn't set here b/c it should be handled by the
1206 * add-user script
1207 * We change displayName only and fall back to cn if
1208 * it does not exist.
1211 if (need_update(sampass, PDB_FULLNAME))
1212 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1213 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME),
1214 pdb_get_fullname(sampass));
1216 if (need_update(sampass, PDB_ACCTDESC))
1217 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1218 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC),
1219 pdb_get_acct_desc(sampass));
1221 if (need_update(sampass, PDB_WORKSTATIONS))
1222 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1223 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS),
1224 pdb_get_workstations(sampass));
1226 if (need_update(sampass, PDB_MUNGEDDIAL))
1227 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1228 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL),
1229 pdb_get_munged_dial(sampass));
1231 if (need_update(sampass, PDB_SMBHOME))
1232 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1233 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH),
1234 pdb_get_homedir(sampass));
1236 if (need_update(sampass, PDB_DRIVE))
1237 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1238 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE),
1239 pdb_get_dir_drive(sampass));
1241 if (need_update(sampass, PDB_LOGONSCRIPT))
1242 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1243 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT),
1244 pdb_get_logon_script(sampass));
1246 if (need_update(sampass, PDB_PROFILE))
1247 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1248 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH),
1249 pdb_get_profile_path(sampass));
1251 if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1252 return false;
1254 if (need_update(sampass, PDB_LOGONTIME))
1255 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1256 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1257 SAFE_FREE(temp);
1259 if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1260 return false;
1262 if (need_update(sampass, PDB_LOGOFFTIME))
1263 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1264 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1265 SAFE_FREE(temp);
1267 if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1268 return false;
1270 if (need_update(sampass, PDB_KICKOFFTIME))
1271 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1272 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1273 SAFE_FREE(temp);
1275 if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1276 return false;
1278 if (need_update(sampass, PDB_CANCHANGETIME))
1279 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1280 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1281 SAFE_FREE(temp);
1283 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1284 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1286 if (need_update(sampass, PDB_LMPASSWD)) {
1287 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1288 if (lm_pw) {
1289 char pwstr[34];
1290 pdb_sethexpwd(pwstr, lm_pw,
1291 pdb_get_acct_ctrl(sampass));
1292 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1293 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1294 pwstr);
1295 } else {
1296 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1297 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1298 NULL);
1301 if (need_update(sampass, PDB_NTPASSWD)) {
1302 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1303 if (nt_pw) {
1304 char pwstr[34];
1305 pdb_sethexpwd(pwstr, nt_pw,
1306 pdb_get_acct_ctrl(sampass));
1307 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1308 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1309 pwstr);
1310 } else {
1311 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1312 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1313 NULL);
1317 if (need_update(sampass, PDB_PWHISTORY)) {
1318 char *pwstr = NULL;
1319 uint32_t pwHistLen = 0;
1320 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1322 pwstr = SMB_MALLOC_ARRAY(char, 1024);
1323 if (!pwstr) {
1324 return false;
1326 if (pwHistLen == 0) {
1327 /* Remove any password history from the LDAP store. */
1328 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1329 pwstr[64] = '\0';
1330 } else {
1331 int i;
1332 uint32_t currHistLen = 0;
1333 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1334 if (pwhist != NULL) {
1335 /* We can only store (1024-1/64 password history entries. */
1336 pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1337 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1338 /* Store the salt. */
1339 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1340 /* Followed by the md5 hash of salt + md4 hash */
1341 pdb_sethexpwd(&pwstr[(i*64)+32],
1342 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1343 DEBUG(100, ("pwstr=%s\n", pwstr));
1347 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1348 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1349 pwstr);
1350 SAFE_FREE(pwstr);
1353 if (need_update(sampass, PDB_PASSLASTSET)) {
1354 if (asprintf(&temp, "%li",
1355 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1356 return false;
1358 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1359 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1360 temp);
1361 SAFE_FREE(temp);
1365 if (need_update(sampass, PDB_HOURS)) {
1366 const uint8 *hours = pdb_get_hours(sampass);
1367 if (hours) {
1368 char hourstr[44];
1369 pdb_sethexhours(hourstr, hours);
1370 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1371 existing,
1372 mods,
1373 get_userattr_key2string(ldap_state->schema_ver,
1374 LDAP_ATTR_LOGON_HOURS),
1375 hourstr);
1379 if (need_update(sampass, PDB_ACCTCTRL))
1380 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1381 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1382 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1384 /* password lockout cache:
1385 - If we are now autolocking or clearing, we write to ldap
1386 - If we are clearing, we delete the cache entry
1387 - If the count is > 0, we update the cache
1389 This even means when autolocking, we cache, just in case the
1390 update doesn't work, and we have to cache the autolock flag */
1392 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1393 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1394 uint16_t badcount = pdb_get_bad_password_count(sampass);
1395 time_t badtime = pdb_get_bad_password_time(sampass);
1396 uint32_t pol;
1397 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1399 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1400 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1402 if ((badcount >= pol) || (badcount == 0)) {
1403 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1404 (unsigned int)badcount, (unsigned int)badtime));
1405 if (asprintf(&temp, "%li", (long)badcount) < 0) {
1406 return false;
1408 smbldap_make_mod(
1409 ldap_state->smbldap_state->ldap_struct,
1410 existing, mods,
1411 get_userattr_key2string(
1412 ldap_state->schema_ver,
1413 LDAP_ATTR_BAD_PASSWORD_COUNT),
1414 temp);
1415 SAFE_FREE(temp);
1417 if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1418 return false;
1420 smbldap_make_mod(
1421 ldap_state->smbldap_state->ldap_struct,
1422 existing, mods,
1423 get_userattr_key2string(
1424 ldap_state->schema_ver,
1425 LDAP_ATTR_BAD_PASSWORD_TIME),
1426 temp);
1427 SAFE_FREE(temp);
1429 if (badcount == 0) {
1430 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1431 login_cache_delentry(sampass);
1432 } else {
1433 struct login_cache cache_entry;
1435 cache_entry.entry_timestamp = time(NULL);
1436 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1437 cache_entry.bad_password_count = badcount;
1438 cache_entry.bad_password_time = badtime;
1440 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1441 login_cache_write(sampass, &cache_entry);
1445 return True;
1448 /**********************************************************************
1449 End enumeration of the LDAP password list.
1450 *********************************************************************/
1452 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1454 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1455 if (ldap_state->result) {
1456 ldap_msgfree(ldap_state->result);
1457 ldap_state->result = NULL;
1461 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1462 const char *new_attr)
1464 int i;
1466 if (new_attr == NULL) {
1467 return;
1470 for (i=0; (*attr_list)[i] != NULL; i++) {
1474 (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1475 const char *, i+2);
1476 SMB_ASSERT((*attr_list) != NULL);
1477 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1478 (*attr_list)[i+1] = NULL;
1481 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1482 const char ***attr_list)
1484 append_attr(mem_ctx, attr_list, "uidNumber");
1485 append_attr(mem_ctx, attr_list, "gidNumber");
1486 append_attr(mem_ctx, attr_list, "homeDirectory");
1487 append_attr(mem_ctx, attr_list, "loginShell");
1488 append_attr(mem_ctx, attr_list, "gecos");
1491 /**********************************************************************
1492 Get struct samu entry from LDAP by username.
1493 *********************************************************************/
1495 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1497 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1498 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1499 LDAPMessage *result = NULL;
1500 LDAPMessage *entry = NULL;
1501 int count;
1502 const char ** attr_list;
1503 int rc;
1505 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1506 append_attr(user, &attr_list,
1507 get_userattr_key2string(ldap_state->schema_ver,
1508 LDAP_ATTR_MOD_TIMESTAMP));
1509 ldapsam_add_unix_attributes(user, &attr_list);
1510 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1511 attr_list);
1512 TALLOC_FREE( attr_list );
1514 if ( rc != LDAP_SUCCESS )
1515 return NT_STATUS_NO_SUCH_USER;
1517 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1519 if (count < 1) {
1520 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1521 ldap_msgfree(result);
1522 return NT_STATUS_NO_SUCH_USER;
1523 } else if (count > 1) {
1524 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1525 ldap_msgfree(result);
1526 return NT_STATUS_NO_SUCH_USER;
1529 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1530 if (entry) {
1531 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1532 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1533 ldap_msgfree(result);
1534 return NT_STATUS_NO_SUCH_USER;
1536 pdb_set_backend_private_data(user, result, NULL,
1537 my_methods, PDB_CHANGED);
1538 smbldap_talloc_autofree_ldapmsg(user, result);
1539 ret = NT_STATUS_OK;
1540 } else {
1541 ldap_msgfree(result);
1543 return ret;
1546 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1547 const struct dom_sid *sid, LDAPMessage **result)
1549 int rc = -1;
1550 const char ** attr_list;
1552 switch ( ldap_state->schema_ver ) {
1553 case SCHEMAVER_SAMBASAMACCOUNT: {
1554 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1555 if (tmp_ctx == NULL) {
1556 return LDAP_NO_MEMORY;
1559 attr_list = get_userattr_list(tmp_ctx,
1560 ldap_state->schema_ver);
1561 append_attr(tmp_ctx, &attr_list,
1562 get_userattr_key2string(
1563 ldap_state->schema_ver,
1564 LDAP_ATTR_MOD_TIMESTAMP));
1565 ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1566 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1567 result, attr_list);
1568 TALLOC_FREE(tmp_ctx);
1570 if ( rc != LDAP_SUCCESS )
1571 return rc;
1572 break;
1575 default:
1576 DEBUG(0,("Invalid schema version specified\n"));
1577 break;
1579 return rc;
1582 /**********************************************************************
1583 Get struct samu entry from LDAP by SID.
1584 *********************************************************************/
1586 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1588 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1589 LDAPMessage *result = NULL;
1590 LDAPMessage *entry = NULL;
1591 int count;
1592 int rc;
1594 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1595 sid, &result);
1596 if (rc != LDAP_SUCCESS)
1597 return NT_STATUS_NO_SUCH_USER;
1599 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1601 if (count < 1) {
1602 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1603 "count=%d\n", sid_string_dbg(sid), count));
1604 ldap_msgfree(result);
1605 return NT_STATUS_NO_SUCH_USER;
1606 } else if (count > 1) {
1607 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1608 "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1609 count));
1610 ldap_msgfree(result);
1611 return NT_STATUS_NO_SUCH_USER;
1614 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1615 if (!entry) {
1616 ldap_msgfree(result);
1617 return NT_STATUS_NO_SUCH_USER;
1620 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1621 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1622 ldap_msgfree(result);
1623 return NT_STATUS_NO_SUCH_USER;
1626 pdb_set_backend_private_data(user, result, NULL,
1627 my_methods, PDB_CHANGED);
1628 smbldap_talloc_autofree_ldapmsg(user, result);
1629 return NT_STATUS_OK;
1632 /********************************************************************
1633 Do the actual modification - also change a plaintext passord if
1634 it it set.
1635 **********************************************************************/
1637 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1638 struct samu *newpwd, char *dn,
1639 LDAPMod **mods, int ldap_op,
1640 bool (*need_update)(const struct samu *, enum pdb_elements))
1642 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1643 int rc;
1645 if (!newpwd || !dn) {
1646 return NT_STATUS_INVALID_PARAMETER;
1649 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1650 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1651 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1652 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1653 BerElement *ber;
1654 struct berval *bv;
1655 char *retoid = NULL;
1656 struct berval *retdata = NULL;
1657 char *utf8_password;
1658 char *utf8_dn;
1659 size_t converted_size;
1660 int ret;
1662 if (!ldap_state->is_nds_ldap) {
1664 if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct,
1665 LDAP_EXOP_MODIFY_PASSWD)) {
1666 DEBUG(2, ("ldap password change requested, but LDAP "
1667 "server does not support it -- ignoring\n"));
1668 return NT_STATUS_OK;
1672 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1673 pdb_get_plaintext_passwd(newpwd),
1674 &converted_size))
1676 return NT_STATUS_NO_MEMORY;
1679 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1680 TALLOC_FREE(utf8_password);
1681 return NT_STATUS_NO_MEMORY;
1684 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1685 DEBUG(0,("ber_alloc_t returns NULL\n"));
1686 TALLOC_FREE(utf8_password);
1687 TALLOC_FREE(utf8_dn);
1688 return NT_STATUS_UNSUCCESSFUL;
1691 if ((ber_printf (ber, "{") < 0) ||
1692 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1693 utf8_dn) < 0)) {
1694 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1695 "value <0\n"));
1696 ber_free(ber,1);
1697 TALLOC_FREE(utf8_dn);
1698 TALLOC_FREE(utf8_password);
1699 return NT_STATUS_UNSUCCESSFUL;
1702 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1703 ret = ber_printf(ber, "ts}",
1704 LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1705 utf8_password);
1706 } else {
1707 ret = ber_printf(ber, "}");
1710 if (ret < 0) {
1711 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1712 "value <0\n"));
1713 ber_free(ber,1);
1714 TALLOC_FREE(utf8_dn);
1715 TALLOC_FREE(utf8_password);
1716 return NT_STATUS_UNSUCCESSFUL;
1719 if ((rc = ber_flatten (ber, &bv))<0) {
1720 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1721 ber_free(ber,1);
1722 TALLOC_FREE(utf8_dn);
1723 TALLOC_FREE(utf8_password);
1724 return NT_STATUS_UNSUCCESSFUL;
1727 TALLOC_FREE(utf8_dn);
1728 TALLOC_FREE(utf8_password);
1729 ber_free(ber, 1);
1731 if (!ldap_state->is_nds_ldap) {
1732 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1733 LDAP_EXOP_MODIFY_PASSWD,
1734 bv, NULL, NULL, &retoid,
1735 &retdata);
1736 } else {
1737 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1738 pdb_get_plaintext_passwd(newpwd));
1740 if (rc != LDAP_SUCCESS) {
1741 char *ld_error = NULL;
1743 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1744 DEBUG(3, ("Could not set userPassword "
1745 "attribute due to an objectClass "
1746 "violation -- ignoring\n"));
1747 ber_bvfree(bv);
1748 return NT_STATUS_OK;
1751 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1752 &ld_error);
1753 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1754 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1755 SAFE_FREE(ld_error);
1756 ber_bvfree(bv);
1757 #if defined(LDAP_CONSTRAINT_VIOLATION)
1758 if (rc == LDAP_CONSTRAINT_VIOLATION)
1759 return NT_STATUS_PASSWORD_RESTRICTION;
1760 #endif
1761 return NT_STATUS_UNSUCCESSFUL;
1762 } else {
1763 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1764 #ifdef DEBUG_PASSWORD
1765 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1766 #endif
1767 if (retdata)
1768 ber_bvfree(retdata);
1769 if (retoid)
1770 ldap_memfree(retoid);
1772 ber_bvfree(bv);
1775 if (!mods) {
1776 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1777 /* may be password change below however */
1778 } else {
1779 switch(ldap_op) {
1780 case LDAP_MOD_ADD:
1781 if (ldap_state->is_nds_ldap) {
1782 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1783 "objectclass",
1784 "inetOrgPerson");
1785 } else {
1786 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1787 "objectclass",
1788 LDAP_OBJ_ACCOUNT);
1790 rc = smbldap_add(ldap_state->smbldap_state,
1791 dn, mods);
1792 break;
1793 case LDAP_MOD_REPLACE:
1794 rc = smbldap_modify(ldap_state->smbldap_state,
1795 dn ,mods);
1796 break;
1797 default:
1798 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1799 ldap_op));
1800 return NT_STATUS_INVALID_PARAMETER;
1803 if (rc!=LDAP_SUCCESS) {
1804 return NT_STATUS_UNSUCCESSFUL;
1808 return NT_STATUS_OK;
1811 /**********************************************************************
1812 Delete entry from LDAP for username.
1813 *********************************************************************/
1815 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1816 struct samu * sam_acct)
1818 struct ldapsam_privates *priv =
1819 (struct ldapsam_privates *)my_methods->private_data;
1820 const char *sname;
1821 int rc;
1822 LDAPMessage *msg, *entry;
1823 NTSTATUS result = NT_STATUS_NO_MEMORY;
1824 const char **attr_list;
1825 TALLOC_CTX *mem_ctx;
1827 if (!sam_acct) {
1828 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1829 return NT_STATUS_INVALID_PARAMETER;
1832 sname = pdb_get_username(sam_acct);
1834 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1835 "LDAP.\n", sname));
1837 mem_ctx = talloc_new(NULL);
1838 if (mem_ctx == NULL) {
1839 DEBUG(0, ("talloc_new failed\n"));
1840 goto done;
1843 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1844 if (attr_list == NULL) {
1845 goto done;
1848 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1850 if ((rc != LDAP_SUCCESS) ||
1851 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1852 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1853 DEBUG(5, ("Could not find user %s\n", sname));
1854 result = NT_STATUS_NO_SUCH_USER;
1855 goto done;
1858 rc = ldapsam_delete_entry(
1859 priv, mem_ctx, entry,
1860 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1861 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1862 attr_list);
1864 result = (rc == LDAP_SUCCESS) ?
1865 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1867 done:
1868 TALLOC_FREE(mem_ctx);
1869 return result;
1872 /**********************************************************************
1873 Update struct samu.
1874 *********************************************************************/
1876 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1878 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1879 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1880 int rc = 0;
1881 char *dn;
1882 LDAPMessage *result = NULL;
1883 LDAPMessage *entry = NULL;
1884 LDAPMod **mods = NULL;
1885 const char **attr_list;
1887 result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1888 if (!result) {
1889 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1890 if (pdb_get_username(newpwd) == NULL) {
1891 return NT_STATUS_INVALID_PARAMETER;
1893 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1894 TALLOC_FREE( attr_list );
1895 if (rc != LDAP_SUCCESS) {
1896 return NT_STATUS_UNSUCCESSFUL;
1898 pdb_set_backend_private_data(newpwd, result, NULL,
1899 my_methods, PDB_CHANGED);
1900 smbldap_talloc_autofree_ldapmsg(newpwd, result);
1903 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1904 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1905 return NT_STATUS_UNSUCCESSFUL;
1908 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1909 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1910 if (!dn) {
1911 return NT_STATUS_UNSUCCESSFUL;
1914 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1916 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1917 pdb_element_is_changed)) {
1918 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1919 TALLOC_FREE(dn);
1920 if (mods != NULL)
1921 ldap_mods_free(mods,True);
1922 return NT_STATUS_UNSUCCESSFUL;
1925 if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1926 && (mods == NULL)) {
1927 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1928 pdb_get_username(newpwd)));
1929 TALLOC_FREE(dn);
1930 return NT_STATUS_OK;
1933 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1935 if (mods != NULL) {
1936 ldap_mods_free(mods,True);
1939 TALLOC_FREE(dn);
1942 * We need to set the backend private data to NULL here. For example
1943 * setuserinfo level 25 does a pdb_update_sam_account twice on the
1944 * same one, and with the explicit delete / add logic for attribute
1945 * values the second time we would use the wrong "old" value which
1946 * does not exist in LDAP anymore. Thus the LDAP server would refuse
1947 * the update.
1948 * The existing LDAPMessage is still being auto-freed by the
1949 * destructor.
1951 pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1952 PDB_CHANGED);
1954 if (!NT_STATUS_IS_OK(ret)) {
1955 return ret;
1958 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1959 pdb_get_username(newpwd)));
1960 return NT_STATUS_OK;
1963 /***************************************************************************
1964 Renames a struct samu
1965 - The "rename user script" has full responsibility for changing everything
1966 ***************************************************************************/
1968 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1969 TALLOC_CTX *tmp_ctx,
1970 uint32_t group_rid,
1971 uint32_t member_rid);
1973 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1974 TALLOC_CTX *mem_ctx,
1975 struct samu *user,
1976 struct dom_sid **pp_sids,
1977 gid_t **pp_gids,
1978 uint32_t *p_num_groups);
1980 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1981 struct samu *old_acct,
1982 const char *newname)
1984 const char *oldname;
1985 int rc;
1986 char *rename_script = NULL;
1987 fstring oldname_lower, newname_lower;
1989 if (!old_acct) {
1990 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1991 return NT_STATUS_INVALID_PARAMETER;
1993 if (!newname) {
1994 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1995 return NT_STATUS_INVALID_PARAMETER;
1998 oldname = pdb_get_username(old_acct);
2000 /* rename the posix user */
2001 rename_script = lp_renameuser_script(talloc_tos());
2002 if (rename_script == NULL) {
2003 return NT_STATUS_NO_MEMORY;
2006 if (!(*rename_script)) {
2007 TALLOC_FREE(rename_script);
2008 return NT_STATUS_ACCESS_DENIED;
2011 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2012 oldname, newname));
2014 /* We have to allow the account name to end with a '$'.
2015 Also, follow the semantics in _samr_create_user() and lower case the
2016 posix name but preserve the case in passdb */
2018 fstrcpy( oldname_lower, oldname );
2019 if (!strlower_m( oldname_lower )) {
2020 return NT_STATUS_INVALID_PARAMETER;
2022 fstrcpy( newname_lower, newname );
2023 if (!strlower_m( newname_lower )) {
2024 return NT_STATUS_INVALID_PARAMETER;
2027 rename_script = realloc_string_sub2(rename_script,
2028 "%unew",
2029 newname_lower,
2030 true,
2031 true);
2032 if (!rename_script) {
2033 return NT_STATUS_NO_MEMORY;
2035 rename_script = realloc_string_sub2(rename_script,
2036 "%uold",
2037 oldname_lower,
2038 true,
2039 true);
2040 rc = smbrun(rename_script, NULL);
2042 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2043 rename_script, rc));
2045 TALLOC_FREE(rename_script);
2047 if (rc == 0) {
2048 smb_nscd_flush_user_cache();
2051 if (rc)
2052 return NT_STATUS_UNSUCCESSFUL;
2054 return NT_STATUS_OK;
2057 /**********************************************************************
2058 Add struct samu to LDAP.
2059 *********************************************************************/
2061 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2063 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2064 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2065 int rc;
2066 LDAPMessage *result = NULL;
2067 LDAPMessage *entry = NULL;
2068 LDAPMod **mods = NULL;
2069 int ldap_op = LDAP_MOD_REPLACE;
2070 uint32_t num_result;
2071 const char **attr_list;
2072 char *escape_user = NULL;
2073 const char *username = pdb_get_username(newpwd);
2074 const struct dom_sid *sid = pdb_get_user_sid(newpwd);
2075 char *filter = NULL;
2076 char *dn = NULL;
2077 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2078 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2080 if (!ctx) {
2081 return NT_STATUS_NO_MEMORY;
2084 if (!username || !*username) {
2085 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2086 status = NT_STATUS_INVALID_PARAMETER;
2087 goto fn_exit;
2090 /* free this list after the second search or in case we exit on failure */
2091 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2093 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2095 if (rc != LDAP_SUCCESS) {
2096 goto fn_exit;
2099 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2100 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2101 username));
2102 goto fn_exit;
2104 ldap_msgfree(result);
2105 result = NULL;
2107 if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2108 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2109 sid, &result);
2110 if (rc == LDAP_SUCCESS) {
2111 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2112 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2113 "already in the base, with samba "
2114 "attributes\n", sid_string_dbg(sid)));
2115 goto fn_exit;
2117 ldap_msgfree(result);
2118 result = NULL;
2122 /* does the entry already exist but without a samba attributes?
2123 we need to return the samba attributes here */
2125 escape_user = escape_ldap_string(talloc_tos(), username);
2126 filter = talloc_strdup(attr_list, "(uid=%u)");
2127 if (!filter) {
2128 status = NT_STATUS_NO_MEMORY;
2129 goto fn_exit;
2131 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2132 TALLOC_FREE(escape_user);
2133 if (!filter) {
2134 status = NT_STATUS_NO_MEMORY;
2135 goto fn_exit;
2138 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2139 filter, attr_list, &result);
2140 if ( rc != LDAP_SUCCESS ) {
2141 goto fn_exit;
2144 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2146 if (num_result > 1) {
2147 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2148 goto fn_exit;
2151 /* Check if we need to update an existing entry */
2152 if (num_result == 1) {
2153 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2154 ldap_op = LDAP_MOD_REPLACE;
2155 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2156 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2157 if (!dn) {
2158 status = NT_STATUS_NO_MEMORY;
2159 goto fn_exit;
2162 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2164 /* There might be a SID for this account already - say an idmap entry */
2166 filter = talloc_asprintf(ctx,
2167 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2168 get_userattr_key2string(ldap_state->schema_ver,
2169 LDAP_ATTR_USER_SID),
2170 sid_string_talloc(ctx, sid),
2171 LDAP_OBJ_IDMAP_ENTRY,
2172 LDAP_OBJ_SID_ENTRY);
2173 if (!filter) {
2174 status = NT_STATUS_NO_MEMORY;
2175 goto fn_exit;
2178 /* free old result before doing a new search */
2179 if (result != NULL) {
2180 ldap_msgfree(result);
2181 result = NULL;
2183 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2184 filter, attr_list, &result);
2186 if ( rc != LDAP_SUCCESS ) {
2187 goto fn_exit;
2190 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2192 if (num_result > 1) {
2193 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2194 goto fn_exit;
2197 /* Check if we need to update an existing entry */
2198 if (num_result == 1) {
2200 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2201 ldap_op = LDAP_MOD_REPLACE;
2202 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2203 dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2204 if (!dn) {
2205 status = NT_STATUS_NO_MEMORY;
2206 goto fn_exit;
2211 if (num_result == 0) {
2212 char *escape_username;
2213 /* Check if we need to add an entry */
2214 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2215 ldap_op = LDAP_MOD_ADD;
2217 escape_username = escape_rdn_val_string_alloc(username);
2218 if (!escape_username) {
2219 status = NT_STATUS_NO_MEMORY;
2220 goto fn_exit;
2223 if (username[strlen(username)-1] == '$') {
2224 dn = talloc_asprintf(ctx,
2225 "uid=%s,%s",
2226 escape_username,
2227 lp_ldap_machine_suffix(talloc_tos()));
2228 } else {
2229 dn = talloc_asprintf(ctx,
2230 "uid=%s,%s",
2231 escape_username,
2232 lp_ldap_user_suffix(talloc_tos()));
2235 SAFE_FREE(escape_username);
2236 if (!dn) {
2237 status = NT_STATUS_NO_MEMORY;
2238 goto fn_exit;
2242 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2243 pdb_element_is_set_or_changed)) {
2244 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2245 if (mods != NULL) {
2246 ldap_mods_free(mods, true);
2248 goto fn_exit;
2251 if (mods == NULL) {
2252 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2253 goto fn_exit;
2255 switch ( ldap_state->schema_ver ) {
2256 case SCHEMAVER_SAMBASAMACCOUNT:
2257 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2258 break;
2259 default:
2260 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2261 break;
2264 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2265 if (!NT_STATUS_IS_OK(ret)) {
2266 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2267 pdb_get_username(newpwd),dn));
2268 ldap_mods_free(mods, true);
2269 goto fn_exit;
2272 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2273 ldap_mods_free(mods, true);
2275 status = NT_STATUS_OK;
2277 fn_exit:
2279 TALLOC_FREE(ctx);
2280 if (result) {
2281 ldap_msgfree(result);
2283 return status;
2286 /**********************************************************************
2287 *********************************************************************/
2289 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2290 const char *filter,
2291 LDAPMessage ** result)
2293 int scope = LDAP_SCOPE_SUBTREE;
2294 int rc;
2295 const char **attr_list;
2297 attr_list = get_attr_list(NULL, groupmap_attr_list);
2298 rc = smbldap_search(ldap_state->smbldap_state,
2299 lp_ldap_suffix (talloc_tos()), scope,
2300 filter, attr_list, 0, result);
2301 TALLOC_FREE(attr_list);
2303 return rc;
2306 /**********************************************************************
2307 *********************************************************************/
2309 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2310 GROUP_MAP *map, LDAPMessage *entry)
2312 char *temp = NULL;
2313 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2315 if (ldap_state == NULL || map == NULL || entry == NULL ||
2316 ldap_state->smbldap_state->ldap_struct == NULL) {
2317 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2318 TALLOC_FREE(ctx);
2319 return false;
2322 temp = smbldap_talloc_single_attribute(
2323 ldap_state->smbldap_state->ldap_struct,
2324 entry,
2325 get_attr_key2string(groupmap_attr_list,
2326 LDAP_ATTR_GIDNUMBER),
2327 ctx);
2328 if (!temp) {
2329 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2330 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2331 TALLOC_FREE(ctx);
2332 return false;
2334 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2336 map->gid = (gid_t)atol(temp);
2338 TALLOC_FREE(temp);
2339 temp = smbldap_talloc_single_attribute(
2340 ldap_state->smbldap_state->ldap_struct,
2341 entry,
2342 get_attr_key2string(groupmap_attr_list,
2343 LDAP_ATTR_GROUP_SID),
2344 ctx);
2345 if (!temp) {
2346 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2347 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2348 TALLOC_FREE(ctx);
2349 return false;
2352 if (!string_to_sid(&map->sid, temp)) {
2353 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2354 TALLOC_FREE(ctx);
2355 return false;
2358 TALLOC_FREE(temp);
2359 temp = smbldap_talloc_single_attribute(
2360 ldap_state->smbldap_state->ldap_struct,
2361 entry,
2362 get_attr_key2string(groupmap_attr_list,
2363 LDAP_ATTR_GROUP_TYPE),
2364 ctx);
2365 if (!temp) {
2366 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2367 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2368 TALLOC_FREE(ctx);
2369 return false;
2371 map->sid_name_use = (enum lsa_SidType)atol(temp);
2373 if ((map->sid_name_use < SID_NAME_USER) ||
2374 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2375 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2376 TALLOC_FREE(ctx);
2377 return false;
2380 TALLOC_FREE(temp);
2381 temp = smbldap_talloc_single_attribute(
2382 ldap_state->smbldap_state->ldap_struct,
2383 entry,
2384 get_attr_key2string(groupmap_attr_list,
2385 LDAP_ATTR_DISPLAY_NAME),
2386 ctx);
2387 if (!temp) {
2388 temp = smbldap_talloc_single_attribute(
2389 ldap_state->smbldap_state->ldap_struct,
2390 entry,
2391 get_attr_key2string(groupmap_attr_list,
2392 LDAP_ATTR_CN),
2393 ctx);
2394 if (!temp) {
2395 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2396 for gidNumber(%lu)\n",(unsigned long)map->gid));
2397 TALLOC_FREE(ctx);
2398 return false;
2401 map->nt_name = talloc_strdup(map, temp);
2402 if (!map->nt_name) {
2403 TALLOC_FREE(ctx);
2404 return false;
2407 TALLOC_FREE(temp);
2408 temp = smbldap_talloc_single_attribute(
2409 ldap_state->smbldap_state->ldap_struct,
2410 entry,
2411 get_attr_key2string(groupmap_attr_list,
2412 LDAP_ATTR_DESC),
2413 ctx);
2414 if (!temp) {
2415 temp = talloc_strdup(ctx, "");
2416 if (!temp) {
2417 TALLOC_FREE(ctx);
2418 return false;
2421 map->comment = talloc_strdup(map, temp);
2422 if (!map->comment) {
2423 TALLOC_FREE(ctx);
2424 return false;
2427 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2428 struct unixid id;
2429 id.id = map->gid;
2430 id.type = ID_TYPE_GID;
2432 idmap_cache_set_sid2unixid(&map->sid, &id);
2435 TALLOC_FREE(ctx);
2436 return true;
2439 /**********************************************************************
2440 *********************************************************************/
2442 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2443 const char *filter,
2444 GROUP_MAP *map)
2446 struct ldapsam_privates *ldap_state =
2447 (struct ldapsam_privates *)methods->private_data;
2448 LDAPMessage *result = NULL;
2449 LDAPMessage *entry = NULL;
2450 int count;
2452 if (ldapsam_search_one_group(ldap_state, filter, &result)
2453 != LDAP_SUCCESS) {
2454 return NT_STATUS_NO_SUCH_GROUP;
2457 count = ldap_count_entries(priv2ld(ldap_state), result);
2459 if (count < 1) {
2460 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2461 "%s\n", filter));
2462 ldap_msgfree(result);
2463 return NT_STATUS_NO_SUCH_GROUP;
2466 if (count > 1) {
2467 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2468 "count=%d\n", filter, count));
2469 ldap_msgfree(result);
2470 return NT_STATUS_NO_SUCH_GROUP;
2473 entry = ldap_first_entry(priv2ld(ldap_state), result);
2475 if (!entry) {
2476 ldap_msgfree(result);
2477 return NT_STATUS_UNSUCCESSFUL;
2480 if (!init_group_from_ldap(ldap_state, map, entry)) {
2481 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2482 "group filter %s\n", filter));
2483 ldap_msgfree(result);
2484 return NT_STATUS_NO_SUCH_GROUP;
2487 ldap_msgfree(result);
2488 return NT_STATUS_OK;
2491 /**********************************************************************
2492 *********************************************************************/
2494 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2495 struct dom_sid sid)
2497 char *filter = NULL;
2498 NTSTATUS status;
2499 fstring tmp;
2501 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2502 LDAP_OBJ_GROUPMAP,
2503 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2504 sid_to_fstring(tmp, &sid)) < 0) {
2505 return NT_STATUS_NO_MEMORY;
2508 status = ldapsam_getgroup(methods, filter, map);
2509 SAFE_FREE(filter);
2510 return status;
2513 /**********************************************************************
2514 *********************************************************************/
2516 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2517 gid_t gid)
2519 char *filter = NULL;
2520 NTSTATUS status;
2522 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2523 LDAP_OBJ_GROUPMAP,
2524 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2525 (unsigned long)gid) < 0) {
2526 return NT_STATUS_NO_MEMORY;
2529 status = ldapsam_getgroup(methods, filter, map);
2530 SAFE_FREE(filter);
2531 return status;
2534 /**********************************************************************
2535 *********************************************************************/
2537 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2538 const char *name)
2540 char *filter = NULL;
2541 char *escape_name = escape_ldap_string(talloc_tos(), name);
2542 NTSTATUS status;
2544 if (!escape_name) {
2545 return NT_STATUS_NO_MEMORY;
2548 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2549 LDAP_OBJ_GROUPMAP,
2550 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2551 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2552 escape_name) < 0) {
2553 TALLOC_FREE(escape_name);
2554 return NT_STATUS_NO_MEMORY;
2557 TALLOC_FREE(escape_name);
2558 status = ldapsam_getgroup(methods, filter, map);
2559 SAFE_FREE(filter);
2560 return status;
2563 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2564 LDAPMessage *entry,
2565 const struct dom_sid *domain_sid,
2566 uint32_t *rid)
2568 fstring str;
2569 struct dom_sid sid;
2571 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2572 str, sizeof(str)-1)) {
2573 DEBUG(10, ("Could not find sambaSID attribute\n"));
2574 return False;
2577 if (!string_to_sid(&sid, str)) {
2578 DEBUG(10, ("Could not convert string %s to sid\n", str));
2579 return False;
2582 if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2583 DEBUG(10, ("SID %s is not in expected domain %s\n",
2584 str, sid_string_dbg(domain_sid)));
2585 return False;
2588 if (!sid_peek_rid(&sid, rid)) {
2589 DEBUG(10, ("Could not peek into RID\n"));
2590 return False;
2593 return True;
2596 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2597 TALLOC_CTX *mem_ctx,
2598 const struct dom_sid *group,
2599 uint32_t **pp_member_rids,
2600 size_t *p_num_members)
2602 struct ldapsam_privates *ldap_state =
2603 (struct ldapsam_privates *)methods->private_data;
2604 struct smbldap_state *conn = ldap_state->smbldap_state;
2605 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2606 const char *sid_attrs[] = { "sambaSID", NULL };
2607 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2608 LDAPMessage *result = NULL;
2609 LDAPMessage *entry;
2610 char *filter;
2611 char **values = NULL;
2612 char **memberuid;
2613 char *gidstr;
2614 int rc, count;
2616 *pp_member_rids = NULL;
2617 *p_num_members = 0;
2619 filter = talloc_asprintf(mem_ctx,
2620 "(&(objectClass=%s)"
2621 "(objectClass=%s)"
2622 "(sambaSID=%s))",
2623 LDAP_OBJ_POSIXGROUP,
2624 LDAP_OBJ_GROUPMAP,
2625 sid_string_talloc(mem_ctx, group));
2626 if (filter == NULL) {
2627 ret = NT_STATUS_NO_MEMORY;
2628 goto done;
2631 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2632 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2633 &result);
2635 if (rc != LDAP_SUCCESS)
2636 goto done;
2638 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2640 count = ldap_count_entries(conn->ldap_struct, result);
2642 if (count > 1) {
2643 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2644 sid_string_dbg(group)));
2645 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2646 goto done;
2649 if (count == 0) {
2650 ret = NT_STATUS_NO_SUCH_GROUP;
2651 goto done;
2654 entry = ldap_first_entry(conn->ldap_struct, result);
2655 if (entry == NULL)
2656 goto done;
2658 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2659 if (!gidstr) {
2660 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2661 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2662 goto done;
2665 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2667 if ((values != NULL) && (values[0] != NULL)) {
2669 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2670 if (filter == NULL) {
2671 ret = NT_STATUS_NO_MEMORY;
2672 goto done;
2675 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2676 char *escape_memberuid;
2678 escape_memberuid = escape_ldap_string(talloc_tos(),
2679 *memberuid);
2680 if (escape_memberuid == NULL) {
2681 ret = NT_STATUS_NO_MEMORY;
2682 goto done;
2685 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2686 TALLOC_FREE(escape_memberuid);
2687 if (filter == NULL) {
2688 ret = NT_STATUS_NO_MEMORY;
2689 goto done;
2693 filter = talloc_asprintf_append_buffer(filter, "))");
2694 if (filter == NULL) {
2695 ret = NT_STATUS_NO_MEMORY;
2696 goto done;
2699 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2700 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2701 &result);
2703 if (rc != LDAP_SUCCESS)
2704 goto done;
2706 count = ldap_count_entries(conn->ldap_struct, result);
2707 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2709 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2711 for (entry = ldap_first_entry(conn->ldap_struct, result);
2712 entry != NULL;
2713 entry = ldap_next_entry(conn->ldap_struct, entry))
2715 char *sidstr;
2716 struct dom_sid sid;
2717 uint32_t rid;
2719 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2720 entry, "sambaSID",
2721 mem_ctx);
2722 if (!sidstr) {
2723 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2724 "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2725 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2726 goto done;
2729 if (!string_to_sid(&sid, sidstr))
2730 goto done;
2732 if (!sid_check_is_in_our_sam(&sid)) {
2733 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2734 "in our domain\n"));
2735 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2736 goto done;
2739 sid_peek_rid(&sid, &rid);
2741 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2742 p_num_members)) {
2743 ret = NT_STATUS_NO_MEMORY;
2744 goto done;
2749 filter = talloc_asprintf(mem_ctx,
2750 "(&(objectClass=%s)"
2751 "(gidNumber=%s))",
2752 LDAP_OBJ_SAMBASAMACCOUNT,
2753 gidstr);
2755 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2756 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2757 &result);
2759 if (rc != LDAP_SUCCESS)
2760 goto done;
2762 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2764 for (entry = ldap_first_entry(conn->ldap_struct, result);
2765 entry != NULL;
2766 entry = ldap_next_entry(conn->ldap_struct, entry))
2768 uint32_t rid;
2770 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2771 entry,
2772 get_global_sam_sid(),
2773 &rid)) {
2774 DEBUG(0, ("Severe DB error, %s can't miss the samba SID" "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2775 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2776 goto done;
2779 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2780 p_num_members)) {
2781 ret = NT_STATUS_NO_MEMORY;
2782 goto done;
2786 ret = NT_STATUS_OK;
2788 done:
2790 if (values)
2791 ldap_value_free(values);
2793 return ret;
2796 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2797 TALLOC_CTX *mem_ctx,
2798 struct samu *user,
2799 struct dom_sid **pp_sids,
2800 gid_t **pp_gids,
2801 uint32_t *p_num_groups)
2803 struct ldapsam_privates *ldap_state =
2804 (struct ldapsam_privates *)methods->private_data;
2805 struct smbldap_state *conn = ldap_state->smbldap_state;
2806 char *filter;
2807 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2808 char *escape_name;
2809 int rc, count;
2810 LDAPMessage *result = NULL;
2811 LDAPMessage *entry;
2812 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2813 uint32_t num_sids;
2814 uint32_t num_gids;
2815 char *gidstr;
2816 gid_t primary_gid = -1;
2818 *pp_sids = NULL;
2819 num_sids = 0;
2821 if (pdb_get_username(user) == NULL) {
2822 return NT_STATUS_INVALID_PARAMETER;
2825 escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2826 if (escape_name == NULL)
2827 return NT_STATUS_NO_MEMORY;
2829 if (user->unix_pw) {
2830 primary_gid = user->unix_pw->pw_gid;
2831 } else {
2832 /* retrieve the users primary gid */
2833 filter = talloc_asprintf(mem_ctx,
2834 "(&(objectClass=%s)(uid=%s))",
2835 LDAP_OBJ_SAMBASAMACCOUNT,
2836 escape_name);
2837 if (filter == NULL) {
2838 ret = NT_STATUS_NO_MEMORY;
2839 goto done;
2842 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2843 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2845 if (rc != LDAP_SUCCESS)
2846 goto done;
2848 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2850 count = ldap_count_entries(priv2ld(ldap_state), result);
2852 switch (count) {
2853 case 0:
2854 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2855 ret = NT_STATUS_NO_SUCH_USER;
2856 goto done;
2857 case 1:
2858 entry = ldap_first_entry(priv2ld(ldap_state), result);
2860 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2861 if (!gidstr) {
2862 DEBUG (1, ("Unable to find the member's gid!\n"));
2863 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2864 goto done;
2866 primary_gid = strtoul(gidstr, NULL, 10);
2867 break;
2868 default:
2869 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2870 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2871 goto done;
2875 filter = talloc_asprintf(mem_ctx,
2876 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2877 LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2878 if (filter == NULL) {
2879 ret = NT_STATUS_NO_MEMORY;
2880 goto done;
2883 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2884 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2886 if (rc != LDAP_SUCCESS)
2887 goto done;
2889 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2891 num_gids = 0;
2892 *pp_gids = NULL;
2894 num_sids = 0;
2895 *pp_sids = NULL;
2897 /* We need to add the primary group as the first gid/sid */
2899 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2900 ret = NT_STATUS_NO_MEMORY;
2901 goto done;
2904 /* This sid will be replaced later */
2906 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2907 &num_sids);
2908 if (!NT_STATUS_IS_OK(ret)) {
2909 goto done;
2912 for (entry = ldap_first_entry(conn->ldap_struct, result);
2913 entry != NULL;
2914 entry = ldap_next_entry(conn->ldap_struct, entry))
2916 fstring str;
2917 struct dom_sid sid;
2918 gid_t gid;
2919 char *end;
2921 if (!smbldap_get_single_attribute(conn->ldap_struct,
2922 entry, "sambaSID",
2923 str, sizeof(str)-1))
2924 continue;
2926 if (!string_to_sid(&sid, str))
2927 goto done;
2929 if (!smbldap_get_single_attribute(conn->ldap_struct,
2930 entry, "gidNumber",
2931 str, sizeof(str)-1))
2932 continue;
2934 gid = strtoul(str, &end, 10);
2936 if (PTR_DIFF(end, str) != strlen(str))
2937 goto done;
2939 if (gid == primary_gid) {
2940 sid_copy(&(*pp_sids)[0], &sid);
2941 } else {
2942 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2943 &num_gids)) {
2944 ret = NT_STATUS_NO_MEMORY;
2945 goto done;
2947 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2948 &num_sids);
2949 if (!NT_STATUS_IS_OK(ret)) {
2950 goto done;
2955 if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2956 DEBUG(3, ("primary group of [%s] not found\n",
2957 pdb_get_username(user)));
2958 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2959 goto done;
2962 *p_num_groups = num_sids;
2964 ret = NT_STATUS_OK;
2966 done:
2968 TALLOC_FREE(escape_name);
2969 return ret;
2972 /**********************************************************************
2973 * Augment a posixGroup object with a sambaGroupMapping domgroup
2974 *********************************************************************/
2976 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2977 struct ldapsam_privates *ldap_state,
2978 GROUP_MAP *map)
2980 const char *filter, *dn;
2981 LDAPMessage *msg, *entry;
2982 LDAPMod **mods;
2983 int rc;
2985 filter = talloc_asprintf(mem_ctx,
2986 "(&(objectClass=%s)(gidNumber=%u))",
2987 LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2988 if (filter == NULL) {
2989 return NT_STATUS_NO_MEMORY;
2992 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2993 get_attr_list(mem_ctx, groupmap_attr_list),
2994 &msg);
2995 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
2997 if ((rc != LDAP_SUCCESS) ||
2998 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2999 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3000 return NT_STATUS_NO_SUCH_GROUP;
3003 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3004 if (dn == NULL) {
3005 return NT_STATUS_NO_MEMORY;
3008 mods = NULL;
3009 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3010 LDAP_OBJ_GROUPMAP);
3011 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3012 sid_string_talloc(mem_ctx, &map->sid));
3013 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3014 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3015 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3016 map->nt_name);
3017 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3018 map->comment);
3019 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3021 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3022 if (rc != LDAP_SUCCESS) {
3023 return NT_STATUS_ACCESS_DENIED;
3026 return NT_STATUS_OK;
3029 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3030 GROUP_MAP *map)
3032 struct ldapsam_privates *ldap_state =
3033 (struct ldapsam_privates *)methods->private_data;
3034 LDAPMessage *msg = NULL;
3035 LDAPMod **mods = NULL;
3036 const char *attrs[] = { NULL };
3037 char *filter;
3039 char *dn;
3040 TALLOC_CTX *mem_ctx;
3041 NTSTATUS result;
3043 struct dom_sid sid;
3045 int rc;
3047 mem_ctx = talloc_new(NULL);
3048 if (mem_ctx == NULL) {
3049 DEBUG(0, ("talloc_new failed\n"));
3050 return NT_STATUS_NO_MEMORY;
3053 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3054 sid_string_talloc(mem_ctx, &map->sid));
3055 if (filter == NULL) {
3056 result = NT_STATUS_NO_MEMORY;
3057 goto done;
3060 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3061 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3062 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3064 if ((rc == LDAP_SUCCESS) &&
3065 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3067 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3068 "group mapping entry\n", sid_string_dbg(&map->sid)));
3069 result = NT_STATUS_GROUP_EXISTS;
3070 goto done;
3073 switch (map->sid_name_use) {
3075 case SID_NAME_DOM_GRP:
3076 /* To map a domain group we need to have a posix group
3077 to attach to. */
3078 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3079 goto done;
3080 break;
3082 case SID_NAME_ALIAS:
3083 if (!sid_check_is_in_our_sam(&map->sid)
3084 && !sid_check_is_in_builtin(&map->sid) )
3086 DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3087 sid_string_dbg(&map->sid)));
3088 result = NT_STATUS_INVALID_PARAMETER;
3089 goto done;
3091 break;
3093 default:
3094 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3095 sid_type_lookup(map->sid_name_use)));
3096 result = NT_STATUS_INVALID_PARAMETER;
3097 goto done;
3100 /* Domain groups have been mapped in a separate routine, we have to
3101 * create an alias now */
3103 if (map->gid == -1) {
3104 DEBUG(10, ("Refusing to map gid==-1\n"));
3105 result = NT_STATUS_INVALID_PARAMETER;
3106 goto done;
3109 if (pdb_gid_to_sid(map->gid, &sid)) {
3110 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3111 "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3112 result = NT_STATUS_GROUP_EXISTS;
3113 goto done;
3116 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3117 * the best we can get out of LDAP. */
3119 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3120 sid_string_talloc(mem_ctx, &map->sid),
3121 lp_ldap_group_suffix(talloc_tos()));
3122 if (dn == NULL) {
3123 result = NT_STATUS_NO_MEMORY;
3124 goto done;
3127 mods = NULL;
3129 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3130 LDAP_OBJ_SID_ENTRY);
3131 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3132 LDAP_OBJ_GROUPMAP);
3133 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3134 sid_string_talloc(mem_ctx, &map->sid));
3135 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3136 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3137 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3138 map->nt_name);
3139 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3140 map->comment);
3141 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3142 talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3143 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3145 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3147 result = (rc == LDAP_SUCCESS) ?
3148 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3150 done:
3151 TALLOC_FREE(mem_ctx);
3152 return result;
3155 /**********************************************************************
3156 * Update a group mapping entry. We're quite strict about what can be changed:
3157 * Only the description and displayname may be changed. It simply does not
3158 * make any sense to change the SID, gid or the type in a mapping.
3159 *********************************************************************/
3161 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3162 GROUP_MAP *map)
3164 struct ldapsam_privates *ldap_state =
3165 (struct ldapsam_privates *)methods->private_data;
3166 int rc;
3167 const char *filter, *dn;
3168 LDAPMessage *msg = NULL;
3169 LDAPMessage *entry = NULL;
3170 LDAPMod **mods = NULL;
3171 TALLOC_CTX *mem_ctx;
3172 NTSTATUS result;
3174 mem_ctx = talloc_new(NULL);
3175 if (mem_ctx == NULL) {
3176 DEBUG(0, ("talloc_new failed\n"));
3177 return NT_STATUS_NO_MEMORY;
3180 /* Make 100% sure that sid, gid and type are not changed by looking up
3181 * exactly the values we're given in LDAP. */
3183 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3184 "(sambaSid=%s)(gidNumber=%u)"
3185 "(sambaGroupType=%d))",
3186 LDAP_OBJ_GROUPMAP,
3187 sid_string_talloc(mem_ctx, &map->sid),
3188 (unsigned int)map->gid, map->sid_name_use);
3189 if (filter == NULL) {
3190 result = NT_STATUS_NO_MEMORY;
3191 goto done;
3194 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3195 get_attr_list(mem_ctx, groupmap_attr_list),
3196 &msg);
3197 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3199 if ((rc != LDAP_SUCCESS) ||
3200 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3201 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3202 result = NT_STATUS_NO_SUCH_GROUP;
3203 goto done;
3206 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3208 if (dn == NULL) {
3209 result = NT_STATUS_NO_MEMORY;
3210 goto done;
3213 mods = NULL;
3214 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3215 map->nt_name);
3216 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3217 map->comment);
3218 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3220 if (mods == NULL) {
3221 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3222 "nothing to do\n"));
3223 result = NT_STATUS_OK;
3224 goto done;
3227 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3229 if (rc != LDAP_SUCCESS) {
3230 result = NT_STATUS_ACCESS_DENIED;
3231 goto done;
3234 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3235 "group %lu in LDAP\n", (unsigned long)map->gid));
3237 result = NT_STATUS_OK;
3239 done:
3240 TALLOC_FREE(mem_ctx);
3241 return result;
3244 /**********************************************************************
3245 *********************************************************************/
3247 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3248 struct dom_sid sid)
3250 struct ldapsam_privates *priv =
3251 (struct ldapsam_privates *)methods->private_data;
3252 LDAPMessage *msg, *entry;
3253 int rc;
3254 NTSTATUS result;
3255 TALLOC_CTX *mem_ctx;
3256 char *filter;
3258 mem_ctx = talloc_new(NULL);
3259 if (mem_ctx == NULL) {
3260 DEBUG(0, ("talloc_new failed\n"));
3261 return NT_STATUS_NO_MEMORY;
3264 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3265 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3266 sid_string_talloc(mem_ctx, &sid));
3267 if (filter == NULL) {
3268 result = NT_STATUS_NO_MEMORY;
3269 goto done;
3271 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3272 get_attr_list(mem_ctx, groupmap_attr_list),
3273 &msg);
3274 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3276 if ((rc != LDAP_SUCCESS) ||
3277 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3278 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3279 result = NT_STATUS_NO_SUCH_GROUP;
3280 goto done;
3283 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3284 get_attr_list(mem_ctx,
3285 groupmap_attr_list_to_delete));
3287 if ((rc == LDAP_NAMING_VIOLATION) ||
3288 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3289 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3290 const char *attrs[] = { "sambaGroupType", "description",
3291 "displayName", "sambaSIDList",
3292 NULL };
3294 /* Second try. Don't delete the sambaSID attribute, this is
3295 for "old" entries that are tacked on a winbind
3296 sambaIdmapEntry. */
3298 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3299 LDAP_OBJ_GROUPMAP, attrs);
3302 if ((rc == LDAP_NAMING_VIOLATION) ||
3303 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3304 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3305 const char *attrs[] = { "sambaGroupType", "description",
3306 "displayName", "sambaSIDList",
3307 "gidNumber", NULL };
3309 /* Third try. This is a post-3.0.21 alias (containing only
3310 * sambaSidEntry and sambaGroupMapping classes), we also have
3311 * to delete the gidNumber attribute, only the sambaSidEntry
3312 * remains */
3314 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3315 LDAP_OBJ_GROUPMAP, attrs);
3318 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3320 done:
3321 TALLOC_FREE(mem_ctx);
3322 return result;
3325 /**********************************************************************
3326 *********************************************************************/
3328 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3329 bool update)
3331 struct ldapsam_privates *ldap_state =
3332 (struct ldapsam_privates *)my_methods->private_data;
3333 char *filter = NULL;
3334 int rc;
3335 const char **attr_list;
3337 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3338 if (!filter) {
3339 return NT_STATUS_NO_MEMORY;
3341 attr_list = get_attr_list( NULL, groupmap_attr_list );
3342 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3343 LDAP_SCOPE_SUBTREE, filter,
3344 attr_list, 0, &ldap_state->result);
3345 TALLOC_FREE(attr_list);
3347 if (rc != LDAP_SUCCESS) {
3348 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3349 ldap_err2string(rc)));
3350 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3351 lp_ldap_suffix(talloc_tos()), filter));
3352 ldap_msgfree(ldap_state->result);
3353 ldap_state->result = NULL;
3354 TALLOC_FREE(filter);
3355 return NT_STATUS_UNSUCCESSFUL;
3358 TALLOC_FREE(filter);
3360 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3361 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3362 ldap_state->result)));
3364 ldap_state->entry =
3365 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3366 ldap_state->result);
3367 ldap_state->index = 0;
3369 return NT_STATUS_OK;
3372 /**********************************************************************
3373 *********************************************************************/
3375 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3377 ldapsam_endsampwent(my_methods);
3380 /**********************************************************************
3381 *********************************************************************/
3383 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3384 GROUP_MAP *map)
3386 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3387 struct ldapsam_privates *ldap_state =
3388 (struct ldapsam_privates *)my_methods->private_data;
3389 bool bret = False;
3391 while (!bret) {
3392 if (!ldap_state->entry)
3393 return ret;
3395 ldap_state->index++;
3396 bret = init_group_from_ldap(ldap_state, map,
3397 ldap_state->entry);
3399 ldap_state->entry =
3400 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3401 ldap_state->entry);
3404 return NT_STATUS_OK;
3407 /**********************************************************************
3408 *********************************************************************/
3410 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3411 const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3412 GROUP_MAP ***pp_rmap,
3413 size_t *p_num_entries,
3414 bool unix_only)
3416 GROUP_MAP *map = NULL;
3417 size_t entries = 0;
3419 *p_num_entries = 0;
3420 *pp_rmap = NULL;
3422 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3423 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3424 "passdb\n"));
3425 return NT_STATUS_ACCESS_DENIED;
3428 while (true) {
3430 map = talloc_zero(NULL, GROUP_MAP);
3431 if (!map) {
3432 return NT_STATUS_NO_MEMORY;
3435 if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
3436 TALLOC_FREE(map);
3437 break;
3440 if (sid_name_use != SID_NAME_UNKNOWN &&
3441 sid_name_use != map->sid_name_use) {
3442 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3443 "not of the requested type\n",
3444 map->nt_name));
3445 continue;
3447 if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
3448 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3449 "non mapped\n", map->nt_name));
3450 continue;
3453 *pp_rmap = talloc_realloc(NULL, *pp_rmap,
3454 GROUP_MAP *, entries + 1);
3455 if (!(*pp_rmap)) {
3456 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3457 "enlarge group map!\n"));
3458 return NT_STATUS_UNSUCCESSFUL;
3461 (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
3463 entries += 1;
3466 ldapsam_endsamgrent(methods);
3468 *p_num_entries = entries;
3470 return NT_STATUS_OK;
3473 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3474 const struct dom_sid *alias,
3475 const struct dom_sid *member,
3476 int modop)
3478 struct ldapsam_privates *ldap_state =
3479 (struct ldapsam_privates *)methods->private_data;
3480 char *dn = NULL;
3481 LDAPMessage *result = NULL;
3482 LDAPMessage *entry = NULL;
3483 int count;
3484 LDAPMod **mods = NULL;
3485 int rc;
3486 enum lsa_SidType type = SID_NAME_USE_NONE;
3487 fstring tmp;
3489 char *filter = NULL;
3491 if (sid_check_is_in_builtin(alias)) {
3492 type = SID_NAME_ALIAS;
3495 if (sid_check_is_in_our_sam(alias)) {
3496 type = SID_NAME_ALIAS;
3499 if (type == SID_NAME_USE_NONE) {
3500 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3501 sid_string_dbg(alias)));
3502 return NT_STATUS_NO_SUCH_ALIAS;
3505 if (asprintf(&filter,
3506 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3507 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3508 type) < 0) {
3509 return NT_STATUS_NO_MEMORY;
3512 if (ldapsam_search_one_group(ldap_state, filter,
3513 &result) != LDAP_SUCCESS) {
3514 SAFE_FREE(filter);
3515 return NT_STATUS_NO_SUCH_ALIAS;
3518 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3519 result);
3521 if (count < 1) {
3522 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3523 ldap_msgfree(result);
3524 SAFE_FREE(filter);
3525 return NT_STATUS_NO_SUCH_ALIAS;
3528 if (count > 1) {
3529 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3530 "filter %s: count=%d\n", filter, count));
3531 ldap_msgfree(result);
3532 SAFE_FREE(filter);
3533 return NT_STATUS_NO_SUCH_ALIAS;
3536 SAFE_FREE(filter);
3538 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3539 result);
3541 if (!entry) {
3542 ldap_msgfree(result);
3543 return NT_STATUS_UNSUCCESSFUL;
3546 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3547 if (!dn) {
3548 ldap_msgfree(result);
3549 return NT_STATUS_UNSUCCESSFUL;
3552 smbldap_set_mod(&mods, modop,
3553 get_attr_key2string(groupmap_attr_list,
3554 LDAP_ATTR_SID_LIST),
3555 sid_to_fstring(tmp, member));
3557 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3559 ldap_mods_free(mods, True);
3560 ldap_msgfree(result);
3561 TALLOC_FREE(dn);
3563 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3564 return NT_STATUS_MEMBER_IN_ALIAS;
3567 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3568 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3571 if (rc != LDAP_SUCCESS) {
3572 return NT_STATUS_UNSUCCESSFUL;
3575 return NT_STATUS_OK;
3578 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3579 const struct dom_sid *alias,
3580 const struct dom_sid *member)
3582 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3585 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3586 const struct dom_sid *alias,
3587 const struct dom_sid *member)
3589 return ldapsam_modify_aliasmem(methods, alias, member,
3590 LDAP_MOD_DELETE);
3593 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3594 const struct dom_sid *alias,
3595 TALLOC_CTX *mem_ctx,
3596 struct dom_sid **pp_members,
3597 size_t *p_num_members)
3599 struct ldapsam_privates *ldap_state =
3600 (struct ldapsam_privates *)methods->private_data;
3601 LDAPMessage *result = NULL;
3602 LDAPMessage *entry = NULL;
3603 int count;
3604 char **values = NULL;
3605 int i;
3606 char *filter = NULL;
3607 uint32_t num_members = 0;
3608 enum lsa_SidType type = SID_NAME_USE_NONE;
3609 fstring tmp;
3611 *pp_members = NULL;
3612 *p_num_members = 0;
3614 if (sid_check_is_in_builtin(alias)) {
3615 type = SID_NAME_ALIAS;
3618 if (sid_check_is_in_our_sam(alias)) {
3619 type = SID_NAME_ALIAS;
3622 if (type == SID_NAME_USE_NONE) {
3623 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3624 sid_string_dbg(alias)));
3625 return NT_STATUS_NO_SUCH_ALIAS;
3628 if (asprintf(&filter,
3629 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3630 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3631 type) < 0) {
3632 return NT_STATUS_NO_MEMORY;
3635 if (ldapsam_search_one_group(ldap_state, filter,
3636 &result) != LDAP_SUCCESS) {
3637 SAFE_FREE(filter);
3638 return NT_STATUS_NO_SUCH_ALIAS;
3641 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3642 result);
3644 if (count < 1) {
3645 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3646 ldap_msgfree(result);
3647 SAFE_FREE(filter);
3648 return NT_STATUS_NO_SUCH_ALIAS;
3651 if (count > 1) {
3652 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3653 "filter %s: count=%d\n", filter, count));
3654 ldap_msgfree(result);
3655 SAFE_FREE(filter);
3656 return NT_STATUS_NO_SUCH_ALIAS;
3659 SAFE_FREE(filter);
3661 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3662 result);
3664 if (!entry) {
3665 ldap_msgfree(result);
3666 return NT_STATUS_UNSUCCESSFUL;
3669 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3670 entry,
3671 get_attr_key2string(groupmap_attr_list,
3672 LDAP_ATTR_SID_LIST));
3674 if (values == NULL) {
3675 ldap_msgfree(result);
3676 return NT_STATUS_OK;
3679 count = ldap_count_values(values);
3681 for (i=0; i<count; i++) {
3682 struct dom_sid member;
3683 NTSTATUS status;
3685 if (!string_to_sid(&member, values[i]))
3686 continue;
3688 status = add_sid_to_array(mem_ctx, &member, pp_members,
3689 &num_members);
3690 if (!NT_STATUS_IS_OK(status)) {
3691 ldap_value_free(values);
3692 ldap_msgfree(result);
3693 return status;
3697 *p_num_members = num_members;
3698 ldap_value_free(values);
3699 ldap_msgfree(result);
3701 return NT_STATUS_OK;
3704 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3705 TALLOC_CTX *mem_ctx,
3706 const struct dom_sid *domain_sid,
3707 const struct dom_sid *members,
3708 size_t num_members,
3709 uint32_t **pp_alias_rids,
3710 size_t *p_num_alias_rids)
3712 struct ldapsam_privates *ldap_state =
3713 (struct ldapsam_privates *)methods->private_data;
3714 LDAP *ldap_struct;
3716 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3718 LDAPMessage *result = NULL;
3719 LDAPMessage *entry = NULL;
3720 int i;
3721 int rc;
3722 char *filter;
3723 enum lsa_SidType type = SID_NAME_USE_NONE;
3724 bool is_builtin = false;
3725 bool sid_added = false;
3727 *pp_alias_rids = NULL;
3728 *p_num_alias_rids = 0;
3730 if (sid_check_is_builtin(domain_sid)) {
3731 is_builtin = true;
3732 type = SID_NAME_ALIAS;
3735 if (sid_check_is_our_sam(domain_sid)) {
3736 type = SID_NAME_ALIAS;
3739 if (type == SID_NAME_USE_NONE) {
3740 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3741 sid_string_dbg(domain_sid)));
3742 return NT_STATUS_UNSUCCESSFUL;
3745 if (num_members == 0) {
3746 return NT_STATUS_OK;
3749 filter = talloc_asprintf(mem_ctx,
3750 "(&(objectclass=%s)(sambaGroupType=%d)(|",
3751 LDAP_OBJ_GROUPMAP, type);
3753 for (i=0; i<num_members; i++)
3754 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3755 filter,
3756 sid_string_talloc(mem_ctx,
3757 &members[i]));
3759 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3761 if (filter == NULL) {
3762 return NT_STATUS_NO_MEMORY;
3765 if (is_builtin &&
3766 ldap_state->search_cache.filter &&
3767 strcmp(ldap_state->search_cache.filter, filter) == 0) {
3768 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3769 result = ldap_state->search_cache.result;
3770 ldap_state->search_cache.result = NULL;
3771 } else {
3772 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3773 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3774 if (rc != LDAP_SUCCESS) {
3775 return NT_STATUS_UNSUCCESSFUL;
3777 smbldap_talloc_autofree_ldapmsg(filter, result);
3780 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3782 for (entry = ldap_first_entry(ldap_struct, result);
3783 entry != NULL;
3784 entry = ldap_next_entry(ldap_struct, entry))
3786 fstring sid_str;
3787 struct dom_sid sid;
3788 uint32_t rid;
3790 if (!smbldap_get_single_attribute(ldap_struct, entry,
3791 LDAP_ATTRIBUTE_SID,
3792 sid_str,
3793 sizeof(sid_str)-1))
3794 continue;
3796 if (!string_to_sid(&sid, sid_str))
3797 continue;
3799 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3800 continue;
3802 sid_added = true;
3804 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3805 p_num_alias_rids)) {
3806 return NT_STATUS_NO_MEMORY;
3810 if (!is_builtin && !sid_added) {
3811 TALLOC_FREE(ldap_state->search_cache.filter);
3813 * Note: result is a talloc child of filter because of the
3814 * smbldap_talloc_autofree_ldapmsg() usage
3816 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3817 ldap_state->search_cache.result = result;
3820 return NT_STATUS_OK;
3823 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3824 enum pdb_policy_type type,
3825 uint32_t value)
3827 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3828 int rc;
3829 LDAPMod **mods = NULL;
3830 fstring value_string;
3831 const char *policy_attr = NULL;
3833 struct ldapsam_privates *ldap_state =
3834 (struct ldapsam_privates *)methods->private_data;
3836 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3838 if (!ldap_state->domain_dn) {
3839 return NT_STATUS_INVALID_PARAMETER;
3842 policy_attr = get_account_policy_attr(type);
3843 if (policy_attr == NULL) {
3844 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3845 "policy\n"));
3846 return ntstatus;
3849 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3851 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3853 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3854 mods);
3856 ldap_mods_free(mods, True);
3858 if (rc != LDAP_SUCCESS) {
3859 return ntstatus;
3862 if (!cache_account_policy_set(type, value)) {
3863 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3864 "update local tdb cache\n"));
3865 return ntstatus;
3868 return NT_STATUS_OK;
3871 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3872 enum pdb_policy_type type,
3873 uint32_t value)
3875 return ldapsam_set_account_policy_in_ldap(methods, type,
3876 value);
3879 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3880 enum pdb_policy_type type,
3881 uint32_t *value)
3883 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3884 LDAPMessage *result = NULL;
3885 LDAPMessage *entry = NULL;
3886 int count;
3887 int rc;
3888 char **vals = NULL;
3889 char *filter;
3890 const char *policy_attr = NULL;
3892 struct ldapsam_privates *ldap_state =
3893 (struct ldapsam_privates *)methods->private_data;
3895 const char *attrs[2];
3897 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3899 if (!ldap_state->domain_dn) {
3900 return NT_STATUS_INVALID_PARAMETER;
3903 policy_attr = get_account_policy_attr(type);
3904 if (!policy_attr) {
3905 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3906 "policy index: %d\n", type));
3907 return ntstatus;
3910 attrs[0] = policy_attr;
3911 attrs[1] = NULL;
3913 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3914 if (filter == NULL) {
3915 return NT_STATUS_NO_MEMORY;
3917 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3918 LDAP_SCOPE_BASE, filter, attrs, 0,
3919 &result);
3920 TALLOC_FREE(filter);
3921 if (rc != LDAP_SUCCESS) {
3922 return ntstatus;
3925 count = ldap_count_entries(priv2ld(ldap_state), result);
3926 if (count < 1) {
3927 goto out;
3930 entry = ldap_first_entry(priv2ld(ldap_state), result);
3931 if (entry == NULL) {
3932 goto out;
3935 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3936 if (vals == NULL) {
3937 goto out;
3940 *value = (uint32_t)atol(vals[0]);
3942 ntstatus = NT_STATUS_OK;
3944 out:
3945 if (vals)
3946 ldap_value_free(vals);
3947 ldap_msgfree(result);
3949 return ntstatus;
3952 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3954 - if user hasn't decided to use account policies inside LDAP just reuse the
3955 old tdb values
3957 - if there is a valid cache entry, return that
3958 - if there is an LDAP entry, update cache and return
3959 - otherwise set to default, update cache and return
3961 Guenther
3963 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3964 enum pdb_policy_type type,
3965 uint32_t *value)
3967 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3969 if (cache_account_policy_get(type, value)) {
3970 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3971 "cache\n"));
3972 return NT_STATUS_OK;
3975 ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3976 value);
3977 if (NT_STATUS_IS_OK(ntstatus)) {
3978 goto update_cache;
3981 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3982 "ldap\n"));
3984 #if 0
3985 /* should we automagically migrate old tdb value here ? */
3986 if (account_policy_get(type, value))
3987 goto update_ldap;
3989 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3990 "default\n", type));
3991 #endif
3993 if (!account_policy_get_default(type, value)) {
3994 return ntstatus;
3997 /* update_ldap: */
3999 ntstatus = ldapsam_set_account_policy(methods, type, *value);
4000 if (!NT_STATUS_IS_OK(ntstatus)) {
4001 return ntstatus;
4004 update_cache:
4006 if (!cache_account_policy_set(type, *value)) {
4007 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
4008 "tdb as a cache\n"));
4009 return NT_STATUS_UNSUCCESSFUL;
4012 return NT_STATUS_OK;
4015 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
4016 const struct dom_sid *domain_sid,
4017 int num_rids,
4018 uint32_t *rids,
4019 const char **names,
4020 enum lsa_SidType *attrs)
4022 struct ldapsam_privates *ldap_state =
4023 (struct ldapsam_privates *)methods->private_data;
4024 LDAPMessage *msg = NULL;
4025 LDAPMessage *entry;
4026 char *allsids = NULL;
4027 int i, rc, num_mapped;
4028 NTSTATUS result = NT_STATUS_NO_MEMORY;
4029 TALLOC_CTX *mem_ctx;
4030 LDAP *ld;
4031 bool is_builtin;
4033 mem_ctx = talloc_new(NULL);
4034 if (mem_ctx == NULL) {
4035 DEBUG(0, ("talloc_new failed\n"));
4036 goto done;
4039 if (!sid_check_is_builtin(domain_sid) &&
4040 !sid_check_is_our_sam(domain_sid)) {
4041 result = NT_STATUS_INVALID_PARAMETER;
4042 goto done;
4045 if (num_rids == 0) {
4046 result = NT_STATUS_NONE_MAPPED;
4047 goto done;
4050 for (i=0; i<num_rids; i++)
4051 attrs[i] = SID_NAME_UNKNOWN;
4053 allsids = talloc_strdup(mem_ctx, "");
4054 if (allsids == NULL) {
4055 goto done;
4058 for (i=0; i<num_rids; i++) {
4059 struct dom_sid sid;
4060 sid_compose(&sid, domain_sid, rids[i]);
4061 allsids = talloc_asprintf_append_buffer(
4062 allsids, "(sambaSid=%s)",
4063 sid_string_talloc(mem_ctx, &sid));
4064 if (allsids == NULL) {
4065 goto done;
4069 /* First look for users */
4072 char *filter;
4073 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4075 filter = talloc_asprintf(
4076 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4077 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4079 if (filter == NULL) {
4080 goto done;
4083 rc = smbldap_search(ldap_state->smbldap_state,
4084 lp_ldap_user_suffix(talloc_tos()),
4085 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4086 &msg);
4087 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4090 if (rc != LDAP_SUCCESS)
4091 goto done;
4093 ld = ldap_state->smbldap_state->ldap_struct;
4094 num_mapped = 0;
4096 for (entry = ldap_first_entry(ld, msg);
4097 entry != NULL;
4098 entry = ldap_next_entry(ld, entry)) {
4099 uint32_t rid;
4100 int rid_index;
4101 const char *name;
4103 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4104 &rid)) {
4105 DEBUG(2, ("Could not find sid from ldap entry\n"));
4106 continue;
4109 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4110 names);
4111 if (name == NULL) {
4112 DEBUG(2, ("Could not retrieve uid attribute\n"));
4113 continue;
4116 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4117 if (rid == rids[rid_index])
4118 break;
4121 if (rid_index == num_rids) {
4122 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4123 continue;
4126 attrs[rid_index] = SID_NAME_USER;
4127 names[rid_index] = name;
4128 num_mapped += 1;
4131 if (num_mapped == num_rids) {
4132 /* No need to look for groups anymore -- we're done */
4133 result = NT_STATUS_OK;
4134 goto done;
4137 /* Same game for groups */
4140 char *filter;
4141 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4142 "sambaGroupType", NULL };
4144 filter = talloc_asprintf(
4145 mem_ctx, "(&(objectClass=%s)(|%s))",
4146 LDAP_OBJ_GROUPMAP, allsids);
4147 if (filter == NULL) {
4148 goto done;
4151 rc = smbldap_search(ldap_state->smbldap_state,
4152 lp_ldap_suffix(talloc_tos()),
4153 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4154 &msg);
4155 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4158 if (rc != LDAP_SUCCESS)
4159 goto done;
4161 /* ldap_struct might have changed due to a reconnect */
4163 ld = ldap_state->smbldap_state->ldap_struct;
4165 /* For consistency checks, we already checked we're only domain or builtin */
4167 is_builtin = sid_check_is_builtin(domain_sid);
4169 for (entry = ldap_first_entry(ld, msg);
4170 entry != NULL;
4171 entry = ldap_next_entry(ld, entry))
4173 uint32_t rid;
4174 int rid_index;
4175 const char *attr;
4176 enum lsa_SidType type;
4177 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4179 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4180 mem_ctx);
4181 if (attr == NULL) {
4182 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4183 dn));
4184 continue;
4187 type = (enum lsa_SidType)atol(attr);
4189 /* Consistency checks */
4190 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4191 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4192 (type != SID_NAME_DOM_GRP)))) {
4193 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4196 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4197 &rid)) {
4198 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4199 continue;
4202 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4204 if (attr == NULL) {
4205 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4206 dn));
4207 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4210 if (attr == NULL) {
4211 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4212 dn));
4213 continue;
4216 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4217 if (rid == rids[rid_index])
4218 break;
4221 if (rid_index == num_rids) {
4222 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4223 continue;
4226 attrs[rid_index] = type;
4227 names[rid_index] = attr;
4228 num_mapped += 1;
4231 result = NT_STATUS_NONE_MAPPED;
4233 if (num_mapped > 0)
4234 result = (num_mapped == num_rids) ?
4235 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4236 done:
4237 TALLOC_FREE(mem_ctx);
4238 return result;
4241 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4243 char *filter = NULL;
4244 char *escaped = NULL;
4245 char *result = NULL;
4247 if (asprintf(&filter, "(&%s(objectclass=%s))",
4248 "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4249 goto done;
4252 escaped = escape_ldap_string(talloc_tos(), username);
4253 if (escaped == NULL) goto done;
4255 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4257 done:
4258 SAFE_FREE(filter);
4259 TALLOC_FREE(escaped);
4261 return result;
4264 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4266 int i, num = 0;
4267 va_list ap;
4268 const char **result;
4270 va_start(ap, mem_ctx);
4271 while (va_arg(ap, const char *) != NULL)
4272 num += 1;
4273 va_end(ap);
4275 if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4276 return NULL;
4279 va_start(ap, mem_ctx);
4280 for (i=0; i<num; i++) {
4281 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4282 if (result[i] == NULL) {
4283 talloc_free(result);
4284 va_end(ap);
4285 return NULL;
4288 va_end(ap);
4290 result[num] = NULL;
4291 return result;
4294 struct ldap_search_state {
4295 struct smbldap_state *connection;
4297 uint32_t acct_flags;
4298 uint16_t group_type;
4300 const char *base;
4301 int scope;
4302 const char *filter;
4303 const char **attrs;
4304 int attrsonly;
4305 void *pagedresults_cookie;
4307 LDAPMessage *entries, *current_entry;
4308 bool (*ldap2displayentry)(struct ldap_search_state *state,
4309 TALLOC_CTX *mem_ctx,
4310 LDAP *ld, LDAPMessage *entry,
4311 struct samr_displayentry *result);
4314 static bool ldapsam_search_firstpage(struct pdb_search *search)
4316 struct ldap_search_state *state =
4317 (struct ldap_search_state *)search->private_data;
4318 LDAP *ld;
4319 int rc = LDAP_OPERATIONS_ERROR;
4321 state->entries = NULL;
4323 if (state->connection->paged_results) {
4324 rc = smbldap_search_paged(state->connection, state->base,
4325 state->scope, state->filter,
4326 state->attrs, state->attrsonly,
4327 lp_ldap_page_size(), &state->entries,
4328 &state->pagedresults_cookie);
4331 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4333 if (state->entries != NULL) {
4334 /* Left over from unsuccessful paged attempt */
4335 ldap_msgfree(state->entries);
4336 state->entries = NULL;
4339 rc = smbldap_search(state->connection, state->base,
4340 state->scope, state->filter, state->attrs,
4341 state->attrsonly, &state->entries);
4343 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4344 return False;
4346 /* Ok, the server was lying. It told us it could do paged
4347 * searches when it could not. */
4348 state->connection->paged_results = False;
4351 ld = state->connection->ldap_struct;
4352 if ( ld == NULL) {
4353 DEBUG(5, ("Don't have an LDAP connection right after a "
4354 "search\n"));
4355 return False;
4357 state->current_entry = ldap_first_entry(ld, state->entries);
4359 return True;
4362 static bool ldapsam_search_nextpage(struct pdb_search *search)
4364 struct ldap_search_state *state =
4365 (struct ldap_search_state *)search->private_data;
4366 int rc;
4368 if (!state->connection->paged_results) {
4369 /* There is no next page when there are no paged results */
4370 return False;
4373 rc = smbldap_search_paged(state->connection, state->base,
4374 state->scope, state->filter, state->attrs,
4375 state->attrsonly, lp_ldap_page_size(),
4376 &state->entries,
4377 &state->pagedresults_cookie);
4379 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4380 return False;
4382 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4384 if (state->current_entry == NULL) {
4385 ldap_msgfree(state->entries);
4386 state->entries = NULL;
4387 return false;
4390 return True;
4393 static bool ldapsam_search_next_entry(struct pdb_search *search,
4394 struct samr_displayentry *entry)
4396 struct ldap_search_state *state =
4397 (struct ldap_search_state *)search->private_data;
4398 bool result;
4400 retry:
4401 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4402 return False;
4404 if ((state->entries == NULL) &&
4405 !ldapsam_search_nextpage(search))
4406 return False;
4408 if (state->current_entry == NULL) {
4409 return false;
4412 result = state->ldap2displayentry(state, search,
4413 state->connection->ldap_struct,
4414 state->current_entry, entry);
4416 if (!result) {
4417 char *dn;
4418 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4419 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4420 if (dn != NULL) ldap_memfree(dn);
4423 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4425 if (state->current_entry == NULL) {
4426 ldap_msgfree(state->entries);
4427 state->entries = NULL;
4430 if (!result) goto retry;
4432 return True;
4435 static void ldapsam_search_end(struct pdb_search *search)
4437 struct ldap_search_state *state =
4438 (struct ldap_search_state *)search->private_data;
4439 int rc;
4441 if (state->pagedresults_cookie == NULL)
4442 return;
4444 if (state->entries != NULL)
4445 ldap_msgfree(state->entries);
4447 state->entries = NULL;
4448 state->current_entry = NULL;
4450 if (!state->connection->paged_results)
4451 return;
4453 /* Tell the LDAP server we're not interested in the rest anymore. */
4455 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4456 state->filter, state->attrs,
4457 state->attrsonly, 0, &state->entries,
4458 &state->pagedresults_cookie);
4460 if (rc != LDAP_SUCCESS)
4461 DEBUG(5, ("Could not end search properly\n"));
4463 return;
4466 static bool ldapuser2displayentry(struct ldap_search_state *state,
4467 TALLOC_CTX *mem_ctx,
4468 LDAP *ld, LDAPMessage *entry,
4469 struct samr_displayentry *result)
4471 char **vals;
4472 size_t converted_size;
4473 struct dom_sid sid;
4474 uint32_t acct_flags;
4476 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4477 if ((vals == NULL) || (vals[0] == NULL)) {
4478 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4479 return False;
4481 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4482 ldap_value_free(vals);
4484 if ((state->acct_flags != 0) &&
4485 ((state->acct_flags & acct_flags) == 0))
4486 return False;
4488 result->acct_flags = acct_flags;
4489 result->account_name = "";
4490 result->fullname = "";
4491 result->description = "";
4493 vals = ldap_get_values(ld, entry, "uid");
4494 if ((vals == NULL) || (vals[0] == NULL)) {
4495 DEBUG(5, ("\"uid\" not found\n"));
4496 return False;
4498 if (!pull_utf8_talloc(mem_ctx,
4499 discard_const_p(char *, &result->account_name),
4500 vals[0], &converted_size))
4502 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4503 strerror(errno)));
4506 ldap_value_free(vals);
4508 vals = ldap_get_values(ld, entry, "displayName");
4509 if ((vals == NULL) || (vals[0] == NULL))
4510 DEBUG(8, ("\"displayName\" not found\n"));
4511 else if (!pull_utf8_talloc(mem_ctx,
4512 discard_const_p(char *, &result->fullname),
4513 vals[0], &converted_size))
4515 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4516 strerror(errno)));
4519 ldap_value_free(vals);
4521 vals = ldap_get_values(ld, entry, "description");
4522 if ((vals == NULL) || (vals[0] == NULL))
4523 DEBUG(8, ("\"description\" not found\n"));
4524 else if (!pull_utf8_talloc(mem_ctx,
4525 discard_const_p(char *, &result->description),
4526 vals[0], &converted_size))
4528 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4529 strerror(errno)));
4532 ldap_value_free(vals);
4534 if ((result->account_name == NULL) ||
4535 (result->fullname == NULL) ||
4536 (result->description == NULL)) {
4537 DEBUG(0, ("talloc failed\n"));
4538 return False;
4541 vals = ldap_get_values(ld, entry, "sambaSid");
4542 if ((vals == NULL) || (vals[0] == NULL)) {
4543 DEBUG(0, ("\"objectSid\" not found\n"));
4544 return False;
4547 if (!string_to_sid(&sid, vals[0])) {
4548 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4549 ldap_value_free(vals);
4550 return False;
4552 ldap_value_free(vals);
4554 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4555 DEBUG(0, ("sid %s does not belong to our domain\n",
4556 sid_string_dbg(&sid)));
4557 return False;
4560 return True;
4564 static bool ldapsam_search_users(struct pdb_methods *methods,
4565 struct pdb_search *search,
4566 uint32_t acct_flags)
4568 struct ldapsam_privates *ldap_state =
4569 (struct ldapsam_privates *)methods->private_data;
4570 struct ldap_search_state *state;
4572 state = talloc(search, struct ldap_search_state);
4573 if (state == NULL) {
4574 DEBUG(0, ("talloc failed\n"));
4575 return False;
4578 state->connection = ldap_state->smbldap_state;
4580 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4581 state->base = lp_ldap_user_suffix(talloc_tos());
4582 else if ((acct_flags != 0) &&
4583 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4584 state->base = lp_ldap_machine_suffix(talloc_tos());
4585 else
4586 state->base = lp_ldap_suffix(talloc_tos());
4588 state->acct_flags = acct_flags;
4589 state->base = talloc_strdup(search, state->base);
4590 state->scope = LDAP_SCOPE_SUBTREE;
4591 state->filter = get_ldap_filter(search, "*");
4592 state->attrs = talloc_attrs(search, "uid", "sambaSid",
4593 "displayName", "description",
4594 "sambaAcctFlags", NULL);
4595 state->attrsonly = 0;
4596 state->pagedresults_cookie = NULL;
4597 state->entries = NULL;
4598 state->ldap2displayentry = ldapuser2displayentry;
4600 if ((state->filter == NULL) || (state->attrs == NULL)) {
4601 DEBUG(0, ("talloc failed\n"));
4602 return False;
4605 search->private_data = state;
4606 search->next_entry = ldapsam_search_next_entry;
4607 search->search_end = ldapsam_search_end;
4609 return ldapsam_search_firstpage(search);
4612 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4613 TALLOC_CTX *mem_ctx,
4614 LDAP *ld, LDAPMessage *entry,
4615 struct samr_displayentry *result)
4617 char **vals;
4618 size_t converted_size;
4619 struct dom_sid sid;
4620 uint16_t group_type;
4622 result->account_name = "";
4623 result->fullname = "";
4624 result->description = "";
4627 vals = ldap_get_values(ld, entry, "sambaGroupType");
4628 if ((vals == NULL) || (vals[0] == NULL)) {
4629 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4630 if (vals != NULL) {
4631 ldap_value_free(vals);
4633 return False;
4636 group_type = atoi(vals[0]);
4638 if ((state->group_type != 0) &&
4639 ((state->group_type != group_type))) {
4640 ldap_value_free(vals);
4641 return False;
4644 ldap_value_free(vals);
4646 /* display name is the NT group name */
4648 vals = ldap_get_values(ld, entry, "displayName");
4649 if ((vals == NULL) || (vals[0] == NULL)) {
4650 DEBUG(8, ("\"displayName\" not found\n"));
4652 /* fallback to the 'cn' attribute */
4653 vals = ldap_get_values(ld, entry, "cn");
4654 if ((vals == NULL) || (vals[0] == NULL)) {
4655 DEBUG(5, ("\"cn\" not found\n"));
4656 return False;
4658 if (!pull_utf8_talloc(mem_ctx,
4659 discard_const_p(char *,
4660 &result->account_name),
4661 vals[0], &converted_size))
4663 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4664 "failed: %s", strerror(errno)));
4667 else if (!pull_utf8_talloc(mem_ctx,
4668 discard_const_p(char *,
4669 &result->account_name),
4670 vals[0], &converted_size))
4672 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4673 strerror(errno)));
4676 ldap_value_free(vals);
4678 vals = ldap_get_values(ld, entry, "description");
4679 if ((vals == NULL) || (vals[0] == NULL))
4680 DEBUG(8, ("\"description\" not found\n"));
4681 else if (!pull_utf8_talloc(mem_ctx,
4682 discard_const_p(char *, &result->description),
4683 vals[0], &converted_size))
4685 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4686 strerror(errno)));
4688 ldap_value_free(vals);
4690 if ((result->account_name == NULL) ||
4691 (result->fullname == NULL) ||
4692 (result->description == NULL)) {
4693 DEBUG(0, ("talloc failed\n"));
4694 return False;
4697 vals = ldap_get_values(ld, entry, "sambaSid");
4698 if ((vals == NULL) || (vals[0] == NULL)) {
4699 DEBUG(0, ("\"objectSid\" not found\n"));
4700 if (vals != NULL) {
4701 ldap_value_free(vals);
4703 return False;
4706 if (!string_to_sid(&sid, vals[0])) {
4707 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4708 return False;
4711 ldap_value_free(vals);
4713 switch (group_type) {
4714 case SID_NAME_DOM_GRP:
4715 case SID_NAME_ALIAS:
4717 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4718 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4720 DEBUG(0, ("%s is not in our domain\n",
4721 sid_string_dbg(&sid)));
4722 return False;
4724 break;
4726 default:
4727 DEBUG(0,("unknown group type: %d\n", group_type));
4728 return False;
4731 result->acct_flags = 0;
4733 return True;
4736 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4737 struct pdb_search *search,
4738 const struct dom_sid *sid,
4739 enum lsa_SidType type)
4741 struct ldapsam_privates *ldap_state =
4742 (struct ldapsam_privates *)methods->private_data;
4743 struct ldap_search_state *state;
4744 fstring tmp;
4746 state = talloc(search, struct ldap_search_state);
4747 if (state == NULL) {
4748 DEBUG(0, ("talloc failed\n"));
4749 return False;
4752 state->connection = ldap_state->smbldap_state;
4754 state->base = lp_ldap_suffix(search);
4755 state->connection = ldap_state->smbldap_state;
4756 state->scope = LDAP_SCOPE_SUBTREE;
4757 state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4758 "(sambaGroupType=%d)(sambaSID=%s*))",
4759 LDAP_OBJ_GROUPMAP,
4760 type, sid_to_fstring(tmp, sid));
4761 state->attrs = talloc_attrs(search, "cn", "sambaSid",
4762 "displayName", "description",
4763 "sambaGroupType", NULL);
4764 state->attrsonly = 0;
4765 state->pagedresults_cookie = NULL;
4766 state->entries = NULL;
4767 state->group_type = type;
4768 state->ldap2displayentry = ldapgroup2displayentry;
4770 if ((state->filter == NULL) || (state->attrs == NULL)) {
4771 DEBUG(0, ("talloc failed\n"));
4772 return False;
4775 search->private_data = state;
4776 search->next_entry = ldapsam_search_next_entry;
4777 search->search_end = ldapsam_search_end;
4779 return ldapsam_search_firstpage(search);
4782 static bool ldapsam_search_groups(struct pdb_methods *methods,
4783 struct pdb_search *search)
4785 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4788 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4789 struct pdb_search *search,
4790 const struct dom_sid *sid)
4792 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4795 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4797 return PDB_CAP_STORE_RIDS;
4800 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4801 uint32_t *rid)
4803 struct smbldap_state *smbldap_state = priv->smbldap_state;
4805 LDAPMessage *result = NULL;
4806 LDAPMessage *entry = NULL;
4807 LDAPMod **mods = NULL;
4808 NTSTATUS status;
4809 char *value;
4810 int rc;
4811 uint32_t nextRid = 0;
4812 const char *dn;
4814 TALLOC_CTX *mem_ctx;
4816 mem_ctx = talloc_new(NULL);
4817 if (mem_ctx == NULL) {
4818 DEBUG(0, ("talloc_new failed\n"));
4819 return NT_STATUS_NO_MEMORY;
4822 status = smbldap_search_domain_info(smbldap_state, &result,
4823 get_global_sam_name(), False);
4824 if (!NT_STATUS_IS_OK(status)) {
4825 DEBUG(3, ("Could not get domain info: %s\n",
4826 nt_errstr(status)));
4827 goto done;
4830 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4832 entry = ldap_first_entry(priv2ld(priv), result);
4833 if (entry == NULL) {
4834 DEBUG(0, ("Could not get domain info entry\n"));
4835 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4836 goto done;
4839 /* Find the largest of the three attributes "sambaNextRid",
4840 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4841 concept of differentiating between user and group rids, and will
4842 use only "sambaNextRid" in the future. But for compatibility
4843 reasons I look if others have chosen different strategies -- VL */
4845 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4846 "sambaNextRid", mem_ctx);
4847 if (value != NULL) {
4848 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4849 nextRid = MAX(nextRid, tmp);
4852 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4853 "sambaNextUserRid", mem_ctx);
4854 if (value != NULL) {
4855 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4856 nextRid = MAX(nextRid, tmp);
4859 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4860 "sambaNextGroupRid", mem_ctx);
4861 if (value != NULL) {
4862 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4863 nextRid = MAX(nextRid, tmp);
4866 if (nextRid == 0) {
4867 nextRid = BASE_RID-1;
4870 nextRid += 1;
4872 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4873 talloc_asprintf(mem_ctx, "%d", nextRid));
4874 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
4876 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4877 status = NT_STATUS_NO_MEMORY;
4878 goto done;
4881 rc = smbldap_modify(smbldap_state, dn, mods);
4883 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4884 * please retry" */
4886 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4888 done:
4889 if (NT_STATUS_IS_OK(status)) {
4890 *rid = nextRid;
4893 TALLOC_FREE(mem_ctx);
4894 return status;
4897 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4899 int i;
4901 for (i=0; i<10; i++) {
4902 NTSTATUS result = ldapsam_get_new_rid(
4903 (struct ldapsam_privates *)methods->private_data, rid);
4904 if (NT_STATUS_IS_OK(result)) {
4905 return result;
4908 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4909 return result;
4912 /* The ldap update failed (maybe a race condition), retry */
4915 /* Tried 10 times, fail. */
4916 return NT_STATUS_ACCESS_DENIED;
4919 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4921 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4922 return NT_STATUS_IS_OK(result) ? True : False;
4925 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4926 const struct dom_sid *sid,
4927 struct unixid *id)
4929 struct ldapsam_privates *priv =
4930 (struct ldapsam_privates *)methods->private_data;
4931 char *filter;
4932 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4933 NULL };
4934 LDAPMessage *result = NULL;
4935 LDAPMessage *entry = NULL;
4936 bool ret = False;
4937 char *value;
4938 int rc;
4940 TALLOC_CTX *mem_ctx;
4942 if (!sid_check_object_is_for_passdb(sid)) {
4943 return false;
4946 ret = pdb_sid_to_id_unix_users_and_groups(sid, id);
4947 if (ret == true) {
4948 return true;
4951 mem_ctx = talloc_new(NULL);
4952 if (mem_ctx == NULL) {
4953 DEBUG(0, ("talloc_new failed\n"));
4954 return False;
4957 filter = talloc_asprintf(mem_ctx,
4958 "(&(sambaSid=%s)"
4959 "(|(objectClass=%s)(objectClass=%s)))",
4960 sid_string_talloc(mem_ctx, sid),
4961 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4962 if (filter == NULL) {
4963 DEBUG(5, ("talloc_asprintf failed\n"));
4964 goto done;
4967 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4968 attrs, &result);
4969 if (rc != LDAP_SUCCESS) {
4970 goto done;
4972 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4974 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4975 DEBUG(10, ("Got %d entries, expected one\n",
4976 ldap_count_entries(priv2ld(priv), result)));
4977 goto done;
4980 entry = ldap_first_entry(priv2ld(priv), result);
4982 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4983 "sambaGroupType", mem_ctx);
4985 if (value != NULL) {
4986 const char *gid_str;
4987 /* It's a group */
4989 gid_str = smbldap_talloc_single_attribute(
4990 priv2ld(priv), entry, "gidNumber", mem_ctx);
4991 if (gid_str == NULL) {
4992 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4993 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4994 entry)));
4995 goto done;
4998 id->id = strtoul(gid_str, NULL, 10);
4999 id->type = ID_TYPE_GID;
5000 idmap_cache_set_sid2unixid(sid, id);
5001 ret = True;
5002 goto done;
5005 /* It must be a user */
5007 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5008 "uidNumber", mem_ctx);
5009 if (value == NULL) {
5010 DEBUG(1, ("Could not find uidNumber in %s\n",
5011 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
5012 goto done;
5015 id->id = strtoul(value, NULL, 10);
5016 id->type = ID_TYPE_UID;
5017 idmap_cache_set_sid2unixid(sid, id);
5019 ret = True;
5020 done:
5021 TALLOC_FREE(mem_ctx);
5022 return ret;
5026 * Find the SID for a uid.
5027 * This is shortcut is only used if ldapsam:trusted is set to true.
5029 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5030 struct dom_sid *sid)
5032 struct ldapsam_privates *priv =
5033 (struct ldapsam_privates *)methods->private_data;
5034 char *filter;
5035 const char *attrs[] = { "sambaSID", NULL };
5036 LDAPMessage *result = NULL;
5037 LDAPMessage *entry = NULL;
5038 bool ret = false;
5039 char *user_sid_string;
5040 struct dom_sid user_sid;
5041 int rc;
5042 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5043 struct unixid id;
5045 filter = talloc_asprintf(tmp_ctx,
5046 "(&(uidNumber=%u)"
5047 "(objectClass=%s)"
5048 "(objectClass=%s))",
5049 (unsigned int)uid,
5050 LDAP_OBJ_POSIXACCOUNT,
5051 LDAP_OBJ_SAMBASAMACCOUNT);
5052 if (filter == NULL) {
5053 DEBUG(3, ("talloc_asprintf failed\n"));
5054 goto done;
5057 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5058 if (rc != LDAP_SUCCESS) {
5059 goto done;
5061 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5063 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5064 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5065 ldap_count_entries(priv2ld(priv), result),
5066 (unsigned int)uid));
5067 goto done;
5070 entry = ldap_first_entry(priv2ld(priv), result);
5072 user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5073 "sambaSID", tmp_ctx);
5074 if (user_sid_string == NULL) {
5075 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5076 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5077 goto done;
5080 if (!string_to_sid(&user_sid, user_sid_string)) {
5081 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5082 user_sid_string));
5083 goto done;
5086 sid_copy(sid, &user_sid);
5088 id.id = uid;
5089 id.type = ID_TYPE_UID;
5091 idmap_cache_set_sid2unixid(sid, &id);
5093 ret = true;
5095 done:
5096 TALLOC_FREE(tmp_ctx);
5097 return ret;
5101 * Find the SID for a gid.
5102 * This is shortcut is only used if ldapsam:trusted is set to true.
5104 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5105 struct dom_sid *sid)
5107 struct ldapsam_privates *priv =
5108 (struct ldapsam_privates *)methods->private_data;
5109 char *filter;
5110 const char *attrs[] = { "sambaSID", NULL };
5111 LDAPMessage *result = NULL;
5112 LDAPMessage *entry = NULL;
5113 bool ret = false;
5114 char *group_sid_string;
5115 struct dom_sid group_sid;
5116 int rc;
5117 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5118 struct unixid id;
5120 filter = talloc_asprintf(tmp_ctx,
5121 "(&(gidNumber=%u)"
5122 "(objectClass=%s))",
5123 (unsigned int)gid,
5124 LDAP_OBJ_GROUPMAP);
5125 if (filter == NULL) {
5126 DEBUG(3, ("talloc_asprintf failed\n"));
5127 goto done;
5130 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5131 if (rc != LDAP_SUCCESS) {
5132 goto done;
5134 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5136 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5137 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5138 ldap_count_entries(priv2ld(priv), result),
5139 (unsigned int)gid));
5140 goto done;
5143 entry = ldap_first_entry(priv2ld(priv), result);
5145 group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5146 "sambaSID", tmp_ctx);
5147 if (group_sid_string == NULL) {
5148 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5149 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5150 goto done;
5153 if (!string_to_sid(&group_sid, group_sid_string)) {
5154 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5155 group_sid_string));
5156 goto done;
5159 sid_copy(sid, &group_sid);
5161 id.id = gid;
5162 id.type = ID_TYPE_GID;
5164 idmap_cache_set_sid2unixid(sid, &id);
5166 ret = true;
5168 done:
5169 TALLOC_FREE(tmp_ctx);
5170 return ret;
5175 * The following functions are called only if
5176 * ldapsam:trusted and ldapsam:editposix are
5177 * set to true
5181 * ldapsam_create_user creates a new
5182 * posixAccount and sambaSamAccount object
5183 * in the ldap users subtree
5185 * The uid is allocated by winbindd.
5188 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5189 TALLOC_CTX *tmp_ctx, const char *name,
5190 uint32_t acb_info, uint32_t *rid)
5192 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5193 LDAPMessage *entry = NULL;
5194 LDAPMessage *result = NULL;
5195 uint32_t num_result;
5196 bool is_machine = False;
5197 bool add_posix = False;
5198 LDAPMod **mods = NULL;
5199 struct samu *user;
5200 char *filter;
5201 char *username;
5202 char *homedir;
5203 char *gidstr;
5204 char *uidstr;
5205 char *shell;
5206 const char *dn = NULL;
5207 struct dom_sid group_sid;
5208 struct dom_sid user_sid;
5209 gid_t gid = -1;
5210 uid_t uid = -1;
5211 NTSTATUS ret;
5212 int rc;
5214 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5215 acb_info & ACB_WSTRUST ||
5216 acb_info & ACB_SVRTRUST ||
5217 acb_info & ACB_DOMTRUST) {
5218 is_machine = True;
5221 username = escape_ldap_string(talloc_tos(), name);
5222 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5223 username, LDAP_OBJ_POSIXACCOUNT);
5224 TALLOC_FREE(username);
5226 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5227 if (rc != LDAP_SUCCESS) {
5228 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5229 return NT_STATUS_ACCESS_DENIED;
5231 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5233 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5235 if (num_result > 1) {
5236 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5237 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5240 if (num_result == 1) {
5241 char *tmp;
5242 /* check if it is just a posix account.
5243 * or if there is a sid attached to this entry
5246 entry = ldap_first_entry(priv2ld(ldap_state), result);
5247 if (!entry) {
5248 return NT_STATUS_UNSUCCESSFUL;
5251 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5252 if (tmp) {
5253 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5254 return NT_STATUS_USER_EXISTS;
5257 /* it is just a posix account, retrieve the dn for later use */
5258 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5259 if (!dn) {
5260 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5261 return NT_STATUS_NO_MEMORY;
5265 if (num_result == 0) {
5266 add_posix = True;
5269 /* Create the basic samu structure and generate the mods for the ldap commit */
5270 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5271 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5272 return ret;
5275 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5277 user = samu_new(tmp_ctx);
5278 if (!user) {
5279 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5280 return NT_STATUS_NO_MEMORY;
5283 if (!pdb_set_username(user, name, PDB_SET)) {
5284 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5285 return NT_STATUS_UNSUCCESSFUL;
5287 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5288 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5289 return NT_STATUS_UNSUCCESSFUL;
5291 if (is_machine) {
5292 if (acb_info & ACB_NORMAL) {
5293 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5294 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5295 return NT_STATUS_UNSUCCESSFUL;
5297 } else {
5298 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5299 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5300 return NT_STATUS_UNSUCCESSFUL;
5303 } else {
5304 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5305 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5306 return NT_STATUS_UNSUCCESSFUL;
5310 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5311 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5312 return NT_STATUS_UNSUCCESSFUL;
5315 if (!init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed)) {
5316 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5317 return NT_STATUS_UNSUCCESSFUL;
5320 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5321 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5323 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5325 if (add_posix) {
5326 char *escape_name;
5328 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5330 /* retrieve the Domain Users group gid */
5331 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5332 !sid_to_gid(&group_sid, &gid)) {
5333 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5334 return NT_STATUS_INVALID_PRIMARY_GROUP;
5337 /* lets allocate a new userid for this user */
5338 if (!winbind_allocate_uid(&uid)) {
5339 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5340 return NT_STATUS_UNSUCCESSFUL;
5344 if (is_machine) {
5345 /* TODO: choose a more appropriate default for machines */
5346 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5347 shell = talloc_strdup(tmp_ctx, "/bin/false");
5348 } else {
5349 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5350 shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5352 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5353 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5355 escape_name = escape_rdn_val_string_alloc(name);
5356 if (!escape_name) {
5357 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5358 return NT_STATUS_NO_MEMORY;
5361 if (is_machine) {
5362 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
5363 } else {
5364 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
5367 SAFE_FREE(escape_name);
5369 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5370 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5371 return NT_STATUS_NO_MEMORY;
5374 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5375 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5376 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5377 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5378 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5379 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5380 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5383 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5385 if (add_posix) {
5386 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5387 } else {
5388 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5391 if (rc != LDAP_SUCCESS) {
5392 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5393 return NT_STATUS_UNSUCCESSFUL;
5396 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5398 flush_pwnam_cache();
5400 return NT_STATUS_OK;
5403 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5405 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5406 LDAPMessage *result = NULL;
5407 LDAPMessage *entry = NULL;
5408 int num_result;
5409 const char *dn;
5410 char *filter;
5411 int rc;
5413 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5415 filter = talloc_asprintf(tmp_ctx,
5416 "(&(uid=%s)"
5417 "(objectClass=%s)"
5418 "(objectClass=%s))",
5419 pdb_get_username(sam_acct),
5420 LDAP_OBJ_POSIXACCOUNT,
5421 LDAP_OBJ_SAMBASAMACCOUNT);
5422 if (filter == NULL) {
5423 return NT_STATUS_NO_MEMORY;
5426 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5427 if (rc != LDAP_SUCCESS) {
5428 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5429 return NT_STATUS_UNSUCCESSFUL;
5431 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5433 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5435 if (num_result == 0) {
5436 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5437 return NT_STATUS_NO_SUCH_USER;
5440 if (num_result > 1) {
5441 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5442 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5445 entry = ldap_first_entry(priv2ld(ldap_state), result);
5446 if (!entry) {
5447 return NT_STATUS_UNSUCCESSFUL;
5450 /* it is just a posix account, retrieve the dn for later use */
5451 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5452 if (!dn) {
5453 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5454 return NT_STATUS_NO_MEMORY;
5457 /* try to remove memberships first */
5459 NTSTATUS status;
5460 struct dom_sid *sids = NULL;
5461 gid_t *gids = NULL;
5462 uint32_t num_groups = 0;
5463 int i;
5464 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5466 status = ldapsam_enum_group_memberships(my_methods,
5467 tmp_ctx,
5468 sam_acct,
5469 &sids,
5470 &gids,
5471 &num_groups);
5472 if (!NT_STATUS_IS_OK(status)) {
5473 goto delete_dn;
5476 for (i=0; i < num_groups; i++) {
5478 uint32_t group_rid;
5480 sid_peek_rid(&sids[i], &group_rid);
5482 ldapsam_del_groupmem(my_methods,
5483 tmp_ctx,
5484 group_rid,
5485 user_rid);
5489 delete_dn:
5491 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5492 if (rc != LDAP_SUCCESS) {
5493 return NT_STATUS_UNSUCCESSFUL;
5496 flush_pwnam_cache();
5498 return NT_STATUS_OK;
5502 * ldapsam_create_group creates a new
5503 * posixGroup and sambaGroupMapping object
5504 * in the ldap groups subtree
5506 * The gid is allocated by winbindd.
5509 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5510 TALLOC_CTX *tmp_ctx,
5511 const char *name,
5512 uint32_t *rid)
5514 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5515 NTSTATUS ret;
5516 LDAPMessage *entry = NULL;
5517 LDAPMessage *result = NULL;
5518 uint32_t num_result;
5519 bool is_new_entry = False;
5520 LDAPMod **mods = NULL;
5521 char *filter;
5522 char *groupsidstr;
5523 char *groupname;
5524 char *grouptype;
5525 char *gidstr;
5526 const char *dn = NULL;
5527 struct dom_sid group_sid;
5528 gid_t gid = -1;
5529 int rc;
5531 groupname = escape_ldap_string(talloc_tos(), name);
5532 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5533 groupname, LDAP_OBJ_POSIXGROUP);
5534 TALLOC_FREE(groupname);
5536 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5537 if (rc != LDAP_SUCCESS) {
5538 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5539 return NT_STATUS_UNSUCCESSFUL;
5541 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5543 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5545 if (num_result > 1) {
5546 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5547 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5550 if (num_result == 1) {
5551 char *tmp;
5552 /* check if it is just a posix group.
5553 * or if there is a sid attached to this entry
5556 entry = ldap_first_entry(priv2ld(ldap_state), result);
5557 if (!entry) {
5558 return NT_STATUS_UNSUCCESSFUL;
5561 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5562 if (tmp) {
5563 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5564 return NT_STATUS_GROUP_EXISTS;
5567 /* it is just a posix group, retrieve the gid and the dn for later use */
5568 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5569 if (!tmp) {
5570 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5571 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5574 gid = strtoul(tmp, NULL, 10);
5576 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5577 if (!dn) {
5578 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5579 return NT_STATUS_NO_MEMORY;
5583 if (num_result == 0) {
5584 is_new_entry = true;
5587 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5588 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5589 return ret;
5592 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5594 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5595 &group_sid));
5596 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5598 if (!groupsidstr || !grouptype) {
5599 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5600 return NT_STATUS_NO_MEMORY;
5603 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5604 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5605 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5606 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5608 if (is_new_entry) {
5609 char *escape_name;
5611 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5613 /* lets allocate a new groupid for this group */
5614 if (!winbind_allocate_gid(&gid)) {
5615 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5616 return NT_STATUS_UNSUCCESSFUL;
5619 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5621 escape_name = escape_rdn_val_string_alloc(name);
5622 if (!escape_name) {
5623 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5624 return NT_STATUS_NO_MEMORY;
5627 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
5629 SAFE_FREE(escape_name);
5631 if (!gidstr || !dn) {
5632 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5633 return NT_STATUS_NO_MEMORY;
5636 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5637 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5638 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5641 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5643 if (is_new_entry) {
5644 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5645 #if 0
5646 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5647 /* This call may fail with rfc2307bis schema */
5648 /* Retry adding a structural class */
5649 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5650 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5652 #endif
5653 } else {
5654 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5657 if (rc != LDAP_SUCCESS) {
5658 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5659 return NT_STATUS_UNSUCCESSFUL;
5662 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5664 return NT_STATUS_OK;
5667 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5669 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5670 LDAPMessage *result = NULL;
5671 LDAPMessage *entry = NULL;
5672 int num_result;
5673 const char *dn;
5674 char *gidstr;
5675 char *filter;
5676 struct dom_sid group_sid;
5677 int rc;
5679 /* get the group sid */
5680 sid_compose(&group_sid, get_global_sam_sid(), rid);
5682 filter = talloc_asprintf(tmp_ctx,
5683 "(&(sambaSID=%s)"
5684 "(objectClass=%s)"
5685 "(objectClass=%s))",
5686 sid_string_talloc(tmp_ctx, &group_sid),
5687 LDAP_OBJ_POSIXGROUP,
5688 LDAP_OBJ_GROUPMAP);
5689 if (filter == NULL) {
5690 return NT_STATUS_NO_MEMORY;
5693 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5694 if (rc != LDAP_SUCCESS) {
5695 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5696 return NT_STATUS_UNSUCCESSFUL;
5698 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5700 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5702 if (num_result == 0) {
5703 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5704 return NT_STATUS_NO_SUCH_GROUP;
5707 if (num_result > 1) {
5708 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5709 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5712 entry = ldap_first_entry(priv2ld(ldap_state), result);
5713 if (!entry) {
5714 return NT_STATUS_UNSUCCESSFUL;
5717 /* here it is, retrieve the dn for later use */
5718 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5719 if (!dn) {
5720 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5721 return NT_STATUS_NO_MEMORY;
5724 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5725 if (!gidstr) {
5726 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5727 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5730 /* check no user have this group marked as primary group */
5731 filter = talloc_asprintf(tmp_ctx,
5732 "(&(gidNumber=%s)"
5733 "(objectClass=%s)"
5734 "(objectClass=%s))",
5735 gidstr,
5736 LDAP_OBJ_POSIXACCOUNT,
5737 LDAP_OBJ_SAMBASAMACCOUNT);
5739 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5740 if (rc != LDAP_SUCCESS) {
5741 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5742 return NT_STATUS_UNSUCCESSFUL;
5744 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5746 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5748 if (num_result != 0) {
5749 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5750 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5753 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5754 if (rc != LDAP_SUCCESS) {
5755 return NT_STATUS_UNSUCCESSFUL;
5758 return NT_STATUS_OK;
5761 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5762 TALLOC_CTX *tmp_ctx,
5763 uint32_t group_rid,
5764 uint32_t member_rid,
5765 int modop)
5767 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5768 LDAPMessage *entry = NULL;
5769 LDAPMessage *result = NULL;
5770 uint32_t num_result;
5771 LDAPMod **mods = NULL;
5772 char *filter;
5773 char *uidstr;
5774 const char *dn = NULL;
5775 struct dom_sid group_sid;
5776 struct dom_sid member_sid;
5777 int rc;
5779 switch (modop) {
5780 case LDAP_MOD_ADD:
5781 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5782 break;
5783 case LDAP_MOD_DELETE:
5784 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5785 break;
5786 default:
5787 return NT_STATUS_UNSUCCESSFUL;
5790 /* get member sid */
5791 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5793 /* get the group sid */
5794 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5796 filter = talloc_asprintf(tmp_ctx,
5797 "(&(sambaSID=%s)"
5798 "(objectClass=%s)"
5799 "(objectClass=%s))",
5800 sid_string_talloc(tmp_ctx, &member_sid),
5801 LDAP_OBJ_POSIXACCOUNT,
5802 LDAP_OBJ_SAMBASAMACCOUNT);
5803 if (filter == NULL) {
5804 return NT_STATUS_NO_MEMORY;
5807 /* get the member uid */
5808 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5809 if (rc != LDAP_SUCCESS) {
5810 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5811 return NT_STATUS_UNSUCCESSFUL;
5813 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5815 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5817 if (num_result == 0) {
5818 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5819 return NT_STATUS_NO_SUCH_MEMBER;
5822 if (num_result > 1) {
5823 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5824 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5827 entry = ldap_first_entry(priv2ld(ldap_state), result);
5828 if (!entry) {
5829 return NT_STATUS_UNSUCCESSFUL;
5832 if (modop == LDAP_MOD_DELETE) {
5833 /* check if we are trying to remove the member from his primary group */
5834 char *gidstr;
5835 gid_t user_gid, group_gid;
5837 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5838 if (!gidstr) {
5839 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5840 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5843 user_gid = strtoul(gidstr, NULL, 10);
5845 if (!sid_to_gid(&group_sid, &group_gid)) {
5846 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5847 return NT_STATUS_UNSUCCESSFUL;
5850 if (user_gid == group_gid) {
5851 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5852 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5856 /* here it is, retrieve the uid for later use */
5857 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5858 if (!uidstr) {
5859 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5860 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5863 filter = talloc_asprintf(tmp_ctx,
5864 "(&(sambaSID=%s)"
5865 "(objectClass=%s)"
5866 "(objectClass=%s))",
5867 sid_string_talloc(tmp_ctx, &group_sid),
5868 LDAP_OBJ_POSIXGROUP,
5869 LDAP_OBJ_GROUPMAP);
5871 /* get the group */
5872 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5873 if (rc != LDAP_SUCCESS) {
5874 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5875 return NT_STATUS_UNSUCCESSFUL;
5877 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5879 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5881 if (num_result == 0) {
5882 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5883 return NT_STATUS_NO_SUCH_GROUP;
5886 if (num_result > 1) {
5887 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5888 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5891 entry = ldap_first_entry(priv2ld(ldap_state), result);
5892 if (!entry) {
5893 return NT_STATUS_UNSUCCESSFUL;
5896 /* here it is, retrieve the dn for later use */
5897 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5898 if (!dn) {
5899 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5900 return NT_STATUS_NO_MEMORY;
5903 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5905 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5907 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5908 if (rc != LDAP_SUCCESS) {
5909 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5910 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5911 return NT_STATUS_MEMBER_IN_GROUP;
5913 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5914 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5915 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5917 return NT_STATUS_UNSUCCESSFUL;
5920 return NT_STATUS_OK;
5923 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5924 TALLOC_CTX *tmp_ctx,
5925 uint32_t group_rid,
5926 uint32_t member_rid)
5928 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5930 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5931 TALLOC_CTX *tmp_ctx,
5932 uint32_t group_rid,
5933 uint32_t member_rid)
5935 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5938 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5939 TALLOC_CTX *mem_ctx,
5940 struct samu *sampass)
5942 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5943 LDAPMessage *entry = NULL;
5944 LDAPMessage *result = NULL;
5945 uint32_t num_result;
5946 LDAPMod **mods = NULL;
5947 char *filter;
5948 char *escape_username;
5949 char *gidstr;
5950 const char *dn = NULL;
5951 gid_t gid;
5952 int rc;
5954 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5956 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5957 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5958 return NT_STATUS_UNSUCCESSFUL;
5960 gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5961 if (!gidstr) {
5962 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5963 return NT_STATUS_NO_MEMORY;
5966 escape_username = escape_ldap_string(talloc_tos(),
5967 pdb_get_username(sampass));
5968 if (escape_username== NULL) {
5969 return NT_STATUS_NO_MEMORY;
5972 filter = talloc_asprintf(mem_ctx,
5973 "(&(uid=%s)"
5974 "(objectClass=%s)"
5975 "(objectClass=%s))",
5976 escape_username,
5977 LDAP_OBJ_POSIXACCOUNT,
5978 LDAP_OBJ_SAMBASAMACCOUNT);
5980 TALLOC_FREE(escape_username);
5982 if (filter == NULL) {
5983 return NT_STATUS_NO_MEMORY;
5986 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5987 if (rc != LDAP_SUCCESS) {
5988 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5989 return NT_STATUS_UNSUCCESSFUL;
5991 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
5993 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5995 if (num_result == 0) {
5996 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5997 return NT_STATUS_NO_SUCH_USER;
6000 if (num_result > 1) {
6001 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
6002 return NT_STATUS_INTERNAL_DB_CORRUPTION;
6005 entry = ldap_first_entry(priv2ld(ldap_state), result);
6006 if (!entry) {
6007 return NT_STATUS_UNSUCCESSFUL;
6010 /* retrieve the dn for later use */
6011 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
6012 if (!dn) {
6013 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
6014 return NT_STATUS_NO_MEMORY;
6017 /* remove the old one, and add the new one, this way we do not risk races */
6018 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
6020 if (mods == NULL) {
6021 return NT_STATUS_OK;
6024 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6026 if (rc != LDAP_SUCCESS) {
6027 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6028 pdb_get_username(sampass), gidstr));
6029 return NT_STATUS_UNSUCCESSFUL;
6032 flush_pwnam_cache();
6034 return NT_STATUS_OK;
6038 /**********************************************************************
6039 trusted domains functions
6040 *********************************************************************/
6042 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6043 const char *domain)
6045 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6046 ldap_state->domain_dn);
6049 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6050 TALLOC_CTX *mem_ctx,
6051 const char *domain, LDAPMessage **entry)
6053 int rc;
6054 char *filter;
6055 int scope = LDAP_SCOPE_SUBTREE;
6056 const char **attrs = NULL; /* NULL: get all attrs */
6057 int attrsonly = 0; /* 0: return values too */
6058 LDAPMessage *result = NULL;
6059 char *trusted_dn;
6060 uint32_t num_result;
6062 filter = talloc_asprintf(talloc_tos(),
6063 "(&(objectClass=%s)(sambaDomainName=%s))",
6064 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6066 trusted_dn = trusteddom_dn(ldap_state, domain);
6067 if (trusted_dn == NULL) {
6068 return False;
6070 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6071 filter, attrs, attrsonly, &result);
6073 if (result != NULL) {
6074 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6077 if (rc == LDAP_NO_SUCH_OBJECT) {
6078 *entry = NULL;
6079 return True;
6082 if (rc != LDAP_SUCCESS) {
6083 return False;
6086 num_result = ldap_count_entries(priv2ld(ldap_state), result);
6088 if (num_result > 1) {
6089 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6090 "%s object for domain '%s'?!\n",
6091 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6092 return False;
6095 if (num_result == 0) {
6096 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6097 "%s object for domain %s.\n",
6098 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6099 *entry = NULL;
6100 } else {
6101 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6104 return True;
6107 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6108 const char *domain,
6109 char** pwd,
6110 struct dom_sid *sid,
6111 time_t *pass_last_set_time)
6113 struct ldapsam_privates *ldap_state =
6114 (struct ldapsam_privates *)methods->private_data;
6115 LDAPMessage *entry = NULL;
6117 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6119 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6120 (entry == NULL))
6122 return False;
6125 /* password */
6126 if (pwd != NULL) {
6127 char *pwd_str;
6128 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6129 entry, "sambaClearTextPassword", talloc_tos());
6130 if (pwd_str == NULL) {
6131 return False;
6133 /* trusteddom_pw routines do not use talloc yet... */
6134 *pwd = SMB_STRDUP(pwd_str);
6135 if (*pwd == NULL) {
6136 return False;
6140 /* last change time */
6141 if (pass_last_set_time != NULL) {
6142 char *time_str;
6143 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6144 entry, "sambaPwdLastSet", talloc_tos());
6145 if (time_str == NULL) {
6146 return False;
6148 *pass_last_set_time = (time_t)atol(time_str);
6151 /* domain sid */
6152 if (sid != NULL) {
6153 char *sid_str;
6154 struct dom_sid dom_sid;
6155 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6156 entry, "sambaSID",
6157 talloc_tos());
6158 if (sid_str == NULL) {
6159 return False;
6161 if (!string_to_sid(&dom_sid, sid_str)) {
6162 return False;
6164 sid_copy(sid, &dom_sid);
6167 return True;
6170 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6171 const char* domain,
6172 const char* pwd,
6173 const struct dom_sid *sid)
6175 struct ldapsam_privates *ldap_state =
6176 (struct ldapsam_privates *)methods->private_data;
6177 LDAPMessage *entry = NULL;
6178 LDAPMod **mods = NULL;
6179 char *prev_pwd = NULL;
6180 char *trusted_dn = NULL;
6181 int rc;
6183 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6186 * get the current entry (if there is one) in order to put the
6187 * current password into the previous password attribute
6189 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6190 return False;
6193 mods = NULL;
6194 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6195 LDAP_OBJ_TRUSTDOM_PASSWORD);
6196 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6197 domain);
6198 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6199 sid_string_tos(sid));
6200 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6201 talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6202 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6203 "sambaClearTextPassword", pwd);
6205 if (entry != NULL) {
6206 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6207 entry, "sambaClearTextPassword", talloc_tos());
6208 if (prev_pwd != NULL) {
6209 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6210 "sambaPreviousClearTextPassword",
6211 prev_pwd);
6215 smbldap_talloc_autofree_ldapmod(talloc_tos(), mods);
6217 trusted_dn = trusteddom_dn(ldap_state, domain);
6218 if (trusted_dn == NULL) {
6219 return False;
6221 if (entry == NULL) {
6222 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6223 } else {
6224 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6227 if (rc != LDAP_SUCCESS) {
6228 DEBUG(1, ("error writing trusted domain password!\n"));
6229 return False;
6232 return True;
6235 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6236 const char *domain)
6238 int rc;
6239 struct ldapsam_privates *ldap_state =
6240 (struct ldapsam_privates *)methods->private_data;
6241 LDAPMessage *entry = NULL;
6242 const char *trusted_dn;
6244 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6245 return False;
6248 if (entry == NULL) {
6249 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6250 "%s\n", domain));
6251 return True;
6254 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6255 entry);
6256 if (trusted_dn == NULL) {
6257 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6258 return False;
6261 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6262 if (rc != LDAP_SUCCESS) {
6263 return False;
6266 return True;
6269 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6270 TALLOC_CTX *mem_ctx,
6271 uint32_t *num_domains,
6272 struct trustdom_info ***domains)
6274 int rc;
6275 struct ldapsam_privates *ldap_state =
6276 (struct ldapsam_privates *)methods->private_data;
6277 char *filter;
6278 int scope = LDAP_SCOPE_SUBTREE;
6279 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6280 int attrsonly = 0; /* 0: return values too */
6281 LDAPMessage *result = NULL;
6282 LDAPMessage *entry = NULL;
6284 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6285 LDAP_OBJ_TRUSTDOM_PASSWORD);
6287 rc = smbldap_search(ldap_state->smbldap_state,
6288 ldap_state->domain_dn,
6289 scope,
6290 filter,
6291 attrs,
6292 attrsonly,
6293 &result);
6295 if (result != NULL) {
6296 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6299 if (rc != LDAP_SUCCESS) {
6300 return NT_STATUS_UNSUCCESSFUL;
6303 *num_domains = 0;
6304 if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6305 DEBUG(1, ("talloc failed\n"));
6306 return NT_STATUS_NO_MEMORY;
6309 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6310 entry != NULL;
6311 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6313 char *dom_name, *dom_sid_str;
6314 struct trustdom_info *dom_info;
6316 dom_info = talloc(*domains, struct trustdom_info);
6317 if (dom_info == NULL) {
6318 DEBUG(1, ("talloc failed\n"));
6319 return NT_STATUS_NO_MEMORY;
6322 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6323 entry,
6324 "sambaDomainName",
6325 talloc_tos());
6326 if (dom_name == NULL) {
6327 DEBUG(1, ("talloc failed\n"));
6328 return NT_STATUS_NO_MEMORY;
6330 dom_info->name = dom_name;
6332 dom_sid_str = smbldap_talloc_single_attribute(
6333 priv2ld(ldap_state), entry, "sambaSID",
6334 talloc_tos());
6335 if (dom_sid_str == NULL) {
6336 DEBUG(1, ("talloc failed\n"));
6337 return NT_STATUS_NO_MEMORY;
6339 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6340 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6341 dom_sid_str));
6342 return NT_STATUS_UNSUCCESSFUL;
6345 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6346 domains, num_domains);
6348 if (*domains == NULL) {
6349 DEBUG(1, ("talloc failed\n"));
6350 return NT_STATUS_NO_MEMORY;
6354 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6355 return NT_STATUS_OK;
6359 /**********************************************************************
6360 Housekeeping
6361 *********************************************************************/
6363 static void free_private_data(void **vp)
6365 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6367 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6369 if ((*ldap_state)->result != NULL) {
6370 ldap_msgfree((*ldap_state)->result);
6371 (*ldap_state)->result = NULL;
6373 if ((*ldap_state)->domain_dn != NULL) {
6374 SAFE_FREE((*ldap_state)->domain_dn);
6377 *ldap_state = NULL;
6379 /* No need to free any further, as it is talloc()ed */
6382 /*********************************************************************
6383 Intitalise the parts of the pdb_methods structure that are common to
6384 all pdb_ldap modes
6385 *********************************************************************/
6387 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6389 NTSTATUS nt_status;
6390 struct ldapsam_privates *ldap_state;
6391 char *bind_dn = NULL;
6392 char *bind_secret = NULL;
6394 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6395 return nt_status;
6398 (*pdb_method)->name = "ldapsam";
6400 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6401 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6402 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6403 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6404 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6405 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6407 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6408 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6409 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6410 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6411 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6412 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6413 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6415 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6416 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6418 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6420 (*pdb_method)->capabilities = ldapsam_capabilities;
6421 (*pdb_method)->new_rid = ldapsam_new_rid;
6423 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6424 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6425 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6426 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6428 /* TODO: Setup private data and free */
6430 if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6431 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6432 return NT_STATUS_NO_MEMORY;
6435 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
6436 DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
6437 return NT_STATUS_NO_MEMORY;
6440 nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
6441 location, false, bind_dn, bind_secret,
6442 &ldap_state->smbldap_state);
6443 memset(bind_secret, '\0', strlen(bind_secret));
6444 SAFE_FREE(bind_secret);
6445 SAFE_FREE(bind_dn);
6446 if ( !NT_STATUS_IS_OK(nt_status) ) {
6447 return nt_status;
6450 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6451 return NT_STATUS_NO_MEMORY;
6454 (*pdb_method)->private_data = ldap_state;
6456 (*pdb_method)->free_private_data = free_private_data;
6458 return NT_STATUS_OK;
6461 /**********************************************************************
6462 Initialise the normal mode for pdb_ldap
6463 *********************************************************************/
6465 NTSTATUS pdb_ldapsam_init_common(struct pdb_methods **pdb_method,
6466 const char *location)
6468 NTSTATUS nt_status;
6469 struct ldapsam_privates *ldap_state = NULL;
6470 uint32_t alg_rid_base;
6471 char *alg_rid_base_string = NULL;
6472 LDAPMessage *result = NULL;
6473 LDAPMessage *entry = NULL;
6474 struct dom_sid ldap_domain_sid;
6475 struct dom_sid secrets_domain_sid;
6476 char *domain_sid_string = NULL;
6477 char *dn = NULL;
6478 char *uri = talloc_strdup( NULL, location );
6480 trim_char( uri, '\"', '\"' );
6481 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6483 TALLOC_FREE(uri);
6485 if (!NT_STATUS_IS_OK(nt_status)) {
6486 return nt_status;
6489 (*pdb_method)->name = "ldapsam";
6491 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6492 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6493 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6494 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6495 (*pdb_method)->search_users = ldapsam_search_users;
6496 (*pdb_method)->search_groups = ldapsam_search_groups;
6497 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6499 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6500 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6501 (*pdb_method)->enum_group_memberships =
6502 ldapsam_enum_group_memberships;
6503 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6504 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6505 (*pdb_method)->uid_to_sid = ldapsam_uid_to_sid;
6506 (*pdb_method)->gid_to_sid = ldapsam_gid_to_sid;
6508 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6509 (*pdb_method)->create_user = ldapsam_create_user;
6510 (*pdb_method)->delete_user = ldapsam_delete_user;
6511 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6512 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6513 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6514 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6515 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6519 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6520 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6522 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6524 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6525 &result,
6526 ldap_state->domain_name, True);
6528 if ( !NT_STATUS_IS_OK(nt_status) ) {
6529 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6530 "info, nor add one to the domain. "
6531 "We cannot work reliably without it.\n"));
6532 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6535 /* Given that the above might fail, everything below this must be
6536 * optional */
6538 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6539 result);
6540 if (!entry) {
6541 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6542 "entry\n"));
6543 ldap_msgfree(result);
6544 return NT_STATUS_UNSUCCESSFUL;
6547 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6548 if (!dn) {
6549 ldap_msgfree(result);
6550 return NT_STATUS_UNSUCCESSFUL;
6553 ldap_state->domain_dn = smb_xstrdup(dn);
6554 TALLOC_FREE(dn);
6556 domain_sid_string = smbldap_talloc_single_attribute(
6557 ldap_state->smbldap_state->ldap_struct,
6558 entry,
6559 get_userattr_key2string(ldap_state->schema_ver,
6560 LDAP_ATTR_USER_SID),
6561 talloc_tos());
6563 if (domain_sid_string) {
6564 bool found_sid;
6565 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6566 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6567 "read as a valid SID\n", domain_sid_string));
6568 ldap_msgfree(result);
6569 TALLOC_FREE(domain_sid_string);
6570 return NT_STATUS_INVALID_PARAMETER;
6572 found_sid = PDB_secrets_fetch_domain_sid(ldap_state->domain_name,
6573 &secrets_domain_sid);
6574 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6575 &ldap_domain_sid)) {
6576 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6577 "%s based on pdb_ldap results %s -> %s\n",
6578 ldap_state->domain_name,
6579 sid_string_dbg(&secrets_domain_sid),
6580 sid_string_dbg(&ldap_domain_sid)));
6582 /* reset secrets.tdb sid */
6583 PDB_secrets_store_domain_sid(ldap_state->domain_name,
6584 &ldap_domain_sid);
6585 DEBUG(1, ("New global sam SID: %s\n",
6586 sid_string_dbg(get_global_sam_sid())));
6588 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6589 TALLOC_FREE(domain_sid_string);
6592 alg_rid_base_string = smbldap_talloc_single_attribute(
6593 ldap_state->smbldap_state->ldap_struct,
6594 entry,
6595 get_attr_key2string( dominfo_attr_list,
6596 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6597 talloc_tos());
6598 if (alg_rid_base_string) {
6599 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6600 if (alg_rid_base != algorithmic_rid_base()) {
6601 DEBUG(0, ("The value of 'algorithmic RID base' has "
6602 "changed since the LDAP\n"
6603 "database was initialised. Aborting. \n"));
6604 ldap_msgfree(result);
6605 TALLOC_FREE(alg_rid_base_string);
6606 return NT_STATUS_UNSUCCESSFUL;
6608 TALLOC_FREE(alg_rid_base_string);
6610 ldap_msgfree(result);
6612 return NT_STATUS_OK;
6615 NTSTATUS pdb_ldapsam_init(void)
6617 NTSTATUS nt_status;
6619 nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION,
6620 "ldapsam",
6621 pdb_ldapsam_init_common);
6622 if (!NT_STATUS_IS_OK(nt_status)) {
6623 return nt_status;
6626 /* Let pdb_nds register backends */
6627 pdb_nds_init();
6629 pdb_ipa_init();
6631 return NT_STATUS_OK;