pdb_tdb: use db_open_trans()
[Samba/gbeck.git] / source / passdb / pdb_ldap.c
blob2a35faf7e01dbb6db4872c91f0c145477d49f526
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"
48 #undef DBGC_CLASS
49 #define DBGC_CLASS DBGC_PASSDB
51 #include <lber.h>
52 #include <ldap.h>
55 * Work around versions of the LDAP client libs that don't have the OIDs
56 * defined, or have them defined under the old name.
57 * This functionality is really a factor of the server, not the client
61 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
62 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
63 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
64 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
65 #endif
67 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
68 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
69 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
70 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID ((ber_tag_t) 0x80U)
71 #endif
73 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
74 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
75 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
76 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW ((ber_tag_t) 0x82U)
77 #endif
80 #include "smbldap.h"
82 /**********************************************************************
83 Simple helper function to make stuff better readable
84 **********************************************************************/
86 static LDAP *priv2ld(struct ldapsam_privates *priv)
88 return priv->smbldap_state->ldap_struct;
91 /**********************************************************************
92 Get the attribute name given a user schame version.
93 **********************************************************************/
95 static const char* get_userattr_key2string( int schema_ver, int key )
97 switch ( schema_ver ) {
98 case SCHEMAVER_SAMBAACCOUNT:
99 return get_attr_key2string( attrib_map_v22, key );
101 case SCHEMAVER_SAMBASAMACCOUNT:
102 return get_attr_key2string( attrib_map_v30, key );
104 default:
105 DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
106 break;
108 return NULL;
111 /**********************************************************************
112 Return the list of attribute names given a user schema version.
113 **********************************************************************/
115 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
117 switch ( schema_ver ) {
118 case SCHEMAVER_SAMBAACCOUNT:
119 return get_attr_list( mem_ctx, attrib_map_v22 );
121 case SCHEMAVER_SAMBASAMACCOUNT:
122 return get_attr_list( mem_ctx, attrib_map_v30 );
123 default:
124 DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
125 break;
128 return NULL;
131 /**************************************************************************
132 Return the list of attribute names to delete given a user schema version.
133 **************************************************************************/
135 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
136 int schema_ver )
138 switch ( schema_ver ) {
139 case SCHEMAVER_SAMBAACCOUNT:
140 return get_attr_list( mem_ctx,
141 attrib_map_to_delete_v22 );
143 case SCHEMAVER_SAMBASAMACCOUNT:
144 return get_attr_list( mem_ctx,
145 attrib_map_to_delete_v30 );
146 default:
147 DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
148 break;
151 return NULL;
155 /*******************************************************************
156 Generate the LDAP search filter for the objectclass based on the
157 version of the schema we are using.
158 ******************************************************************/
160 static const char* get_objclass_filter( int schema_ver )
162 fstring objclass_filter;
163 char *result;
165 switch( schema_ver ) {
166 case SCHEMAVER_SAMBAACCOUNT:
167 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
168 break;
169 case SCHEMAVER_SAMBASAMACCOUNT:
170 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
171 break;
172 default:
173 DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
174 objclass_filter[0] = '\0';
175 break;
178 result = talloc_strdup(talloc_tos(), objclass_filter);
179 SMB_ASSERT(result != NULL);
180 return result;
183 /*****************************************************************
184 Scan a sequence number off OpenLDAP's syncrepl contextCSN
185 ******************************************************************/
187 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
189 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
190 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
191 LDAPMessage *msg = NULL;
192 LDAPMessage *entry = NULL;
193 TALLOC_CTX *mem_ctx;
194 char **values = NULL;
195 int rc, num_result, num_values, rid;
196 char *suffix = NULL;
197 char *tok;
198 const char *p;
199 const char **attrs;
201 /* Unfortunatly there is no proper way to detect syncrepl-support in
202 * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
203 * but do not show up in the root-DSE yet. Neither we can query the
204 * subschema-context for the syncProviderSubentry or syncConsumerSubentry
205 * objectclass. Currently we require lp_ldap_suffix() to show up as
206 * namingContext. - Guenther
209 if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
210 return ntstatus;
213 if (!seq_num) {
214 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
215 return ntstatus;
218 if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix())) {
219 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
220 "as top-level namingContext\n", lp_ldap_suffix()));
221 return ntstatus;
224 mem_ctx = talloc_init("ldapsam_get_seq_num");
226 if (mem_ctx == NULL)
227 return NT_STATUS_NO_MEMORY;
229 if ((attrs = TALLOC_ARRAY(mem_ctx, const char *, 2)) == NULL) {
230 ntstatus = NT_STATUS_NO_MEMORY;
231 goto done;
234 /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
235 rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
236 if (rid > 0) {
238 /* consumer syncreplCookie: */
239 /* csn=20050126161620Z#0000001#00#00000 */
240 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
241 attrs[1] = NULL;
242 suffix = talloc_asprintf(mem_ctx,
243 "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
244 if (!suffix) {
245 ntstatus = NT_STATUS_NO_MEMORY;
246 goto done;
248 } else {
250 /* provider contextCSN */
251 /* 20050126161620Z#000009#00#000000 */
252 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
253 attrs[1] = NULL;
254 suffix = talloc_asprintf(mem_ctx,
255 "cn=ldapsync,%s", lp_ldap_suffix());
257 if (!suffix) {
258 ntstatus = NT_STATUS_NO_MEMORY;
259 goto done;
263 rc = smbldap_search(ldap_state->smbldap_state, suffix,
264 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
266 if (rc != LDAP_SUCCESS) {
267 goto done;
270 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
271 if (num_result != 1) {
272 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
273 goto done;
276 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
277 if (entry == NULL) {
278 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
279 goto done;
282 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
283 if (values == NULL) {
284 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
285 goto done;
288 num_values = ldap_count_values(values);
289 if (num_values == 0) {
290 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
291 goto done;
294 p = values[0];
295 if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
296 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
297 goto done;
300 p = tok;
301 if (!strncmp(p, "csn=", strlen("csn=")))
302 p += strlen("csn=");
304 DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
306 *seq_num = generalized_to_unix_time(p);
308 /* very basic sanity check */
309 if (*seq_num <= 0) {
310 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n",
311 (int)*seq_num));
312 goto done;
315 ntstatus = NT_STATUS_OK;
317 done:
318 if (values != NULL)
319 ldap_value_free(values);
320 if (msg != NULL)
321 ldap_msgfree(msg);
322 if (mem_ctx)
323 talloc_destroy(mem_ctx);
325 return ntstatus;
328 /*******************************************************************
329 Run the search by name.
330 ******************************************************************/
332 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
333 const char *user,
334 LDAPMessage ** result,
335 const char **attr)
337 char *filter = NULL;
338 char *escape_user = escape_ldap_string_alloc(user);
339 int ret = -1;
341 if (!escape_user) {
342 return LDAP_NO_MEMORY;
346 * in the filter expression, replace %u with the real name
347 * so in ldap filter, %u MUST exist :-)
349 filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
350 get_objclass_filter(ldap_state->schema_ver));
351 if (!filter) {
352 return LDAP_NO_MEMORY;
355 * have to use this here because $ is filtered out
356 * in string_sub
359 filter = talloc_all_string_sub(talloc_tos(),
360 filter, "%u", escape_user);
361 if (!filter) {
362 return LDAP_NO_MEMORY;
364 SAFE_FREE(escape_user);
366 ret = smbldap_search_suffix(ldap_state->smbldap_state,
367 filter, attr, result);
368 TALLOC_FREE(filter);
369 return ret;
372 /*******************************************************************
373 Run the search by rid.
374 ******************************************************************/
376 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
377 uint32 rid, LDAPMessage ** result,
378 const char **attr)
380 char *filter = NULL;
381 int rc;
383 filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
384 get_objclass_filter(ldap_state->schema_ver));
385 if (!filter) {
386 return LDAP_NO_MEMORY;
389 rc = smbldap_search_suffix(ldap_state->smbldap_state,
390 filter, attr, result);
391 TALLOC_FREE(filter);
392 return rc;
395 /*******************************************************************
396 Run the search by SID.
397 ******************************************************************/
399 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
400 const DOM_SID *sid, LDAPMessage ** result,
401 const char **attr)
403 char *filter = NULL;
404 int rc;
405 fstring sid_string;
407 filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
408 get_userattr_key2string(ldap_state->schema_ver,
409 LDAP_ATTR_USER_SID),
410 sid_to_fstring(sid_string, sid),
411 get_objclass_filter(ldap_state->schema_ver));
412 if (!filter) {
413 return LDAP_NO_MEMORY;
416 rc = smbldap_search_suffix(ldap_state->smbldap_state,
417 filter, attr, result);
419 TALLOC_FREE(filter);
420 return rc;
423 /*******************************************************************
424 Delete complete object or objectclass and attrs from
425 object found in search_result depending on lp_ldap_delete_dn
426 ******************************************************************/
428 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
429 TALLOC_CTX *mem_ctx,
430 LDAPMessage *entry,
431 const char *objectclass,
432 const char **attrs)
434 LDAPMod **mods = NULL;
435 char *name;
436 const char *dn;
437 BerElement *ptr = NULL;
439 dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
440 if (dn == NULL) {
441 return LDAP_NO_MEMORY;
444 if (lp_ldap_delete_dn()) {
445 return smbldap_delete(priv->smbldap_state, dn);
448 /* Ok, delete only the SAM attributes */
450 for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
451 name != NULL;
452 name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
453 const char **attrib;
455 /* We are only allowed to delete the attributes that
456 really exist. */
458 for (attrib = attrs; *attrib != NULL; attrib++) {
459 if (strequal(*attrib, name)) {
460 DEBUG(10, ("ldapsam_delete_entry: deleting "
461 "attribute %s\n", name));
462 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
463 NULL);
466 ldap_memfree(name);
469 if (ptr != NULL) {
470 ber_free(ptr, 0);
473 smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
474 talloc_autofree_ldapmod(mem_ctx, mods);
476 return smbldap_modify(priv->smbldap_state, dn, mods);
479 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
481 char *temp;
482 struct tm tm;
484 temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
485 get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
486 talloc_tos());
487 if (!temp) {
488 return (time_t) 0;
491 if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
492 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
493 (char*)temp));
494 TALLOC_FREE(temp);
495 return (time_t) 0;
497 TALLOC_FREE(temp);
498 tzset();
499 return timegm(&tm);
502 /**********************************************************************
503 Initialize struct samu from an LDAP query.
504 (Based on init_sam_from_buffer in pdb_tdb.c)
505 *********************************************************************/
507 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
508 struct samu * sampass,
509 LDAPMessage * entry)
511 time_t logon_time,
512 logoff_time,
513 kickoff_time,
514 pass_last_set_time,
515 pass_can_change_time,
516 pass_must_change_time,
517 ldap_entry_time,
518 bad_password_time;
519 char *username = NULL,
520 *domain = NULL,
521 *nt_username = NULL,
522 *fullname = NULL,
523 *homedir = NULL,
524 *dir_drive = NULL,
525 *logon_script = NULL,
526 *profile_path = NULL,
527 *acct_desc = NULL,
528 *workstations = NULL,
529 *munged_dial = NULL;
530 uint32 user_rid;
531 uint8 smblmpwd[LM_HASH_LEN],
532 smbntpwd[NT_HASH_LEN];
533 bool use_samba_attrs = True;
534 uint32 acct_ctrl = 0;
535 uint16 logon_divs;
536 uint16 bad_password_count = 0,
537 logon_count = 0;
538 uint32 hours_len;
539 uint8 hours[MAX_HOURS_LEN];
540 char *temp = NULL;
541 LOGIN_CACHE *cache_entry = NULL;
542 uint32 pwHistLen;
543 bool expand_explicit = lp_passdb_expand_explicit();
544 bool ret = false;
545 TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
547 if (!ctx) {
548 return false;
550 if (sampass == NULL || ldap_state == NULL || entry == NULL) {
551 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
552 goto fn_exit;
555 if (priv2ld(ldap_state) == NULL) {
556 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
557 "ldap_struct is NULL!\n"));
558 goto fn_exit;
561 if (!(username = smbldap_talloc_single_attribute(priv2ld(ldap_state),
562 entry,
563 "uid",
564 ctx))) {
565 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
566 "this user!\n"));
567 goto fn_exit;
570 DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
572 nt_username = talloc_strdup(ctx, username);
573 if (!nt_username) {
574 goto fn_exit;
577 domain = talloc_strdup(ctx, ldap_state->domain_name);
578 if (!domain) {
579 goto fn_exit;
582 pdb_set_username(sampass, username, PDB_SET);
584 pdb_set_domain(sampass, domain, PDB_DEFAULT);
585 pdb_set_nt_username(sampass, nt_username, PDB_SET);
587 /* deal with different attributes between the schema first */
589 if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
590 if ((temp = smbldap_talloc_single_attribute(
591 ldap_state->smbldap_state->ldap_struct,
592 entry,
593 get_userattr_key2string(ldap_state->schema_ver,
594 LDAP_ATTR_USER_SID),
595 ctx))!=NULL) {
596 pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
598 } else {
599 if ((temp = smbldap_talloc_single_attribute(
600 ldap_state->smbldap_state->ldap_struct,
601 entry,
602 get_userattr_key2string(ldap_state->schema_ver,
603 LDAP_ATTR_USER_RID),
604 ctx))!=NULL) {
605 user_rid = (uint32)atol(temp);
606 pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
610 if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
611 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n",
612 get_userattr_key2string(ldap_state->schema_ver,
613 LDAP_ATTR_USER_SID),
614 get_userattr_key2string(ldap_state->schema_ver,
615 LDAP_ATTR_USER_RID),
616 username));
617 return False;
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_PWD_LAST_SET),
625 ctx);
626 if (temp) {
627 pass_last_set_time = (time_t) atol(temp);
628 pdb_set_pass_last_set_time(sampass,
629 pass_last_set_time, PDB_SET);
632 temp = smbldap_talloc_single_attribute(
633 ldap_state->smbldap_state->ldap_struct,
634 entry,
635 get_userattr_key2string(ldap_state->schema_ver,
636 LDAP_ATTR_LOGON_TIME),
637 ctx);
638 if (temp) {
639 logon_time = (time_t) atol(temp);
640 pdb_set_logon_time(sampass, logon_time, PDB_SET);
643 temp = smbldap_talloc_single_attribute(
644 ldap_state->smbldap_state->ldap_struct,
645 entry,
646 get_userattr_key2string(ldap_state->schema_ver,
647 LDAP_ATTR_LOGOFF_TIME),
648 ctx);
649 if (temp) {
650 logoff_time = (time_t) atol(temp);
651 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
654 temp = smbldap_talloc_single_attribute(
655 ldap_state->smbldap_state->ldap_struct,
656 entry,
657 get_userattr_key2string(ldap_state->schema_ver,
658 LDAP_ATTR_KICKOFF_TIME),
659 ctx);
660 if (temp) {
661 kickoff_time = (time_t) atol(temp);
662 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
665 temp = smbldap_talloc_single_attribute(
666 ldap_state->smbldap_state->ldap_struct,
667 entry,
668 get_userattr_key2string(ldap_state->schema_ver,
669 LDAP_ATTR_PWD_CAN_CHANGE),
670 ctx);
671 if (temp) {
672 pass_can_change_time = (time_t) atol(temp);
673 pdb_set_pass_can_change_time(sampass,
674 pass_can_change_time, PDB_SET);
677 temp = smbldap_talloc_single_attribute(
678 ldap_state->smbldap_state->ldap_struct,
679 entry,
680 get_userattr_key2string(ldap_state->schema_ver,
681 LDAP_ATTR_PWD_MUST_CHANGE),
682 ctx);
683 if (temp) {
684 pass_must_change_time = (time_t) atol(temp);
685 pdb_set_pass_must_change_time(sampass,
686 pass_must_change_time, PDB_SET);
689 /* recommend that 'gecos' and 'displayName' should refer to the same
690 * attribute OID. userFullName depreciated, only used by Samba
691 * primary rules of LDAP: don't make a new attribute when one is already defined
692 * that fits your needs; using cn then displayName rather than 'userFullName'
695 fullname = smbldap_talloc_single_attribute(
696 ldap_state->smbldap_state->ldap_struct,
697 entry,
698 get_userattr_key2string(ldap_state->schema_ver,
699 LDAP_ATTR_DISPLAY_NAME),
700 ctx);
701 if (fullname) {
702 pdb_set_fullname(sampass, fullname, PDB_SET);
703 } else {
704 fullname = smbldap_talloc_single_attribute(
705 ldap_state->smbldap_state->ldap_struct,
706 entry,
707 get_userattr_key2string(ldap_state->schema_ver,
708 LDAP_ATTR_CN),
709 ctx);
710 if (fullname) {
711 pdb_set_fullname(sampass, fullname, PDB_SET);
715 dir_drive = smbldap_talloc_single_attribute(
716 ldap_state->smbldap_state->ldap_struct,
717 entry,
718 get_userattr_key2string(ldap_state->schema_ver,
719 LDAP_ATTR_HOME_DRIVE),
720 ctx);
721 if (dir_drive) {
722 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
723 } else {
724 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
727 homedir = smbldap_talloc_single_attribute(
728 ldap_state->smbldap_state->ldap_struct,
729 entry,
730 get_userattr_key2string(ldap_state->schema_ver,
731 LDAP_ATTR_HOME_PATH),
732 ctx);
733 if (homedir) {
734 if (expand_explicit) {
735 homedir = talloc_sub_basic(ctx,
736 username,
737 domain,
738 homedir);
739 if (!homedir) {
740 goto fn_exit;
743 pdb_set_homedir(sampass, homedir, PDB_SET);
744 } else {
745 pdb_set_homedir(sampass,
746 talloc_sub_basic(ctx, username, domain,
747 lp_logon_home()),
748 PDB_DEFAULT);
751 logon_script = smbldap_talloc_single_attribute(
752 ldap_state->smbldap_state->ldap_struct,
753 entry,
754 get_userattr_key2string(ldap_state->schema_ver,
755 LDAP_ATTR_LOGON_SCRIPT),
756 ctx);
757 if (logon_script) {
758 if (expand_explicit) {
759 logon_script = talloc_sub_basic(ctx,
760 username,
761 domain,
762 logon_script);
763 if (!logon_script) {
764 goto fn_exit;
767 pdb_set_logon_script(sampass, logon_script, PDB_SET);
768 } else {
769 pdb_set_logon_script(sampass,
770 talloc_sub_basic(ctx, username, domain,
771 lp_logon_script()),
772 PDB_DEFAULT );
775 profile_path = smbldap_talloc_single_attribute(
776 ldap_state->smbldap_state->ldap_struct,
777 entry,
778 get_userattr_key2string(ldap_state->schema_ver,
779 LDAP_ATTR_PROFILE_PATH),
780 ctx);
781 if (profile_path) {
782 if (expand_explicit) {
783 profile_path = talloc_sub_basic(ctx,
784 username,
785 domain,
786 profile_path);
787 if (!profile_path) {
788 goto fn_exit;
791 pdb_set_profile_path(sampass, profile_path, PDB_SET);
792 } else {
793 pdb_set_profile_path(sampass,
794 talloc_sub_basic(ctx, username, domain,
795 lp_logon_path()),
796 PDB_DEFAULT );
799 acct_desc = smbldap_talloc_single_attribute(
800 ldap_state->smbldap_state->ldap_struct,
801 entry,
802 get_userattr_key2string(ldap_state->schema_ver,
803 LDAP_ATTR_DESC),
804 ctx);
805 if (acct_desc) {
806 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
809 workstations = smbldap_talloc_single_attribute(
810 ldap_state->smbldap_state->ldap_struct,
811 entry,
812 get_userattr_key2string(ldap_state->schema_ver,
813 LDAP_ATTR_USER_WKS),
814 ctx);
815 if (workstations) {
816 pdb_set_workstations(sampass, workstations, PDB_SET);
819 munged_dial = smbldap_talloc_single_attribute(
820 ldap_state->smbldap_state->ldap_struct,
821 entry,
822 get_userattr_key2string(ldap_state->schema_ver,
823 LDAP_ATTR_MUNGED_DIAL),
824 ctx);
825 if (munged_dial) {
826 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
829 /* FIXME: hours stuff should be cleaner */
831 logon_divs = 168;
832 hours_len = 21;
833 memset(hours, 0xff, hours_len);
835 if (ldap_state->is_nds_ldap) {
836 char *user_dn;
837 size_t pwd_len;
838 char clear_text_pw[512];
840 /* Make call to Novell eDirectory ldap extension to get clear text password.
841 NOTE: This will only work if we have an SSL connection to eDirectory. */
842 user_dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
843 if (user_dn != NULL) {
844 DEBUG(3, ("init_sam_from_ldap: smbldap_get_dn(%s) returned '%s'\n", username, user_dn));
846 pwd_len = sizeof(clear_text_pw);
847 if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
848 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
849 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
850 SAFE_FREE(user_dn);
851 return False;
853 ZERO_STRUCT(smblmpwd);
854 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
855 SAFE_FREE(user_dn);
856 return False;
858 ZERO_STRUCT(smbntpwd);
859 use_samba_attrs = False;
862 SAFE_FREE(user_dn);
864 } else {
865 DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
869 if (use_samba_attrs) {
870 temp = smbldap_talloc_single_attribute(
871 ldap_state->smbldap_state->ldap_struct,
872 entry,
873 get_userattr_key2string(ldap_state->schema_ver,
874 LDAP_ATTR_LMPW),
875 ctx);
876 if (temp) {
877 pdb_gethexpwd(temp, smblmpwd);
878 memset((char *)temp, '\0', strlen(temp)+1);
879 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
880 goto fn_exit;
882 ZERO_STRUCT(smblmpwd);
885 temp = smbldap_talloc_single_attribute(
886 ldap_state->smbldap_state->ldap_struct,
887 entry,
888 get_userattr_key2string(ldap_state->schema_ver,
889 LDAP_ATTR_NTPW),
890 ctx);
891 if (temp) {
892 pdb_gethexpwd(temp, smbntpwd);
893 memset((char *)temp, '\0', strlen(temp)+1);
894 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
895 goto fn_exit;
897 ZERO_STRUCT(smbntpwd);
901 pwHistLen = 0;
903 pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
904 if (pwHistLen > 0){
905 uint8 *pwhist = NULL;
906 int i;
907 char *history_string = TALLOC_ARRAY(ctx, char,
908 MAX_PW_HISTORY_LEN*64);
910 if (!history_string) {
911 goto fn_exit;
914 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
916 if ((pwhist = TALLOC_ARRAY(ctx, uint8,
917 pwHistLen * PW_HISTORY_ENTRY_LEN)) ==
918 NULL){
919 DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
920 goto fn_exit;
922 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
924 if (smbldap_get_single_attribute(
925 ldap_state->smbldap_state->ldap_struct,
926 entry,
927 get_userattr_key2string(ldap_state->schema_ver,
928 LDAP_ATTR_PWD_HISTORY),
929 history_string,
930 MAX_PW_HISTORY_LEN*64)) {
931 bool hex_failed = false;
932 for (i = 0; i < pwHistLen; i++){
933 /* Get the 16 byte salt. */
934 if (!pdb_gethexpwd(&history_string[i*64],
935 &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
936 hex_failed = true;
937 break;
939 /* Get the 16 byte MD5 hash of salt+passwd. */
940 if (!pdb_gethexpwd(&history_string[(i*64)+32],
941 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
942 PW_HISTORY_SALT_LEN])) {
943 hex_failed = True;
944 break;
947 if (hex_failed) {
948 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
949 username));
950 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
953 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
954 goto fn_exit;
958 temp = smbldap_talloc_single_attribute(
959 ldap_state->smbldap_state->ldap_struct,
960 entry,
961 get_userattr_key2string(ldap_state->schema_ver,
962 LDAP_ATTR_ACB_INFO),
963 ctx);
964 if (temp) {
965 acct_ctrl = pdb_decode_acct_ctrl(temp);
967 if (acct_ctrl == 0) {
968 acct_ctrl |= ACB_NORMAL;
971 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
972 } else {
973 acct_ctrl |= ACB_NORMAL;
976 pdb_set_hours_len(sampass, hours_len, PDB_SET);
977 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
979 temp = smbldap_talloc_single_attribute(
980 ldap_state->smbldap_state->ldap_struct,
981 entry,
982 get_userattr_key2string(ldap_state->schema_ver,
983 LDAP_ATTR_BAD_PASSWORD_COUNT),
984 ctx);
985 if (temp) {
986 bad_password_count = (uint32) atol(temp);
987 pdb_set_bad_password_count(sampass,
988 bad_password_count, PDB_SET);
991 temp = smbldap_talloc_single_attribute(
992 ldap_state->smbldap_state->ldap_struct,
993 entry,
994 get_userattr_key2string(ldap_state->schema_ver,
995 LDAP_ATTR_BAD_PASSWORD_TIME),
996 ctx);
997 if (temp) {
998 bad_password_time = (time_t) atol(temp);
999 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
1003 temp = smbldap_talloc_single_attribute(
1004 ldap_state->smbldap_state->ldap_struct,
1005 entry,
1006 get_userattr_key2string(ldap_state->schema_ver,
1007 LDAP_ATTR_LOGON_COUNT),
1008 ctx);
1009 if (temp) {
1010 logon_count = (uint32) atol(temp);
1011 pdb_set_logon_count(sampass, logon_count, PDB_SET);
1014 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
1016 temp = smbldap_talloc_single_attribute(
1017 ldap_state->smbldap_state->ldap_struct,
1018 entry,
1019 get_userattr_key2string(ldap_state->schema_ver,
1020 LDAP_ATTR_LOGON_HOURS),
1021 ctx);
1022 if (temp) {
1023 pdb_gethexhours(temp, hours);
1024 memset((char *)temp, '\0', strlen(temp) +1);
1025 pdb_set_hours(sampass, hours, PDB_SET);
1026 ZERO_STRUCT(hours);
1029 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
1030 temp = smbldap_talloc_single_attribute(
1031 priv2ld(ldap_state),
1032 entry,
1033 "uidNumber",
1034 ctx);
1035 if (temp) {
1036 /* We've got a uid, feed the cache */
1037 uid_t uid = strtoul(temp, NULL, 10);
1038 store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
1042 /* check the timestamp of the cache vs ldap entry */
1043 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1044 entry))) {
1045 ret = true;
1046 goto fn_exit;
1049 /* see if we have newer updates */
1050 if (!(cache_entry = login_cache_read(sampass))) {
1051 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1052 (unsigned int)pdb_get_bad_password_count(sampass),
1053 (unsigned int)pdb_get_bad_password_time(sampass)));
1054 ret = true;
1055 goto fn_exit;
1058 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1059 (unsigned int)ldap_entry_time,
1060 (unsigned int)cache_entry->entry_timestamp,
1061 (unsigned int)cache_entry->bad_password_time));
1063 if (ldap_entry_time > cache_entry->entry_timestamp) {
1064 /* cache is older than directory , so
1065 we need to delete the entry but allow the
1066 fields to be written out */
1067 login_cache_delentry(sampass);
1068 } else {
1069 /* read cache in */
1070 pdb_set_acct_ctrl(sampass,
1071 pdb_get_acct_ctrl(sampass) |
1072 (cache_entry->acct_ctrl & ACB_AUTOLOCK),
1073 PDB_SET);
1074 pdb_set_bad_password_count(sampass,
1075 cache_entry->bad_password_count,
1076 PDB_SET);
1077 pdb_set_bad_password_time(sampass,
1078 cache_entry->bad_password_time,
1079 PDB_SET);
1082 ret = true;
1084 fn_exit:
1086 TALLOC_FREE(ctx);
1087 SAFE_FREE(cache_entry);
1088 return ret;
1091 /**********************************************************************
1092 Initialize the ldap db from a struct samu. Called on update.
1093 (Based on init_buffer_from_sam in pdb_tdb.c)
1094 *********************************************************************/
1096 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1097 LDAPMessage *existing,
1098 LDAPMod *** mods, struct samu * sampass,
1099 bool (*need_update)(const struct samu *,
1100 enum pdb_elements))
1102 char *temp = NULL;
1103 uint32 rid;
1105 if (mods == NULL || sampass == NULL) {
1106 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1107 return False;
1110 *mods = NULL;
1113 * took out adding "objectclass: sambaAccount"
1114 * do this on a per-mod basis
1116 if (need_update(sampass, PDB_USERNAME)) {
1117 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1118 "uid", pdb_get_username(sampass));
1119 if (ldap_state->is_nds_ldap) {
1120 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1121 "cn", pdb_get_username(sampass));
1122 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1123 "sn", pdb_get_username(sampass));
1127 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1129 /* only update the RID if we actually need to */
1130 if (need_update(sampass, PDB_USERSID)) {
1131 fstring sid_string;
1132 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
1134 switch ( ldap_state->schema_ver ) {
1135 case SCHEMAVER_SAMBAACCOUNT:
1136 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
1137 DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1138 sid_string_dbg(user_sid),
1139 sid_string_dbg(
1140 &ldap_state->domain_sid)));
1141 return False;
1143 if (asprintf(&temp, "%i", rid) < 0) {
1144 return false;
1146 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1147 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
1148 temp);
1149 SAFE_FREE(temp);
1150 break;
1152 case SCHEMAVER_SAMBASAMACCOUNT:
1153 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1154 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1155 sid_to_fstring(sid_string, user_sid));
1156 break;
1158 default:
1159 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1160 break;
1164 /* we don't need to store the primary group RID - so leaving it
1165 'free' to hang off the unix primary group makes life easier */
1167 if (need_update(sampass, PDB_GROUPSID)) {
1168 fstring sid_string;
1169 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1171 switch ( ldap_state->schema_ver ) {
1172 case SCHEMAVER_SAMBAACCOUNT:
1173 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1174 DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1175 sid_string_dbg(group_sid),
1176 sid_string_dbg(
1177 &ldap_state->domain_sid)));
1178 return False;
1181 if (asprintf(&temp, "%i", rid) < 0) {
1182 return false;
1184 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1185 get_userattr_key2string(ldap_state->schema_ver,
1186 LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1187 SAFE_FREE(temp);
1188 break;
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", 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", 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", 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", 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 (asprintf(&temp, "%li", pdb_get_pass_must_change_time(sampass)) < 0) {
1284 return false;
1286 if (need_update(sampass, PDB_MUSTCHANGETIME))
1287 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1288 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1289 SAFE_FREE(temp);
1291 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1292 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1294 if (need_update(sampass, PDB_LMPASSWD)) {
1295 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1296 if (lm_pw) {
1297 char pwstr[34];
1298 pdb_sethexpwd(pwstr, lm_pw,
1299 pdb_get_acct_ctrl(sampass));
1300 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1301 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1302 pwstr);
1303 } else {
1304 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1305 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1306 NULL);
1309 if (need_update(sampass, PDB_NTPASSWD)) {
1310 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1311 if (nt_pw) {
1312 char pwstr[34];
1313 pdb_sethexpwd(pwstr, nt_pw,
1314 pdb_get_acct_ctrl(sampass));
1315 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1316 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1317 pwstr);
1318 } else {
1319 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1320 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1321 NULL);
1325 if (need_update(sampass, PDB_PWHISTORY)) {
1326 char *pwstr = NULL;
1327 uint32 pwHistLen = 0;
1328 pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1330 pwstr = SMB_MALLOC_ARRAY(char, 1024);
1331 if (!pwstr) {
1332 return false;
1334 if (pwHistLen == 0) {
1335 /* Remove any password history from the LDAP store. */
1336 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1337 pwstr[64] = '\0';
1338 } else {
1339 int i;
1340 uint32 currHistLen = 0;
1341 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1342 if (pwhist != NULL) {
1343 /* We can only store (1024-1/64 password history entries. */
1344 pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1345 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1346 /* Store the salt. */
1347 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1348 /* Followed by the md5 hash of salt + md4 hash */
1349 pdb_sethexpwd(&pwstr[(i*64)+32],
1350 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1351 DEBUG(100, ("pwstr=%s\n", pwstr));
1355 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1356 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1357 pwstr);
1358 SAFE_FREE(pwstr);
1361 if (need_update(sampass, PDB_PASSLASTSET)) {
1362 if (asprintf(&temp, "%li",
1363 pdb_get_pass_last_set_time(sampass)) < 0) {
1364 return false;
1366 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1367 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1368 temp);
1369 SAFE_FREE(temp);
1373 if (need_update(sampass, PDB_HOURS)) {
1374 const uint8 *hours = pdb_get_hours(sampass);
1375 if (hours) {
1376 char hourstr[44];
1377 pdb_sethexhours(hourstr, hours);
1378 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1379 existing,
1380 mods,
1381 get_userattr_key2string(ldap_state->schema_ver,
1382 LDAP_ATTR_LOGON_HOURS),
1383 hourstr);
1387 if (need_update(sampass, PDB_ACCTCTRL))
1388 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1389 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1390 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1392 /* password lockout cache:
1393 - If we are now autolocking or clearing, we write to ldap
1394 - If we are clearing, we delete the cache entry
1395 - If the count is > 0, we update the cache
1397 This even means when autolocking, we cache, just in case the
1398 update doesn't work, and we have to cache the autolock flag */
1400 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1401 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1402 uint16 badcount = pdb_get_bad_password_count(sampass);
1403 time_t badtime = pdb_get_bad_password_time(sampass);
1404 uint32 pol;
1405 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1407 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1408 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1410 if ((badcount >= pol) || (badcount == 0)) {
1411 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1412 (unsigned int)badcount, (unsigned int)badtime));
1413 if (asprintf(&temp, "%li", (long)badcount) < 0) {
1414 return false;
1416 smbldap_make_mod(
1417 ldap_state->smbldap_state->ldap_struct,
1418 existing, mods,
1419 get_userattr_key2string(
1420 ldap_state->schema_ver,
1421 LDAP_ATTR_BAD_PASSWORD_COUNT),
1422 temp);
1423 SAFE_FREE(temp);
1425 if (asprintf(&temp, "%li", badtime) < 0) {
1426 return false;
1428 smbldap_make_mod(
1429 ldap_state->smbldap_state->ldap_struct,
1430 existing, mods,
1431 get_userattr_key2string(
1432 ldap_state->schema_ver,
1433 LDAP_ATTR_BAD_PASSWORD_TIME),
1434 temp);
1435 SAFE_FREE(temp);
1437 if (badcount == 0) {
1438 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1439 login_cache_delentry(sampass);
1440 } else {
1441 LOGIN_CACHE cache_entry;
1443 cache_entry.entry_timestamp = time(NULL);
1444 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1445 cache_entry.bad_password_count = badcount;
1446 cache_entry.bad_password_time = badtime;
1448 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1449 login_cache_write(sampass, cache_entry);
1453 return True;
1456 /**********************************************************************
1457 End enumeration of the LDAP password list.
1458 *********************************************************************/
1460 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1462 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1463 if (ldap_state->result) {
1464 ldap_msgfree(ldap_state->result);
1465 ldap_state->result = NULL;
1469 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1470 const char *new_attr)
1472 int i;
1474 if (new_attr == NULL) {
1475 return;
1478 for (i=0; (*attr_list)[i] != NULL; i++) {
1482 (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1483 const char *, i+2);
1484 SMB_ASSERT((*attr_list) != NULL);
1485 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1486 (*attr_list)[i+1] = NULL;
1489 /**********************************************************************
1490 Get struct samu entry from LDAP by username.
1491 *********************************************************************/
1493 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1495 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1496 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1497 LDAPMessage *result = NULL;
1498 LDAPMessage *entry = NULL;
1499 int count;
1500 const char ** attr_list;
1501 int rc;
1503 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1504 append_attr(user, &attr_list,
1505 get_userattr_key2string(ldap_state->schema_ver,
1506 LDAP_ATTR_MOD_TIMESTAMP));
1507 append_attr(user, &attr_list, "uidNumber");
1508 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1509 attr_list);
1510 TALLOC_FREE( attr_list );
1512 if ( rc != LDAP_SUCCESS )
1513 return NT_STATUS_NO_SUCH_USER;
1515 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1517 if (count < 1) {
1518 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1519 ldap_msgfree(result);
1520 return NT_STATUS_NO_SUCH_USER;
1521 } else if (count > 1) {
1522 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1523 ldap_msgfree(result);
1524 return NT_STATUS_NO_SUCH_USER;
1527 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1528 if (entry) {
1529 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1530 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1531 ldap_msgfree(result);
1532 return NT_STATUS_NO_SUCH_USER;
1534 pdb_set_backend_private_data(user, result, NULL,
1535 my_methods, PDB_CHANGED);
1536 talloc_autofree_ldapmsg(user, result);
1537 ret = NT_STATUS_OK;
1538 } else {
1539 ldap_msgfree(result);
1541 return ret;
1544 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1545 const DOM_SID *sid, LDAPMessage **result)
1547 int rc = -1;
1548 const char ** attr_list;
1549 uint32 rid;
1551 switch ( ldap_state->schema_ver ) {
1552 case SCHEMAVER_SAMBASAMACCOUNT: {
1553 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1554 if (tmp_ctx == NULL) {
1555 return LDAP_NO_MEMORY;
1558 attr_list = get_userattr_list(tmp_ctx,
1559 ldap_state->schema_ver);
1560 append_attr(tmp_ctx, &attr_list,
1561 get_userattr_key2string(
1562 ldap_state->schema_ver,
1563 LDAP_ATTR_MOD_TIMESTAMP));
1564 append_attr(tmp_ctx, &attr_list, "uidNumber");
1565 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1566 result, attr_list);
1567 TALLOC_FREE(tmp_ctx);
1569 if ( rc != LDAP_SUCCESS )
1570 return rc;
1571 break;
1574 case SCHEMAVER_SAMBAACCOUNT:
1575 if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1576 return rc;
1579 attr_list = get_userattr_list(NULL,
1580 ldap_state->schema_ver);
1581 rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1582 TALLOC_FREE( attr_list );
1584 if ( rc != LDAP_SUCCESS )
1585 return rc;
1586 break;
1588 return rc;
1591 /**********************************************************************
1592 Get struct samu entry from LDAP by SID.
1593 *********************************************************************/
1595 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1597 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1598 LDAPMessage *result = NULL;
1599 LDAPMessage *entry = NULL;
1600 int count;
1601 int rc;
1603 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1604 sid, &result);
1605 if (rc != LDAP_SUCCESS)
1606 return NT_STATUS_NO_SUCH_USER;
1608 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1610 if (count < 1) {
1611 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1612 "count=%d\n", sid_string_dbg(sid), count));
1613 ldap_msgfree(result);
1614 return NT_STATUS_NO_SUCH_USER;
1615 } else if (count > 1) {
1616 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1617 "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1618 count));
1619 ldap_msgfree(result);
1620 return NT_STATUS_NO_SUCH_USER;
1623 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1624 if (!entry) {
1625 ldap_msgfree(result);
1626 return NT_STATUS_NO_SUCH_USER;
1629 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1630 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1631 ldap_msgfree(result);
1632 return NT_STATUS_NO_SUCH_USER;
1635 pdb_set_backend_private_data(user, result, NULL,
1636 my_methods, PDB_CHANGED);
1637 talloc_autofree_ldapmsg(user, result);
1638 return NT_STATUS_OK;
1641 /********************************************************************
1642 Do the actual modification - also change a plaintext passord if
1643 it it set.
1644 **********************************************************************/
1646 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1647 struct samu *newpwd, char *dn,
1648 LDAPMod **mods, int ldap_op,
1649 bool (*need_update)(const struct samu *, enum pdb_elements))
1651 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1652 int rc;
1654 if (!newpwd || !dn) {
1655 return NT_STATUS_INVALID_PARAMETER;
1658 if (!mods) {
1659 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1660 /* may be password change below however */
1661 } else {
1662 switch(ldap_op) {
1663 case LDAP_MOD_ADD:
1664 if (ldap_state->is_nds_ldap) {
1665 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1666 "objectclass",
1667 "inetOrgPerson");
1668 } else {
1669 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1670 "objectclass",
1671 LDAP_OBJ_ACCOUNT);
1673 rc = smbldap_add(ldap_state->smbldap_state,
1674 dn, mods);
1675 break;
1676 case LDAP_MOD_REPLACE:
1677 rc = smbldap_modify(ldap_state->smbldap_state,
1678 dn ,mods);
1679 break;
1680 default:
1681 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1682 ldap_op));
1683 return NT_STATUS_INVALID_PARAMETER;
1686 if (rc!=LDAP_SUCCESS) {
1687 return NT_STATUS_UNSUCCESSFUL;
1691 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1692 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1693 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1694 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1695 BerElement *ber;
1696 struct berval *bv;
1697 char *retoid = NULL;
1698 struct berval *retdata = NULL;
1699 char *utf8_password;
1700 char *utf8_dn;
1702 if (!ldap_state->is_nds_ldap) {
1704 if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct,
1705 LDAP_EXOP_MODIFY_PASSWD)) {
1706 DEBUG(2, ("ldap password change requested, but LDAP "
1707 "server does not support it -- ignoring\n"));
1708 return NT_STATUS_OK;
1712 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1713 return NT_STATUS_NO_MEMORY;
1716 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1717 SAFE_FREE(utf8_password);
1718 return NT_STATUS_NO_MEMORY;
1721 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1722 DEBUG(0,("ber_alloc_t returns NULL\n"));
1723 SAFE_FREE(utf8_password);
1724 SAFE_FREE(utf8_dn);
1725 return NT_STATUS_UNSUCCESSFUL;
1728 if ((ber_printf (ber, "{") < 0) ||
1729 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn) < 0) ||
1730 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password) < 0) ||
1731 (ber_printf (ber, "n}") < 0)) {
1732 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a value <0\n"));
1733 ber_free(ber,1);
1734 SAFE_FREE(utf8_dn);
1735 SAFE_FREE(utf8_password);
1736 return NT_STATUS_UNSUCCESSFUL;
1739 if ((rc = ber_flatten (ber, &bv))<0) {
1740 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1741 ber_free(ber,1);
1742 SAFE_FREE(utf8_dn);
1743 SAFE_FREE(utf8_password);
1744 return NT_STATUS_UNSUCCESSFUL;
1747 SAFE_FREE(utf8_dn);
1748 SAFE_FREE(utf8_password);
1749 ber_free(ber, 1);
1751 if (!ldap_state->is_nds_ldap) {
1752 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1753 LDAP_EXOP_MODIFY_PASSWD,
1754 bv, NULL, NULL, &retoid,
1755 &retdata);
1756 } else {
1757 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1758 pdb_get_plaintext_passwd(newpwd));
1760 if (rc != LDAP_SUCCESS) {
1761 char *ld_error = NULL;
1763 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1764 DEBUG(3, ("Could not set userPassword "
1765 "attribute due to an objectClass "
1766 "violation -- ignoring\n"));
1767 ber_bvfree(bv);
1768 return NT_STATUS_OK;
1771 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1772 &ld_error);
1773 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1774 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1775 SAFE_FREE(ld_error);
1776 ber_bvfree(bv);
1777 #if defined(LDAP_CONSTRAINT_VIOLATION)
1778 if (rc == LDAP_CONSTRAINT_VIOLATION)
1779 return NT_STATUS_PASSWORD_RESTRICTION;
1780 #endif
1781 return NT_STATUS_UNSUCCESSFUL;
1782 } else {
1783 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1784 #ifdef DEBUG_PASSWORD
1785 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1786 #endif
1787 if (retdata)
1788 ber_bvfree(retdata);
1789 if (retoid)
1790 ldap_memfree(retoid);
1792 ber_bvfree(bv);
1794 return NT_STATUS_OK;
1797 /**********************************************************************
1798 Delete entry from LDAP for username.
1799 *********************************************************************/
1801 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1802 struct samu * sam_acct)
1804 struct ldapsam_privates *priv =
1805 (struct ldapsam_privates *)my_methods->private_data;
1806 const char *sname;
1807 int rc;
1808 LDAPMessage *msg, *entry;
1809 NTSTATUS result = NT_STATUS_NO_MEMORY;
1810 const char **attr_list;
1811 TALLOC_CTX *mem_ctx;
1813 if (!sam_acct) {
1814 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1815 return NT_STATUS_INVALID_PARAMETER;
1818 sname = pdb_get_username(sam_acct);
1820 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1821 "LDAP.\n", sname));
1823 mem_ctx = talloc_new(NULL);
1824 if (mem_ctx == NULL) {
1825 DEBUG(0, ("talloc_new failed\n"));
1826 goto done;
1829 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1830 if (attr_list == NULL) {
1831 goto done;
1834 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1836 if ((rc != LDAP_SUCCESS) ||
1837 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1838 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1839 DEBUG(5, ("Could not find user %s\n", sname));
1840 result = NT_STATUS_NO_SUCH_USER;
1841 goto done;
1844 rc = ldapsam_delete_entry(
1845 priv, mem_ctx, entry,
1846 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1847 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1848 attr_list);
1850 result = (rc == LDAP_SUCCESS) ?
1851 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1853 done:
1854 TALLOC_FREE(mem_ctx);
1855 return result;
1858 /**********************************************************************
1859 Helper function to determine for update_sam_account whether
1860 we need LDAP modification.
1861 *********************************************************************/
1863 static bool element_is_changed(const struct samu *sampass,
1864 enum pdb_elements element)
1866 return IS_SAM_CHANGED(sampass, element);
1869 /**********************************************************************
1870 Update struct samu.
1871 *********************************************************************/
1873 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1875 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1876 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1877 int rc = 0;
1878 char *dn;
1879 LDAPMessage *result = NULL;
1880 LDAPMessage *entry = NULL;
1881 LDAPMod **mods = NULL;
1882 const char **attr_list;
1884 result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1885 if (!result) {
1886 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1887 if (pdb_get_username(newpwd) == NULL) {
1888 return NT_STATUS_INVALID_PARAMETER;
1890 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1891 TALLOC_FREE( attr_list );
1892 if (rc != LDAP_SUCCESS) {
1893 return NT_STATUS_UNSUCCESSFUL;
1895 pdb_set_backend_private_data(newpwd, result, NULL,
1896 my_methods, PDB_CHANGED);
1897 talloc_autofree_ldapmsg(newpwd, result);
1900 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1901 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1902 return NT_STATUS_UNSUCCESSFUL;
1905 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1906 dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1907 if (!dn) {
1908 return NT_STATUS_UNSUCCESSFUL;
1911 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1913 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1914 element_is_changed)) {
1915 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1916 SAFE_FREE(dn);
1917 if (mods != NULL)
1918 ldap_mods_free(mods,True);
1919 return NT_STATUS_UNSUCCESSFUL;
1922 if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1923 && (mods == NULL)) {
1924 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1925 pdb_get_username(newpwd)));
1926 SAFE_FREE(dn);
1927 return NT_STATUS_OK;
1930 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1932 if (mods != NULL) {
1933 ldap_mods_free(mods,True);
1936 SAFE_FREE(dn);
1939 * We need to set the backend private data to NULL here. For example
1940 * setuserinfo level 25 does a pdb_update_sam_account twice on the
1941 * same one, and with the explicit delete / add logic for attribute
1942 * values the second time we would use the wrong "old" value which
1943 * does not exist in LDAP anymore. Thus the LDAP server would refuse
1944 * the update.
1945 * The existing LDAPMessage is still being auto-freed by the
1946 * destructor.
1948 pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1949 PDB_CHANGED);
1951 if (!NT_STATUS_IS_OK(ret)) {
1952 return ret;
1955 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1956 pdb_get_username(newpwd)));
1957 return NT_STATUS_OK;
1960 /***************************************************************************
1961 Renames a struct samu
1962 - The "rename user script" has full responsibility for changing everything
1963 ***************************************************************************/
1965 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1966 struct samu *old_acct,
1967 const char *newname)
1969 const char *oldname;
1970 int rc;
1971 char *rename_script = NULL;
1972 fstring oldname_lower, newname_lower;
1974 if (!old_acct) {
1975 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1976 return NT_STATUS_INVALID_PARAMETER;
1978 if (!newname) {
1979 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1980 return NT_STATUS_INVALID_PARAMETER;
1983 oldname = pdb_get_username(old_acct);
1985 /* rename the posix user */
1986 rename_script = SMB_STRDUP(lp_renameuser_script());
1987 if (rename_script == NULL) {
1988 return NT_STATUS_NO_MEMORY;
1991 if (!(*rename_script)) {
1992 SAFE_FREE(rename_script);
1993 return NT_STATUS_ACCESS_DENIED;
1996 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
1997 oldname, newname));
1999 /* We have to allow the account name to end with a '$'.
2000 Also, follow the semantics in _samr_create_user() and lower case the
2001 posix name but preserve the case in passdb */
2003 fstrcpy( oldname_lower, oldname );
2004 strlower_m( oldname_lower );
2005 fstrcpy( newname_lower, newname );
2006 strlower_m( newname_lower );
2007 rename_script = realloc_string_sub2(rename_script,
2008 "%unew",
2009 newname_lower,
2010 true,
2011 true);
2012 if (rename_script) {
2013 return NT_STATUS_NO_MEMORY;
2015 rename_script = realloc_string_sub2(rename_script,
2016 "%uold",
2017 oldname_lower,
2018 true,
2019 true);
2020 rc = smbrun(rename_script, NULL);
2022 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2023 rename_script, rc));
2025 SAFE_FREE(rename_script);
2027 if (rc == 0) {
2028 smb_nscd_flush_user_cache();
2031 if (rc)
2032 return NT_STATUS_UNSUCCESSFUL;
2034 return NT_STATUS_OK;
2037 /**********************************************************************
2038 Helper function to determine for update_sam_account whether
2039 we need LDAP modification.
2040 *********************************************************************/
2042 static bool element_is_set_or_changed(const struct samu *sampass,
2043 enum pdb_elements element)
2045 return (IS_SAM_SET(sampass, element) ||
2046 IS_SAM_CHANGED(sampass, element));
2049 /**********************************************************************
2050 Add struct samu to LDAP.
2051 *********************************************************************/
2053 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2055 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2056 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2057 int rc;
2058 LDAPMessage *result = NULL;
2059 LDAPMessage *entry = NULL;
2060 LDAPMod **mods = NULL;
2061 int ldap_op = LDAP_MOD_REPLACE;
2062 uint32 num_result;
2063 const char **attr_list;
2064 char *escape_user = NULL;
2065 const char *username = pdb_get_username(newpwd);
2066 const DOM_SID *sid = pdb_get_user_sid(newpwd);
2067 char *filter = NULL;
2068 char *dn = NULL;
2069 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2070 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2072 if (!ctx) {
2073 return NT_STATUS_NO_MEMORY;
2076 if (!username || !*username) {
2077 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2078 status = NT_STATUS_INVALID_PARAMETER;
2079 goto fn_exit;
2082 /* free this list after the second search or in case we exit on failure */
2083 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2085 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2087 if (rc != LDAP_SUCCESS) {
2088 goto fn_exit;
2091 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2092 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2093 username));
2094 goto fn_exit;
2096 ldap_msgfree(result);
2097 result = NULL;
2099 if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
2100 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2101 sid, &result);
2102 if (rc == LDAP_SUCCESS) {
2103 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2104 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2105 "already in the base, with samba "
2106 "attributes\n", sid_string_dbg(sid)));
2107 goto fn_exit;
2109 ldap_msgfree(result);
2110 result = NULL;
2114 /* does the entry already exist but without a samba attributes?
2115 we need to return the samba attributes here */
2117 escape_user = escape_ldap_string_alloc( username );
2118 filter = talloc_strdup(attr_list, "(uid=%u)");
2119 if (!filter) {
2120 status = NT_STATUS_NO_MEMORY;
2121 goto fn_exit;
2123 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2124 if (!filter) {
2125 status = NT_STATUS_NO_MEMORY;
2126 goto fn_exit;
2128 SAFE_FREE(escape_user);
2130 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2131 filter, attr_list, &result);
2132 if ( rc != LDAP_SUCCESS ) {
2133 goto fn_exit;
2136 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2138 if (num_result > 1) {
2139 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2140 goto fn_exit;
2143 /* Check if we need to update an existing entry */
2144 if (num_result == 1) {
2145 char *tmp;
2147 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2148 ldap_op = LDAP_MOD_REPLACE;
2149 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2150 tmp = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2151 if (!tmp) {
2152 goto fn_exit;
2154 dn = talloc_asprintf(ctx, "%s", tmp);
2155 SAFE_FREE(tmp);
2156 if (!dn) {
2157 status = NT_STATUS_NO_MEMORY;
2158 goto fn_exit;
2161 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2163 /* There might be a SID for this account already - say an idmap entry */
2165 filter = talloc_asprintf(ctx,
2166 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2167 get_userattr_key2string(ldap_state->schema_ver,
2168 LDAP_ATTR_USER_SID),
2169 sid_string_talloc(ctx, sid),
2170 LDAP_OBJ_IDMAP_ENTRY,
2171 LDAP_OBJ_SID_ENTRY);
2172 if (!filter) {
2173 status = NT_STATUS_NO_MEMORY;
2174 goto fn_exit;
2177 /* free old result before doing a new search */
2178 if (result != NULL) {
2179 ldap_msgfree(result);
2180 result = NULL;
2182 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2183 filter, attr_list, &result);
2185 if ( rc != LDAP_SUCCESS ) {
2186 goto fn_exit;
2189 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2191 if (num_result > 1) {
2192 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2193 goto fn_exit;
2196 /* Check if we need to update an existing entry */
2197 if (num_result == 1) {
2198 char *tmp;
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 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2204 if (!tmp) {
2205 goto fn_exit;
2207 dn = talloc_asprintf(ctx, "%s", tmp);
2208 SAFE_FREE(tmp);
2209 if (!dn) {
2210 status = NT_STATUS_NO_MEMORY;
2211 goto fn_exit;
2216 if (num_result == 0) {
2217 char *escape_username;
2218 /* Check if we need to add an entry */
2219 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2220 ldap_op = LDAP_MOD_ADD;
2222 escape_username = escape_rdn_val_string_alloc(username);
2223 if (!escape_username) {
2224 status = NT_STATUS_NO_MEMORY;
2225 goto fn_exit;
2228 if (username[strlen(username)-1] == '$') {
2229 dn = talloc_asprintf(ctx,
2230 "uid=%s,%s",
2231 escape_username,
2232 lp_ldap_machine_suffix());
2233 } else {
2234 dn = talloc_asprintf(ctx,
2235 "uid=%s,%s",
2236 escape_username,
2237 lp_ldap_user_suffix());
2240 SAFE_FREE(escape_username);
2241 if (!dn) {
2242 status = NT_STATUS_NO_MEMORY;
2243 goto fn_exit;
2247 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2248 element_is_set_or_changed)) {
2249 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2250 if (mods != NULL) {
2251 ldap_mods_free(mods, true);
2253 goto fn_exit;
2256 if (mods == NULL) {
2257 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2258 goto fn_exit;
2260 switch ( ldap_state->schema_ver ) {
2261 case SCHEMAVER_SAMBAACCOUNT:
2262 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2263 break;
2264 case SCHEMAVER_SAMBASAMACCOUNT:
2265 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2266 break;
2267 default:
2268 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2269 break;
2272 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2273 if (!NT_STATUS_IS_OK(ret)) {
2274 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2275 pdb_get_username(newpwd),dn));
2276 ldap_mods_free(mods, true);
2277 goto fn_exit;
2280 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2281 ldap_mods_free(mods, true);
2283 status = NT_STATUS_OK;
2285 fn_exit:
2287 TALLOC_FREE(ctx);
2288 SAFE_FREE(escape_user);
2289 if (result) {
2290 ldap_msgfree(result);
2292 return status;
2295 /**********************************************************************
2296 *********************************************************************/
2298 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2299 const char *filter,
2300 LDAPMessage ** result)
2302 int scope = LDAP_SCOPE_SUBTREE;
2303 int rc;
2304 const char **attr_list;
2306 attr_list = get_attr_list(NULL, groupmap_attr_list);
2307 rc = smbldap_search(ldap_state->smbldap_state,
2308 lp_ldap_group_suffix (), scope,
2309 filter, attr_list, 0, result);
2310 TALLOC_FREE(attr_list);
2312 return rc;
2315 /**********************************************************************
2316 *********************************************************************/
2318 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2319 GROUP_MAP *map, LDAPMessage *entry)
2321 char *temp = NULL;
2322 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2324 if (ldap_state == NULL || map == NULL || entry == NULL ||
2325 ldap_state->smbldap_state->ldap_struct == NULL) {
2326 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2327 TALLOC_FREE(ctx);
2328 return false;
2331 temp = smbldap_talloc_single_attribute(
2332 ldap_state->smbldap_state->ldap_struct,
2333 entry,
2334 get_attr_key2string(groupmap_attr_list,
2335 LDAP_ATTR_GIDNUMBER),
2336 ctx);
2337 if (!temp) {
2338 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2339 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2340 TALLOC_FREE(ctx);
2341 return false;
2343 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2345 map->gid = (gid_t)atol(temp);
2347 TALLOC_FREE(temp);
2348 temp = smbldap_talloc_single_attribute(
2349 ldap_state->smbldap_state->ldap_struct,
2350 entry,
2351 get_attr_key2string(groupmap_attr_list,
2352 LDAP_ATTR_GROUP_SID),
2353 ctx);
2354 if (!temp) {
2355 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2356 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2357 TALLOC_FREE(ctx);
2358 return false;
2361 if (!string_to_sid(&map->sid, temp)) {
2362 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2363 TALLOC_FREE(ctx);
2364 return false;
2367 TALLOC_FREE(temp);
2368 temp = smbldap_talloc_single_attribute(
2369 ldap_state->smbldap_state->ldap_struct,
2370 entry,
2371 get_attr_key2string(groupmap_attr_list,
2372 LDAP_ATTR_GROUP_TYPE),
2373 ctx);
2374 if (!temp) {
2375 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2376 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2377 TALLOC_FREE(ctx);
2378 return false;
2380 map->sid_name_use = (enum lsa_SidType)atol(temp);
2382 if ((map->sid_name_use < SID_NAME_USER) ||
2383 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2384 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2385 TALLOC_FREE(ctx);
2386 return false;
2389 TALLOC_FREE(temp);
2390 temp = smbldap_talloc_single_attribute(
2391 ldap_state->smbldap_state->ldap_struct,
2392 entry,
2393 get_attr_key2string(groupmap_attr_list,
2394 LDAP_ATTR_DISPLAY_NAME),
2395 ctx);
2396 if (!temp) {
2397 temp = smbldap_talloc_single_attribute(
2398 ldap_state->smbldap_state->ldap_struct,
2399 entry,
2400 get_attr_key2string(groupmap_attr_list,
2401 LDAP_ATTR_CN),
2402 ctx);
2403 if (!temp) {
2404 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2405 for gidNumber(%lu)\n",(unsigned long)map->gid));
2406 TALLOC_FREE(ctx);
2407 return false;
2410 fstrcpy(map->nt_name, temp);
2412 TALLOC_FREE(temp);
2413 temp = smbldap_talloc_single_attribute(
2414 ldap_state->smbldap_state->ldap_struct,
2415 entry,
2416 get_attr_key2string(groupmap_attr_list,
2417 LDAP_ATTR_DESC),
2418 ctx);
2419 if (!temp) {
2420 temp = talloc_strdup(ctx, "");
2421 if (!temp) {
2422 TALLOC_FREE(ctx);
2423 return false;
2426 fstrcpy(map->comment, temp);
2428 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2429 store_gid_sid_cache(&map->sid, map->gid);
2432 TALLOC_FREE(ctx);
2433 return true;
2436 /**********************************************************************
2437 *********************************************************************/
2439 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2440 const char *filter,
2441 GROUP_MAP *map)
2443 struct ldapsam_privates *ldap_state =
2444 (struct ldapsam_privates *)methods->private_data;
2445 LDAPMessage *result = NULL;
2446 LDAPMessage *entry = NULL;
2447 int count;
2449 if (ldapsam_search_one_group(ldap_state, filter, &result)
2450 != LDAP_SUCCESS) {
2451 return NT_STATUS_NO_SUCH_GROUP;
2454 count = ldap_count_entries(priv2ld(ldap_state), result);
2456 if (count < 1) {
2457 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2458 "%s\n", filter));
2459 ldap_msgfree(result);
2460 return NT_STATUS_NO_SUCH_GROUP;
2463 if (count > 1) {
2464 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2465 "count=%d\n", filter, count));
2466 ldap_msgfree(result);
2467 return NT_STATUS_NO_SUCH_GROUP;
2470 entry = ldap_first_entry(priv2ld(ldap_state), result);
2472 if (!entry) {
2473 ldap_msgfree(result);
2474 return NT_STATUS_UNSUCCESSFUL;
2477 if (!init_group_from_ldap(ldap_state, map, entry)) {
2478 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2479 "group filter %s\n", filter));
2480 ldap_msgfree(result);
2481 return NT_STATUS_NO_SUCH_GROUP;
2484 ldap_msgfree(result);
2485 return NT_STATUS_OK;
2488 /**********************************************************************
2489 *********************************************************************/
2491 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2492 DOM_SID sid)
2494 char *filter = NULL;
2495 NTSTATUS status;
2496 fstring tmp;
2498 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2499 LDAP_OBJ_GROUPMAP,
2500 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2501 sid_to_fstring(tmp, &sid)) < 0) {
2502 return NT_STATUS_NO_MEMORY;
2505 status = ldapsam_getgroup(methods, filter, map);
2506 SAFE_FREE(filter);
2507 return status;
2510 /**********************************************************************
2511 *********************************************************************/
2513 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2514 gid_t gid)
2516 char *filter = NULL;
2517 NTSTATUS status;
2519 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2520 LDAP_OBJ_GROUPMAP,
2521 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2522 (unsigned long)gid) < 0) {
2523 return NT_STATUS_NO_MEMORY;
2526 status = ldapsam_getgroup(methods, filter, map);
2527 SAFE_FREE(filter);
2528 return status;
2531 /**********************************************************************
2532 *********************************************************************/
2534 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2535 const char *name)
2537 char *filter = NULL;
2538 char *escape_name = escape_ldap_string_alloc(name);
2539 NTSTATUS status;
2541 if (!escape_name) {
2542 return NT_STATUS_NO_MEMORY;
2545 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2546 LDAP_OBJ_GROUPMAP,
2547 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2548 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2549 escape_name) < 0) {
2550 SAFE_FREE(escape_name);
2551 return NT_STATUS_NO_MEMORY;
2554 SAFE_FREE(escape_name);
2555 status = ldapsam_getgroup(methods, filter, map);
2556 SAFE_FREE(filter);
2557 return status;
2560 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2561 LDAPMessage *entry,
2562 const DOM_SID *domain_sid,
2563 uint32 *rid)
2565 fstring str;
2566 DOM_SID sid;
2568 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2569 str, sizeof(str)-1)) {
2570 DEBUG(10, ("Could not find sambaSID attribute\n"));
2571 return False;
2574 if (!string_to_sid(&sid, str)) {
2575 DEBUG(10, ("Could not convert string %s to sid\n", str));
2576 return False;
2579 if (sid_compare_domain(&sid, domain_sid) != 0) {
2580 DEBUG(10, ("SID %s is not in expected domain %s\n",
2581 str, sid_string_dbg(domain_sid)));
2582 return False;
2585 if (!sid_peek_rid(&sid, rid)) {
2586 DEBUG(10, ("Could not peek into RID\n"));
2587 return False;
2590 return True;
2593 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2594 TALLOC_CTX *mem_ctx,
2595 const DOM_SID *group,
2596 uint32 **pp_member_rids,
2597 size_t *p_num_members)
2599 struct ldapsam_privates *ldap_state =
2600 (struct ldapsam_privates *)methods->private_data;
2601 struct smbldap_state *conn = ldap_state->smbldap_state;
2602 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2603 const char *sid_attrs[] = { "sambaSID", NULL };
2604 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2605 LDAPMessage *result = NULL;
2606 LDAPMessage *entry;
2607 char *filter;
2608 char **values = NULL;
2609 char **memberuid;
2610 char *gidstr;
2611 int rc, count;
2613 *pp_member_rids = NULL;
2614 *p_num_members = 0;
2616 filter = talloc_asprintf(mem_ctx,
2617 "(&(objectClass=%s)"
2618 "(objectClass=%s)"
2619 "(sambaSID=%s))",
2620 LDAP_OBJ_POSIXGROUP,
2621 LDAP_OBJ_GROUPMAP,
2622 sid_string_talloc(mem_ctx, group));
2623 if (filter == NULL) {
2624 ret = NT_STATUS_NO_MEMORY;
2625 goto done;
2628 rc = smbldap_search(conn, lp_ldap_group_suffix(),
2629 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2630 &result);
2632 if (rc != LDAP_SUCCESS)
2633 goto done;
2635 talloc_autofree_ldapmsg(mem_ctx, result);
2637 count = ldap_count_entries(conn->ldap_struct, result);
2639 if (count > 1) {
2640 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2641 sid_string_dbg(group)));
2642 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2643 goto done;
2646 if (count == 0) {
2647 ret = NT_STATUS_NO_SUCH_GROUP;
2648 goto done;
2651 entry = ldap_first_entry(conn->ldap_struct, result);
2652 if (entry == NULL)
2653 goto done;
2655 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2656 if (!gidstr) {
2657 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2658 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2659 goto done;
2662 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2664 if (values) {
2666 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2667 if (filter == NULL) {
2668 ret = NT_STATUS_NO_MEMORY;
2669 goto done;
2672 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2673 char *escape_memberuid;
2675 escape_memberuid = escape_ldap_string_alloc(*memberuid);
2676 if (escape_memberuid == NULL) {
2677 ret = NT_STATUS_NO_MEMORY;
2678 goto done;
2681 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2682 if (filter == NULL) {
2683 SAFE_FREE(escape_memberuid);
2684 ret = NT_STATUS_NO_MEMORY;
2685 goto done;
2688 SAFE_FREE(escape_memberuid);
2691 filter = talloc_asprintf_append_buffer(filter, "))");
2692 if (filter == NULL) {
2693 ret = NT_STATUS_NO_MEMORY;
2694 goto done;
2697 rc = smbldap_search(conn, lp_ldap_suffix(),
2698 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2699 &result);
2701 if (rc != LDAP_SUCCESS)
2702 goto done;
2704 count = ldap_count_entries(conn->ldap_struct, result);
2705 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2707 talloc_autofree_ldapmsg(mem_ctx, result);
2709 for (entry = ldap_first_entry(conn->ldap_struct, result);
2710 entry != NULL;
2711 entry = ldap_next_entry(conn->ldap_struct, entry))
2713 char *sidstr;
2714 DOM_SID sid;
2715 uint32 rid;
2717 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2718 entry, "sambaSID",
2719 mem_ctx);
2720 if (!sidstr) {
2721 DEBUG(0, ("Severe DB error, sambaSamAccount can't miss "
2722 "the sambaSID attribute\n"));
2723 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2724 goto done;
2727 if (!string_to_sid(&sid, sidstr))
2728 goto done;
2730 if (!sid_check_is_in_our_domain(&sid)) {
2731 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2732 "in our domain\n"));
2733 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2734 goto done;
2737 sid_peek_rid(&sid, &rid);
2739 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2740 p_num_members)) {
2741 ret = NT_STATUS_NO_MEMORY;
2742 goto done;
2747 filter = talloc_asprintf(mem_ctx,
2748 "(&(objectClass=%s)"
2749 "(gidNumber=%s))",
2750 LDAP_OBJ_SAMBASAMACCOUNT,
2751 gidstr);
2753 rc = smbldap_search(conn, lp_ldap_suffix(),
2754 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2755 &result);
2757 if (rc != LDAP_SUCCESS)
2758 goto done;
2760 talloc_autofree_ldapmsg(mem_ctx, result);
2762 for (entry = ldap_first_entry(conn->ldap_struct, result);
2763 entry != NULL;
2764 entry = ldap_next_entry(conn->ldap_struct, entry))
2766 uint32 rid;
2768 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2769 entry,
2770 get_global_sam_sid(),
2771 &rid)) {
2772 DEBUG(0, ("Severe DB error, sambaSamAccount can't miss "
2773 "the sambaSID attribute\n"));
2774 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2775 goto done;
2778 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2779 p_num_members)) {
2780 ret = NT_STATUS_NO_MEMORY;
2781 goto done;
2785 ret = NT_STATUS_OK;
2787 done:
2789 if (values)
2790 ldap_value_free(values);
2792 return ret;
2795 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2796 TALLOC_CTX *mem_ctx,
2797 struct samu *user,
2798 DOM_SID **pp_sids,
2799 gid_t **pp_gids,
2800 size_t *p_num_groups)
2802 struct ldapsam_privates *ldap_state =
2803 (struct ldapsam_privates *)methods->private_data;
2804 struct smbldap_state *conn = ldap_state->smbldap_state;
2805 char *filter;
2806 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2807 char *escape_name;
2808 int rc, count;
2809 LDAPMessage *result = NULL;
2810 LDAPMessage *entry;
2811 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2812 size_t num_sids, num_gids;
2813 char *gidstr;
2814 gid_t primary_gid = -1;
2816 *pp_sids = NULL;
2817 num_sids = 0;
2819 if (pdb_get_username(user) == NULL) {
2820 return NT_STATUS_INVALID_PARAMETER;
2823 escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2824 if (escape_name == NULL)
2825 return NT_STATUS_NO_MEMORY;
2827 /* retrieve the users primary gid */
2828 filter = talloc_asprintf(mem_ctx,
2829 "(&(objectClass=%s)(uid=%s))",
2830 LDAP_OBJ_SAMBASAMACCOUNT,
2831 escape_name);
2832 if (filter == NULL) {
2833 ret = NT_STATUS_NO_MEMORY;
2834 goto done;
2837 rc = smbldap_search(conn, lp_ldap_suffix(),
2838 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2840 if (rc != LDAP_SUCCESS)
2841 goto done;
2843 talloc_autofree_ldapmsg(mem_ctx, result);
2845 count = ldap_count_entries(priv2ld(ldap_state), result);
2847 switch (count) {
2848 case 0:
2849 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2850 ret = NT_STATUS_NO_SUCH_USER;
2851 goto done;
2852 case 1:
2853 entry = ldap_first_entry(priv2ld(ldap_state), result);
2855 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2856 if (!gidstr) {
2857 DEBUG (1, ("Unable to find the member's gid!\n"));
2858 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2859 goto done;
2861 primary_gid = strtoul(gidstr, NULL, 10);
2862 break;
2863 default:
2864 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2865 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2866 goto done;
2869 filter = talloc_asprintf(mem_ctx,
2870 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%d)))",
2871 LDAP_OBJ_POSIXGROUP, escape_name, primary_gid);
2872 if (filter == NULL) {
2873 ret = NT_STATUS_NO_MEMORY;
2874 goto done;
2877 rc = smbldap_search(conn, lp_ldap_group_suffix(),
2878 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2880 if (rc != LDAP_SUCCESS)
2881 goto done;
2883 talloc_autofree_ldapmsg(mem_ctx, result);
2885 num_gids = 0;
2886 *pp_gids = NULL;
2888 num_sids = 0;
2889 *pp_sids = NULL;
2891 /* We need to add the primary group as the first gid/sid */
2893 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2894 ret = NT_STATUS_NO_MEMORY;
2895 goto done;
2898 /* This sid will be replaced later */
2900 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2901 &num_sids);
2902 if (!NT_STATUS_IS_OK(ret)) {
2903 goto done;
2906 for (entry = ldap_first_entry(conn->ldap_struct, result);
2907 entry != NULL;
2908 entry = ldap_next_entry(conn->ldap_struct, entry))
2910 fstring str;
2911 DOM_SID sid;
2912 gid_t gid;
2913 char *end;
2915 if (!smbldap_get_single_attribute(conn->ldap_struct,
2916 entry, "sambaSID",
2917 str, sizeof(str)-1))
2918 continue;
2920 if (!string_to_sid(&sid, str))
2921 goto done;
2923 if (!smbldap_get_single_attribute(conn->ldap_struct,
2924 entry, "gidNumber",
2925 str, sizeof(str)-1))
2926 continue;
2928 gid = strtoul(str, &end, 10);
2930 if (PTR_DIFF(end, str) != strlen(str))
2931 goto done;
2933 if (gid == primary_gid) {
2934 sid_copy(&(*pp_sids)[0], &sid);
2935 } else {
2936 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2937 &num_gids)) {
2938 ret = NT_STATUS_NO_MEMORY;
2939 goto done;
2941 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2942 &num_sids);
2943 if (!NT_STATUS_IS_OK(ret)) {
2944 goto done;
2949 if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2950 DEBUG(3, ("primary group of [%s] not found\n",
2951 pdb_get_username(user)));
2952 goto done;
2955 *p_num_groups = num_sids;
2957 ret = NT_STATUS_OK;
2959 done:
2961 SAFE_FREE(escape_name);
2962 return ret;
2965 /**********************************************************************
2966 * Augment a posixGroup object with a sambaGroupMapping domgroup
2967 *********************************************************************/
2969 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2970 struct ldapsam_privates *ldap_state,
2971 GROUP_MAP *map)
2973 const char *filter, *dn;
2974 LDAPMessage *msg, *entry;
2975 LDAPMod **mods;
2976 int rc;
2978 filter = talloc_asprintf(mem_ctx,
2979 "(&(objectClass=posixGroup)(gidNumber=%u))",
2980 map->gid);
2981 if (filter == NULL) {
2982 return NT_STATUS_NO_MEMORY;
2985 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2986 get_attr_list(mem_ctx, groupmap_attr_list),
2987 &msg);
2988 talloc_autofree_ldapmsg(mem_ctx, msg);
2990 if ((rc != LDAP_SUCCESS) ||
2991 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2992 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2993 return NT_STATUS_NO_SUCH_GROUP;
2996 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2997 if (dn == NULL) {
2998 return NT_STATUS_NO_MEMORY;
3001 mods = NULL;
3002 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3003 "sambaGroupMapping");
3004 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3005 sid_string_talloc(mem_ctx, &map->sid));
3006 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3007 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3008 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3009 map->nt_name);
3010 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3011 map->comment);
3012 talloc_autofree_ldapmod(mem_ctx, mods);
3014 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3015 if (rc != LDAP_SUCCESS) {
3016 return NT_STATUS_ACCESS_DENIED;
3019 return NT_STATUS_OK;
3022 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3023 GROUP_MAP *map)
3025 struct ldapsam_privates *ldap_state =
3026 (struct ldapsam_privates *)methods->private_data;
3027 LDAPMessage *msg = NULL;
3028 LDAPMod **mods = NULL;
3029 const char *attrs[] = { NULL };
3030 char *filter;
3032 char *dn;
3033 TALLOC_CTX *mem_ctx;
3034 NTSTATUS result;
3036 DOM_SID sid;
3038 int rc;
3040 mem_ctx = talloc_new(NULL);
3041 if (mem_ctx == NULL) {
3042 DEBUG(0, ("talloc_new failed\n"));
3043 return NT_STATUS_NO_MEMORY;
3046 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3047 sid_string_talloc(mem_ctx, &map->sid));
3048 if (filter == NULL) {
3049 result = NT_STATUS_NO_MEMORY;
3050 goto done;
3053 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3054 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3055 talloc_autofree_ldapmsg(mem_ctx, msg);
3057 if ((rc == LDAP_SUCCESS) &&
3058 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3060 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3061 "group mapping entry\n", sid_string_dbg(&map->sid)));
3062 result = NT_STATUS_GROUP_EXISTS;
3063 goto done;
3066 switch (map->sid_name_use) {
3068 case SID_NAME_DOM_GRP:
3069 /* To map a domain group we need to have a posix group
3070 to attach to. */
3071 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3072 goto done;
3073 break;
3075 case SID_NAME_ALIAS:
3076 if (!sid_check_is_in_our_domain(&map->sid)
3077 && !sid_check_is_in_builtin(&map->sid) )
3079 DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3080 sid_string_dbg(&map->sid)));
3081 result = NT_STATUS_INVALID_PARAMETER;
3082 goto done;
3084 break;
3086 default:
3087 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3088 sid_type_lookup(map->sid_name_use)));
3089 result = NT_STATUS_INVALID_PARAMETER;
3090 goto done;
3093 /* Domain groups have been mapped in a separate routine, we have to
3094 * create an alias now */
3096 if (map->gid == -1) {
3097 DEBUG(10, ("Refusing to map gid==-1\n"));
3098 result = NT_STATUS_INVALID_PARAMETER;
3099 goto done;
3102 if (pdb_gid_to_sid(map->gid, &sid)) {
3103 DEBUG(3, ("Gid %d is already mapped to SID %s, refusing to "
3104 "add\n", map->gid, sid_string_dbg(&sid)));
3105 result = NT_STATUS_GROUP_EXISTS;
3106 goto done;
3109 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3110 * the best we can get out of LDAP. */
3112 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3113 sid_string_talloc(mem_ctx, &map->sid),
3114 lp_ldap_group_suffix());
3115 if (dn == NULL) {
3116 result = NT_STATUS_NO_MEMORY;
3117 goto done;
3120 mods = NULL;
3122 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3123 "sambaSidEntry");
3124 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3125 "sambaGroupMapping");
3127 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3128 sid_string_talloc(mem_ctx, &map->sid));
3129 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3130 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3131 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3132 map->nt_name);
3133 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3134 map->comment);
3135 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3136 talloc_asprintf(mem_ctx, "%u", map->gid));
3137 talloc_autofree_ldapmod(mem_ctx, mods);
3139 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3141 result = (rc == LDAP_SUCCESS) ?
3142 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3144 done:
3145 TALLOC_FREE(mem_ctx);
3146 return result;
3149 /**********************************************************************
3150 * Update a group mapping entry. We're quite strict about what can be changed:
3151 * Only the description and displayname may be changed. It simply does not
3152 * make any sense to change the SID, gid or the type in a mapping.
3153 *********************************************************************/
3155 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3156 GROUP_MAP *map)
3158 struct ldapsam_privates *ldap_state =
3159 (struct ldapsam_privates *)methods->private_data;
3160 int rc;
3161 const char *filter, *dn;
3162 LDAPMessage *msg = NULL;
3163 LDAPMessage *entry = NULL;
3164 LDAPMod **mods = NULL;
3165 TALLOC_CTX *mem_ctx;
3166 NTSTATUS result;
3168 mem_ctx = talloc_new(NULL);
3169 if (mem_ctx == NULL) {
3170 DEBUG(0, ("talloc_new failed\n"));
3171 return NT_STATUS_NO_MEMORY;
3174 /* Make 100% sure that sid, gid and type are not changed by looking up
3175 * exactly the values we're given in LDAP. */
3177 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3178 "(sambaSid=%s)(gidNumber=%u)"
3179 "(sambaGroupType=%d))",
3180 LDAP_OBJ_GROUPMAP,
3181 sid_string_talloc(mem_ctx, &map->sid),
3182 map->gid, map->sid_name_use);
3183 if (filter == NULL) {
3184 result = NT_STATUS_NO_MEMORY;
3185 goto done;
3188 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3189 get_attr_list(mem_ctx, groupmap_attr_list),
3190 &msg);
3191 talloc_autofree_ldapmsg(mem_ctx, msg);
3193 if ((rc != LDAP_SUCCESS) ||
3194 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3195 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3196 result = NT_STATUS_NO_SUCH_GROUP;
3197 goto done;
3200 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3202 if (dn == NULL) {
3203 result = NT_STATUS_NO_MEMORY;
3204 goto done;
3207 mods = NULL;
3208 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3209 map->nt_name);
3210 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3211 map->comment);
3212 talloc_autofree_ldapmod(mem_ctx, mods);
3214 if (mods == NULL) {
3215 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3216 "nothing to do\n"));
3217 result = NT_STATUS_OK;
3218 goto done;
3221 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3223 if (rc != LDAP_SUCCESS) {
3224 result = NT_STATUS_ACCESS_DENIED;
3225 goto done;
3228 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3229 "group %lu in LDAP\n", (unsigned long)map->gid));
3231 result = NT_STATUS_OK;
3233 done:
3234 TALLOC_FREE(mem_ctx);
3235 return result;
3238 /**********************************************************************
3239 *********************************************************************/
3241 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3242 DOM_SID sid)
3244 struct ldapsam_privates *priv =
3245 (struct ldapsam_privates *)methods->private_data;
3246 LDAPMessage *msg, *entry;
3247 int rc;
3248 NTSTATUS result;
3249 TALLOC_CTX *mem_ctx;
3250 char *filter;
3252 mem_ctx = talloc_new(NULL);
3253 if (mem_ctx == NULL) {
3254 DEBUG(0, ("talloc_new failed\n"));
3255 return NT_STATUS_NO_MEMORY;
3258 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3259 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3260 sid_string_talloc(mem_ctx, &sid));
3261 if (filter == NULL) {
3262 result = NT_STATUS_NO_MEMORY;
3263 goto done;
3265 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3266 get_attr_list(mem_ctx, groupmap_attr_list),
3267 &msg);
3268 talloc_autofree_ldapmsg(mem_ctx, msg);
3270 if ((rc != LDAP_SUCCESS) ||
3271 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3272 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3273 result = NT_STATUS_NO_SUCH_GROUP;
3274 goto done;
3277 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3278 get_attr_list(mem_ctx,
3279 groupmap_attr_list_to_delete));
3281 if ((rc == LDAP_NAMING_VIOLATION) ||
3282 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3283 const char *attrs[] = { "sambaGroupType", "description",
3284 "displayName", "sambaSIDList",
3285 NULL };
3287 /* Second try. Don't delete the sambaSID attribute, this is
3288 for "old" entries that are tacked on a winbind
3289 sambaIdmapEntry. */
3291 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3292 LDAP_OBJ_GROUPMAP, attrs);
3295 if ((rc == LDAP_NAMING_VIOLATION) ||
3296 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3297 const char *attrs[] = { "sambaGroupType", "description",
3298 "displayName", "sambaSIDList",
3299 "gidNumber", NULL };
3301 /* Third try. This is a post-3.0.21 alias (containing only
3302 * sambaSidEntry and sambaGroupMapping classes), we also have
3303 * to delete the gidNumber attribute, only the sambaSidEntry
3304 * remains */
3306 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3307 LDAP_OBJ_GROUPMAP, attrs);
3310 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3312 done:
3313 TALLOC_FREE(mem_ctx);
3314 return result;
3317 /**********************************************************************
3318 *********************************************************************/
3320 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3321 bool update)
3323 struct ldapsam_privates *ldap_state =
3324 (struct ldapsam_privates *)my_methods->private_data;
3325 char *filter = NULL;
3326 int rc;
3327 const char **attr_list;
3329 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3330 if (!filter) {
3331 return NT_STATUS_NO_MEMORY;
3333 attr_list = get_attr_list( NULL, groupmap_attr_list );
3334 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3335 LDAP_SCOPE_SUBTREE, filter,
3336 attr_list, 0, &ldap_state->result);
3337 TALLOC_FREE(attr_list);
3339 if (rc != LDAP_SUCCESS) {
3340 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3341 ldap_err2string(rc)));
3342 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3343 lp_ldap_group_suffix(), filter));
3344 ldap_msgfree(ldap_state->result);
3345 ldap_state->result = NULL;
3346 TALLOC_FREE(filter);
3347 return NT_STATUS_UNSUCCESSFUL;
3350 TALLOC_FREE(filter);
3352 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3353 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3354 ldap_state->result)));
3356 ldap_state->entry =
3357 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3358 ldap_state->result);
3359 ldap_state->index = 0;
3361 return NT_STATUS_OK;
3364 /**********************************************************************
3365 *********************************************************************/
3367 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3369 ldapsam_endsampwent(my_methods);
3372 /**********************************************************************
3373 *********************************************************************/
3375 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3376 GROUP_MAP *map)
3378 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3379 struct ldapsam_privates *ldap_state =
3380 (struct ldapsam_privates *)my_methods->private_data;
3381 bool bret = False;
3383 while (!bret) {
3384 if (!ldap_state->entry)
3385 return ret;
3387 ldap_state->index++;
3388 bret = init_group_from_ldap(ldap_state, map,
3389 ldap_state->entry);
3391 ldap_state->entry =
3392 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3393 ldap_state->entry);
3396 return NT_STATUS_OK;
3399 /**********************************************************************
3400 *********************************************************************/
3402 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3403 const DOM_SID *domsid, enum lsa_SidType sid_name_use,
3404 GROUP_MAP **pp_rmap,
3405 size_t *p_num_entries,
3406 bool unix_only)
3408 GROUP_MAP map;
3409 size_t entries = 0;
3411 *p_num_entries = 0;
3412 *pp_rmap = NULL;
3414 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3415 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3416 "passdb\n"));
3417 return NT_STATUS_ACCESS_DENIED;
3420 while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3421 if (sid_name_use != SID_NAME_UNKNOWN &&
3422 sid_name_use != map.sid_name_use) {
3423 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3424 "not of the requested type\n", map.nt_name));
3425 continue;
3427 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3428 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3429 "non mapped\n", map.nt_name));
3430 continue;
3433 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3434 if (!(*pp_rmap)) {
3435 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3436 "enlarge group map!\n"));
3437 return NT_STATUS_UNSUCCESSFUL;
3440 (*pp_rmap)[entries] = map;
3442 entries += 1;
3445 ldapsam_endsamgrent(methods);
3447 *p_num_entries = entries;
3449 return NT_STATUS_OK;
3452 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3453 const DOM_SID *alias,
3454 const DOM_SID *member,
3455 int modop)
3457 struct ldapsam_privates *ldap_state =
3458 (struct ldapsam_privates *)methods->private_data;
3459 char *dn = NULL;
3460 LDAPMessage *result = NULL;
3461 LDAPMessage *entry = NULL;
3462 int count;
3463 LDAPMod **mods = NULL;
3464 int rc;
3465 enum lsa_SidType type = SID_NAME_USE_NONE;
3466 fstring tmp;
3468 char *filter = NULL;
3470 if (sid_check_is_in_builtin(alias)) {
3471 type = SID_NAME_ALIAS;
3474 if (sid_check_is_in_our_domain(alias)) {
3475 type = SID_NAME_ALIAS;
3478 if (type == SID_NAME_USE_NONE) {
3479 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3480 sid_string_dbg(alias)));
3481 return NT_STATUS_NO_SUCH_ALIAS;
3484 if (asprintf(&filter,
3485 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3486 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3487 type) < 0) {
3488 return NT_STATUS_NO_MEMORY;
3491 if (ldapsam_search_one_group(ldap_state, filter,
3492 &result) != LDAP_SUCCESS) {
3493 SAFE_FREE(filter);
3494 return NT_STATUS_NO_SUCH_ALIAS;
3497 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3498 result);
3500 if (count < 1) {
3501 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3502 ldap_msgfree(result);
3503 SAFE_FREE(filter);
3504 return NT_STATUS_NO_SUCH_ALIAS;
3507 if (count > 1) {
3508 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3509 "filter %s: count=%d\n", filter, count));
3510 ldap_msgfree(result);
3511 SAFE_FREE(filter);
3512 return NT_STATUS_NO_SUCH_ALIAS;
3515 SAFE_FREE(filter);
3517 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3518 result);
3520 if (!entry) {
3521 ldap_msgfree(result);
3522 return NT_STATUS_UNSUCCESSFUL;
3525 dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
3526 if (!dn) {
3527 ldap_msgfree(result);
3528 return NT_STATUS_UNSUCCESSFUL;
3531 smbldap_set_mod(&mods, modop,
3532 get_attr_key2string(groupmap_attr_list,
3533 LDAP_ATTR_SID_LIST),
3534 sid_to_fstring(tmp, member));
3536 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3538 ldap_mods_free(mods, True);
3539 ldap_msgfree(result);
3540 SAFE_FREE(dn);
3542 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3543 return NT_STATUS_MEMBER_IN_ALIAS;
3546 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3547 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3550 if (rc != LDAP_SUCCESS) {
3551 return NT_STATUS_UNSUCCESSFUL;
3554 return NT_STATUS_OK;
3557 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3558 const DOM_SID *alias,
3559 const DOM_SID *member)
3561 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3564 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3565 const DOM_SID *alias,
3566 const DOM_SID *member)
3568 return ldapsam_modify_aliasmem(methods, alias, member,
3569 LDAP_MOD_DELETE);
3572 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3573 const DOM_SID *alias,
3574 DOM_SID **pp_members,
3575 size_t *p_num_members)
3577 struct ldapsam_privates *ldap_state =
3578 (struct ldapsam_privates *)methods->private_data;
3579 LDAPMessage *result = NULL;
3580 LDAPMessage *entry = NULL;
3581 int count;
3582 char **values = NULL;
3583 int i;
3584 char *filter = NULL;
3585 size_t num_members = 0;
3586 enum lsa_SidType type = SID_NAME_USE_NONE;
3587 fstring tmp;
3589 *pp_members = NULL;
3590 *p_num_members = 0;
3592 if (sid_check_is_in_builtin(alias)) {
3593 type = SID_NAME_ALIAS;
3596 if (sid_check_is_in_our_domain(alias)) {
3597 type = SID_NAME_ALIAS;
3600 if (type == SID_NAME_USE_NONE) {
3601 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3602 sid_string_dbg(alias)));
3603 return NT_STATUS_NO_SUCH_ALIAS;
3606 if (asprintf(&filter,
3607 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3608 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3609 type) < 0) {
3610 return NT_STATUS_NO_MEMORY;
3613 if (ldapsam_search_one_group(ldap_state, filter,
3614 &result) != LDAP_SUCCESS) {
3615 SAFE_FREE(filter);
3616 return NT_STATUS_NO_SUCH_ALIAS;
3619 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3620 result);
3622 if (count < 1) {
3623 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3624 ldap_msgfree(result);
3625 SAFE_FREE(filter);
3626 return NT_STATUS_NO_SUCH_ALIAS;
3629 if (count > 1) {
3630 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3631 "filter %s: count=%d\n", filter, count));
3632 ldap_msgfree(result);
3633 SAFE_FREE(filter);
3634 return NT_STATUS_NO_SUCH_ALIAS;
3637 SAFE_FREE(filter);
3639 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3640 result);
3642 if (!entry) {
3643 ldap_msgfree(result);
3644 return NT_STATUS_UNSUCCESSFUL;
3647 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3648 entry,
3649 get_attr_key2string(groupmap_attr_list,
3650 LDAP_ATTR_SID_LIST));
3652 if (values == NULL) {
3653 ldap_msgfree(result);
3654 return NT_STATUS_OK;
3657 count = ldap_count_values(values);
3659 for (i=0; i<count; i++) {
3660 DOM_SID member;
3661 NTSTATUS status;
3663 if (!string_to_sid(&member, values[i]))
3664 continue;
3666 status = add_sid_to_array(NULL, &member, pp_members,
3667 &num_members);
3668 if (!NT_STATUS_IS_OK(status)) {
3669 ldap_value_free(values);
3670 ldap_msgfree(result);
3671 return status;
3675 *p_num_members = num_members;
3676 ldap_value_free(values);
3677 ldap_msgfree(result);
3679 return NT_STATUS_OK;
3682 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3683 TALLOC_CTX *mem_ctx,
3684 const DOM_SID *domain_sid,
3685 const DOM_SID *members,
3686 size_t num_members,
3687 uint32 **pp_alias_rids,
3688 size_t *p_num_alias_rids)
3690 struct ldapsam_privates *ldap_state =
3691 (struct ldapsam_privates *)methods->private_data;
3692 LDAP *ldap_struct;
3694 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3696 LDAPMessage *result = NULL;
3697 LDAPMessage *entry = NULL;
3698 int i;
3699 int rc;
3700 char *filter;
3701 enum lsa_SidType type = SID_NAME_USE_NONE;
3703 if (sid_check_is_builtin(domain_sid)) {
3704 type = SID_NAME_ALIAS;
3707 if (sid_check_is_domain(domain_sid)) {
3708 type = SID_NAME_ALIAS;
3711 if (type == SID_NAME_USE_NONE) {
3712 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3713 sid_string_dbg(domain_sid)));
3714 return NT_STATUS_UNSUCCESSFUL;
3717 filter = talloc_asprintf(mem_ctx,
3718 "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3719 LDAP_OBJ_GROUPMAP, type);
3721 for (i=0; i<num_members; i++)
3722 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3723 filter,
3724 sid_string_talloc(mem_ctx,
3725 &members[i]));
3727 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3729 if (filter == NULL) {
3730 return NT_STATUS_NO_MEMORY;
3733 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3734 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3736 if (rc != LDAP_SUCCESS)
3737 return NT_STATUS_UNSUCCESSFUL;
3739 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3741 for (entry = ldap_first_entry(ldap_struct, result);
3742 entry != NULL;
3743 entry = ldap_next_entry(ldap_struct, entry))
3745 fstring sid_str;
3746 DOM_SID sid;
3747 uint32 rid;
3749 if (!smbldap_get_single_attribute(ldap_struct, entry,
3750 LDAP_ATTRIBUTE_SID,
3751 sid_str,
3752 sizeof(sid_str)-1))
3753 continue;
3755 if (!string_to_sid(&sid, sid_str))
3756 continue;
3758 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3759 continue;
3761 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3762 p_num_alias_rids)) {
3763 ldap_msgfree(result);
3764 return NT_STATUS_NO_MEMORY;
3768 ldap_msgfree(result);
3769 return NT_STATUS_OK;
3772 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3773 int policy_index,
3774 uint32 value)
3776 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3777 int rc;
3778 LDAPMod **mods = NULL;
3779 fstring value_string;
3780 const char *policy_attr = NULL;
3782 struct ldapsam_privates *ldap_state =
3783 (struct ldapsam_privates *)methods->private_data;
3785 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3787 if (!ldap_state->domain_dn) {
3788 return NT_STATUS_INVALID_PARAMETER;
3791 policy_attr = get_account_policy_attr(policy_index);
3792 if (policy_attr == NULL) {
3793 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3794 "policy\n"));
3795 return ntstatus;
3798 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3800 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3802 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3803 mods);
3805 ldap_mods_free(mods, True);
3807 if (rc != LDAP_SUCCESS) {
3808 return ntstatus;
3811 if (!cache_account_policy_set(policy_index, value)) {
3812 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3813 "update local tdb cache\n"));
3814 return ntstatus;
3817 return NT_STATUS_OK;
3820 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3821 int policy_index, uint32 value)
3823 return ldapsam_set_account_policy_in_ldap(methods, policy_index,
3824 value);
3827 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3828 int policy_index,
3829 uint32 *value)
3831 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3832 LDAPMessage *result = NULL;
3833 LDAPMessage *entry = NULL;
3834 int count;
3835 int rc;
3836 char **vals = NULL;
3837 const char *policy_attr = NULL;
3839 struct ldapsam_privates *ldap_state =
3840 (struct ldapsam_privates *)methods->private_data;
3842 const char *attrs[2];
3844 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3846 if (!ldap_state->domain_dn) {
3847 return NT_STATUS_INVALID_PARAMETER;
3850 policy_attr = get_account_policy_attr(policy_index);
3851 if (!policy_attr) {
3852 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3853 "policy index: %d\n", policy_index));
3854 return ntstatus;
3857 attrs[0] = policy_attr;
3858 attrs[1] = NULL;
3860 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3861 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3862 &result);
3864 if (rc != LDAP_SUCCESS) {
3865 return ntstatus;
3868 count = ldap_count_entries(priv2ld(ldap_state), result);
3869 if (count < 1) {
3870 goto out;
3873 entry = ldap_first_entry(priv2ld(ldap_state), result);
3874 if (entry == NULL) {
3875 goto out;
3878 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3879 if (vals == NULL) {
3880 goto out;
3883 *value = (uint32)atol(vals[0]);
3885 ntstatus = NT_STATUS_OK;
3887 out:
3888 if (vals)
3889 ldap_value_free(vals);
3890 ldap_msgfree(result);
3892 return ntstatus;
3895 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3897 - if user hasn't decided to use account policies inside LDAP just reuse the
3898 old tdb values
3900 - if there is a valid cache entry, return that
3901 - if there is an LDAP entry, update cache and return
3902 - otherwise set to default, update cache and return
3904 Guenther
3906 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3907 int policy_index, uint32 *value)
3909 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3911 if (cache_account_policy_get(policy_index, value)) {
3912 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3913 "cache\n"));
3914 return NT_STATUS_OK;
3917 ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index,
3918 value);
3919 if (NT_STATUS_IS_OK(ntstatus)) {
3920 goto update_cache;
3923 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3924 "ldap\n"));
3926 #if 0
3927 /* should we automagically migrate old tdb value here ? */
3928 if (account_policy_get(policy_index, value))
3929 goto update_ldap;
3931 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3932 "default\n", policy_index));
3933 #endif
3935 if (!account_policy_get_default(policy_index, value)) {
3936 return ntstatus;
3939 /* update_ldap: */
3941 ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3942 if (!NT_STATUS_IS_OK(ntstatus)) {
3943 return ntstatus;
3946 update_cache:
3948 if (!cache_account_policy_set(policy_index, *value)) {
3949 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3950 "tdb as a cache\n"));
3951 return NT_STATUS_UNSUCCESSFUL;
3954 return NT_STATUS_OK;
3957 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3958 const DOM_SID *domain_sid,
3959 int num_rids,
3960 uint32 *rids,
3961 const char **names,
3962 enum lsa_SidType *attrs)
3964 struct ldapsam_privates *ldap_state =
3965 (struct ldapsam_privates *)methods->private_data;
3966 LDAPMessage *msg = NULL;
3967 LDAPMessage *entry;
3968 char *allsids = NULL;
3969 int i, rc, num_mapped;
3970 NTSTATUS result = NT_STATUS_NO_MEMORY;
3971 TALLOC_CTX *mem_ctx;
3972 LDAP *ld;
3973 bool is_builtin;
3975 mem_ctx = talloc_new(NULL);
3976 if (mem_ctx == NULL) {
3977 DEBUG(0, ("talloc_new failed\n"));
3978 goto done;
3981 if (!sid_check_is_builtin(domain_sid) &&
3982 !sid_check_is_domain(domain_sid)) {
3983 result = NT_STATUS_INVALID_PARAMETER;
3984 goto done;
3987 for (i=0; i<num_rids; i++)
3988 attrs[i] = SID_NAME_UNKNOWN;
3990 allsids = talloc_strdup(mem_ctx, "");
3991 if (allsids == NULL) {
3992 goto done;
3995 for (i=0; i<num_rids; i++) {
3996 DOM_SID sid;
3997 sid_compose(&sid, domain_sid, rids[i]);
3998 allsids = talloc_asprintf_append_buffer(
3999 allsids, "(sambaSid=%s)",
4000 sid_string_talloc(mem_ctx, &sid));
4001 if (allsids == NULL) {
4002 goto done;
4006 /* First look for users */
4009 char *filter;
4010 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4012 filter = talloc_asprintf(
4013 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4014 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4016 if (filter == NULL) {
4017 goto done;
4020 rc = smbldap_search(ldap_state->smbldap_state,
4021 lp_ldap_user_suffix(),
4022 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4023 &msg);
4024 talloc_autofree_ldapmsg(mem_ctx, msg);
4027 if (rc != LDAP_SUCCESS)
4028 goto done;
4030 ld = ldap_state->smbldap_state->ldap_struct;
4031 num_mapped = 0;
4033 for (entry = ldap_first_entry(ld, msg);
4034 entry != NULL;
4035 entry = ldap_next_entry(ld, entry)) {
4036 uint32 rid;
4037 int rid_index;
4038 const char *name;
4040 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4041 &rid)) {
4042 DEBUG(2, ("Could not find sid from ldap entry\n"));
4043 continue;
4046 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4047 names);
4048 if (name == NULL) {
4049 DEBUG(2, ("Could not retrieve uid attribute\n"));
4050 continue;
4053 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4054 if (rid == rids[rid_index])
4055 break;
4058 if (rid_index == num_rids) {
4059 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4060 continue;
4063 attrs[rid_index] = SID_NAME_USER;
4064 names[rid_index] = name;
4065 num_mapped += 1;
4068 if (num_mapped == num_rids) {
4069 /* No need to look for groups anymore -- we're done */
4070 result = NT_STATUS_OK;
4071 goto done;
4074 /* Same game for groups */
4077 char *filter;
4078 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4079 "sambaGroupType", NULL };
4081 filter = talloc_asprintf(
4082 mem_ctx, "(&(objectClass=%s)(|%s))",
4083 LDAP_OBJ_GROUPMAP, allsids);
4084 if (filter == NULL) {
4085 goto done;
4088 rc = smbldap_search(ldap_state->smbldap_state,
4089 lp_ldap_group_suffix(),
4090 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4091 &msg);
4092 talloc_autofree_ldapmsg(mem_ctx, msg);
4095 if (rc != LDAP_SUCCESS)
4096 goto done;
4098 /* ldap_struct might have changed due to a reconnect */
4100 ld = ldap_state->smbldap_state->ldap_struct;
4102 /* For consistency checks, we already checked we're only domain or builtin */
4104 is_builtin = sid_check_is_builtin(domain_sid);
4106 for (entry = ldap_first_entry(ld, msg);
4107 entry != NULL;
4108 entry = ldap_next_entry(ld, entry))
4110 uint32 rid;
4111 int rid_index;
4112 const char *attr;
4113 enum lsa_SidType type;
4114 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4116 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4117 mem_ctx);
4118 if (attr == NULL) {
4119 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4120 dn));
4121 continue;
4124 type = (enum lsa_SidType)atol(attr);
4126 /* Consistency checks */
4127 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4128 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4129 (type != SID_NAME_DOM_GRP)))) {
4130 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4133 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4134 &rid)) {
4135 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4136 continue;
4139 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4141 if (attr == NULL) {
4142 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4143 dn));
4144 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4147 if (attr == NULL) {
4148 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4149 dn));
4150 continue;
4153 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4154 if (rid == rids[rid_index])
4155 break;
4158 if (rid_index == num_rids) {
4159 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4160 continue;
4163 attrs[rid_index] = type;
4164 names[rid_index] = attr;
4165 num_mapped += 1;
4168 result = NT_STATUS_NONE_MAPPED;
4170 if (num_mapped > 0)
4171 result = (num_mapped == num_rids) ?
4172 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4173 done:
4174 TALLOC_FREE(mem_ctx);
4175 return result;
4178 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4180 char *filter = NULL;
4181 char *escaped = NULL;
4182 char *result = NULL;
4184 asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
4185 "(uid=%u)");
4186 if (filter == NULL) goto done;
4188 escaped = escape_ldap_string_alloc(username);
4189 if (escaped == NULL) goto done;
4191 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4193 done:
4194 SAFE_FREE(filter);
4195 SAFE_FREE(escaped);
4197 return result;
4200 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4202 int i, num = 0;
4203 va_list ap;
4204 const char **result;
4206 va_start(ap, mem_ctx);
4207 while (va_arg(ap, const char *) != NULL)
4208 num += 1;
4209 va_end(ap);
4211 if ((result = TALLOC_ARRAY(mem_ctx, const char *, num+1)) == NULL) {
4212 return NULL;
4215 va_start(ap, mem_ctx);
4216 for (i=0; i<num; i++) {
4217 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4218 if (result[i] == NULL) {
4219 talloc_free(result);
4220 return NULL;
4223 va_end(ap);
4225 result[num] = NULL;
4226 return result;
4229 struct ldap_search_state {
4230 struct smbldap_state *connection;
4232 uint32 acct_flags;
4233 uint16 group_type;
4235 const char *base;
4236 int scope;
4237 const char *filter;
4238 const char **attrs;
4239 int attrsonly;
4240 void *pagedresults_cookie;
4242 LDAPMessage *entries, *current_entry;
4243 bool (*ldap2displayentry)(struct ldap_search_state *state,
4244 TALLOC_CTX *mem_ctx,
4245 LDAP *ld, LDAPMessage *entry,
4246 struct samr_displayentry *result);
4249 static bool ldapsam_search_firstpage(struct pdb_search *search)
4251 struct ldap_search_state *state =
4252 (struct ldap_search_state *)search->private_data;
4253 LDAP *ld;
4254 int rc = LDAP_OPERATIONS_ERROR;
4256 state->entries = NULL;
4258 if (state->connection->paged_results) {
4259 rc = smbldap_search_paged(state->connection, state->base,
4260 state->scope, state->filter,
4261 state->attrs, state->attrsonly,
4262 lp_ldap_page_size(), &state->entries,
4263 &state->pagedresults_cookie);
4266 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4268 if (state->entries != NULL) {
4269 /* Left over from unsuccessful paged attempt */
4270 ldap_msgfree(state->entries);
4271 state->entries = NULL;
4274 rc = smbldap_search(state->connection, state->base,
4275 state->scope, state->filter, state->attrs,
4276 state->attrsonly, &state->entries);
4278 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4279 return False;
4281 /* Ok, the server was lying. It told us it could do paged
4282 * searches when it could not. */
4283 state->connection->paged_results = False;
4286 ld = state->connection->ldap_struct;
4287 if ( ld == NULL) {
4288 DEBUG(5, ("Don't have an LDAP connection right after a "
4289 "search\n"));
4290 return False;
4292 state->current_entry = ldap_first_entry(ld, state->entries);
4294 if (state->current_entry == NULL) {
4295 ldap_msgfree(state->entries);
4296 state->entries = NULL;
4299 return True;
4302 static bool ldapsam_search_nextpage(struct pdb_search *search)
4304 struct ldap_search_state *state =
4305 (struct ldap_search_state *)search->private_data;
4306 int rc;
4308 if (!state->connection->paged_results) {
4309 /* There is no next page when there are no paged results */
4310 return False;
4313 rc = smbldap_search_paged(state->connection, state->base,
4314 state->scope, state->filter, state->attrs,
4315 state->attrsonly, lp_ldap_page_size(),
4316 &state->entries,
4317 &state->pagedresults_cookie);
4319 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4320 return False;
4322 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4324 if (state->current_entry == NULL) {
4325 ldap_msgfree(state->entries);
4326 state->entries = NULL;
4329 return True;
4332 static bool ldapsam_search_next_entry(struct pdb_search *search,
4333 struct samr_displayentry *entry)
4335 struct ldap_search_state *state =
4336 (struct ldap_search_state *)search->private_data;
4337 bool result;
4339 retry:
4340 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4341 return False;
4343 if ((state->entries == NULL) &&
4344 !ldapsam_search_nextpage(search))
4345 return False;
4347 result = state->ldap2displayentry(state, search->mem_ctx, state->connection->ldap_struct,
4348 state->current_entry, entry);
4350 if (!result) {
4351 char *dn;
4352 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4353 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4354 if (dn != NULL) ldap_memfree(dn);
4357 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4359 if (state->current_entry == NULL) {
4360 ldap_msgfree(state->entries);
4361 state->entries = NULL;
4364 if (!result) goto retry;
4366 return True;
4369 static void ldapsam_search_end(struct pdb_search *search)
4371 struct ldap_search_state *state =
4372 (struct ldap_search_state *)search->private_data;
4373 int rc;
4375 if (state->pagedresults_cookie == NULL)
4376 return;
4378 if (state->entries != NULL)
4379 ldap_msgfree(state->entries);
4381 state->entries = NULL;
4382 state->current_entry = NULL;
4384 if (!state->connection->paged_results)
4385 return;
4387 /* Tell the LDAP server we're not interested in the rest anymore. */
4389 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4390 state->filter, state->attrs,
4391 state->attrsonly, 0, &state->entries,
4392 &state->pagedresults_cookie);
4394 if (rc != LDAP_SUCCESS)
4395 DEBUG(5, ("Could not end search properly\n"));
4397 return;
4400 static bool ldapuser2displayentry(struct ldap_search_state *state,
4401 TALLOC_CTX *mem_ctx,
4402 LDAP *ld, LDAPMessage *entry,
4403 struct samr_displayentry *result)
4405 char **vals;
4406 DOM_SID sid;
4407 uint32 acct_flags;
4409 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4410 if ((vals == NULL) || (vals[0] == NULL)) {
4411 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4412 return False;
4414 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4415 ldap_value_free(vals);
4417 if ((state->acct_flags != 0) &&
4418 ((state->acct_flags & acct_flags) == 0))
4419 return False;
4421 result->acct_flags = acct_flags;
4422 result->account_name = "";
4423 result->fullname = "";
4424 result->description = "";
4426 vals = ldap_get_values(ld, entry, "uid");
4427 if ((vals == NULL) || (vals[0] == NULL)) {
4428 DEBUG(5, ("\"uid\" not found\n"));
4429 return False;
4431 pull_utf8_talloc(mem_ctx,
4432 CONST_DISCARD(char **, &result->account_name),
4433 vals[0]);
4434 ldap_value_free(vals);
4436 vals = ldap_get_values(ld, entry, "displayName");
4437 if ((vals == NULL) || (vals[0] == NULL))
4438 DEBUG(8, ("\"displayName\" not found\n"));
4439 else
4440 pull_utf8_talloc(mem_ctx,
4441 CONST_DISCARD(char **, &result->fullname),
4442 vals[0]);
4443 ldap_value_free(vals);
4445 vals = ldap_get_values(ld, entry, "description");
4446 if ((vals == NULL) || (vals[0] == NULL))
4447 DEBUG(8, ("\"description\" not found\n"));
4448 else
4449 pull_utf8_talloc(mem_ctx,
4450 CONST_DISCARD(char **, &result->description),
4451 vals[0]);
4452 ldap_value_free(vals);
4454 if ((result->account_name == NULL) ||
4455 (result->fullname == NULL) ||
4456 (result->description == NULL)) {
4457 DEBUG(0, ("talloc failed\n"));
4458 return False;
4461 vals = ldap_get_values(ld, entry, "sambaSid");
4462 if ((vals == NULL) || (vals[0] == NULL)) {
4463 DEBUG(0, ("\"objectSid\" not found\n"));
4464 return False;
4467 if (!string_to_sid(&sid, vals[0])) {
4468 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4469 ldap_value_free(vals);
4470 return False;
4472 ldap_value_free(vals);
4474 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4475 DEBUG(0, ("sid %s does not belong to our domain\n",
4476 sid_string_dbg(&sid)));
4477 return False;
4480 return True;
4484 static bool ldapsam_search_users(struct pdb_methods *methods,
4485 struct pdb_search *search,
4486 uint32 acct_flags)
4488 struct ldapsam_privates *ldap_state =
4489 (struct ldapsam_privates *)methods->private_data;
4490 struct ldap_search_state *state;
4492 state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4493 if (state == NULL) {
4494 DEBUG(0, ("talloc failed\n"));
4495 return False;
4498 state->connection = ldap_state->smbldap_state;
4500 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4501 state->base = lp_ldap_user_suffix();
4502 else if ((acct_flags != 0) &&
4503 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4504 state->base = lp_ldap_machine_suffix();
4505 else
4506 state->base = lp_ldap_suffix();
4508 state->acct_flags = acct_flags;
4509 state->base = talloc_strdup(search->mem_ctx, state->base);
4510 state->scope = LDAP_SCOPE_SUBTREE;
4511 state->filter = get_ldap_filter(search->mem_ctx, "*");
4512 state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
4513 "displayName", "description",
4514 "sambaAcctFlags", NULL);
4515 state->attrsonly = 0;
4516 state->pagedresults_cookie = NULL;
4517 state->entries = NULL;
4518 state->ldap2displayentry = ldapuser2displayentry;
4520 if ((state->filter == NULL) || (state->attrs == NULL)) {
4521 DEBUG(0, ("talloc failed\n"));
4522 return False;
4525 search->private_data = state;
4526 search->next_entry = ldapsam_search_next_entry;
4527 search->search_end = ldapsam_search_end;
4529 return ldapsam_search_firstpage(search);
4532 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4533 TALLOC_CTX *mem_ctx,
4534 LDAP *ld, LDAPMessage *entry,
4535 struct samr_displayentry *result)
4537 char **vals;
4538 DOM_SID sid;
4539 uint16 group_type;
4541 result->account_name = "";
4542 result->fullname = "";
4543 result->description = "";
4546 vals = ldap_get_values(ld, entry, "sambaGroupType");
4547 if ((vals == NULL) || (vals[0] == NULL)) {
4548 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4549 if (vals != NULL) {
4550 ldap_value_free(vals);
4552 return False;
4555 group_type = atoi(vals[0]);
4557 if ((state->group_type != 0) &&
4558 ((state->group_type != group_type))) {
4559 ldap_value_free(vals);
4560 return False;
4563 ldap_value_free(vals);
4565 /* display name is the NT group name */
4567 vals = ldap_get_values(ld, entry, "displayName");
4568 if ((vals == NULL) || (vals[0] == NULL)) {
4569 DEBUG(8, ("\"displayName\" not found\n"));
4571 /* fallback to the 'cn' attribute */
4572 vals = ldap_get_values(ld, entry, "cn");
4573 if ((vals == NULL) || (vals[0] == NULL)) {
4574 DEBUG(5, ("\"cn\" not found\n"));
4575 return False;
4577 pull_utf8_talloc(mem_ctx,
4578 CONST_DISCARD(char **, &result->account_name),
4579 vals[0]);
4581 else {
4582 pull_utf8_talloc(mem_ctx,
4583 CONST_DISCARD(char **, &result->account_name),
4584 vals[0]);
4587 ldap_value_free(vals);
4589 vals = ldap_get_values(ld, entry, "description");
4590 if ((vals == NULL) || (vals[0] == NULL))
4591 DEBUG(8, ("\"description\" not found\n"));
4592 else
4593 pull_utf8_talloc(mem_ctx,
4594 CONST_DISCARD(char **, &result->description),
4595 vals[0]);
4596 ldap_value_free(vals);
4598 if ((result->account_name == NULL) ||
4599 (result->fullname == NULL) ||
4600 (result->description == NULL)) {
4601 DEBUG(0, ("talloc failed\n"));
4602 return False;
4605 vals = ldap_get_values(ld, entry, "sambaSid");
4606 if ((vals == NULL) || (vals[0] == NULL)) {
4607 DEBUG(0, ("\"objectSid\" not found\n"));
4608 if (vals != NULL) {
4609 ldap_value_free(vals);
4611 return False;
4614 if (!string_to_sid(&sid, vals[0])) {
4615 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4616 return False;
4619 ldap_value_free(vals);
4621 switch (group_type) {
4622 case SID_NAME_DOM_GRP:
4623 case SID_NAME_ALIAS:
4625 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4626 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4628 DEBUG(0, ("%s is not in our domain\n",
4629 sid_string_dbg(&sid)));
4630 return False;
4632 break;
4634 default:
4635 DEBUG(0,("unkown group type: %d\n", group_type));
4636 return False;
4639 return True;
4642 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4643 struct pdb_search *search,
4644 const DOM_SID *sid,
4645 enum lsa_SidType type)
4647 struct ldapsam_privates *ldap_state =
4648 (struct ldapsam_privates *)methods->private_data;
4649 struct ldap_search_state *state;
4650 fstring tmp;
4652 state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4653 if (state == NULL) {
4654 DEBUG(0, ("talloc failed\n"));
4655 return False;
4658 state->connection = ldap_state->smbldap_state;
4660 state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
4661 state->connection = ldap_state->smbldap_state;
4662 state->scope = LDAP_SCOPE_SUBTREE;
4663 state->filter = talloc_asprintf(search->mem_ctx,
4664 "(&(objectclass=sambaGroupMapping)"
4665 "(sambaGroupType=%d)(sambaSID=%s*))",
4666 type, sid_to_fstring(tmp, sid));
4667 state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
4668 "displayName", "description",
4669 "sambaGroupType", NULL);
4670 state->attrsonly = 0;
4671 state->pagedresults_cookie = NULL;
4672 state->entries = NULL;
4673 state->group_type = type;
4674 state->ldap2displayentry = ldapgroup2displayentry;
4676 if ((state->filter == NULL) || (state->attrs == NULL)) {
4677 DEBUG(0, ("talloc failed\n"));
4678 return False;
4681 search->private_data = state;
4682 search->next_entry = ldapsam_search_next_entry;
4683 search->search_end = ldapsam_search_end;
4685 return ldapsam_search_firstpage(search);
4688 static bool ldapsam_search_groups(struct pdb_methods *methods,
4689 struct pdb_search *search)
4691 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4694 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4695 struct pdb_search *search,
4696 const DOM_SID *sid)
4698 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4701 static bool ldapsam_rid_algorithm(struct pdb_methods *methods)
4703 return False;
4706 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4707 uint32 *rid)
4709 struct smbldap_state *smbldap_state = priv->smbldap_state;
4711 LDAPMessage *result = NULL;
4712 LDAPMessage *entry = NULL;
4713 LDAPMod **mods = NULL;
4714 NTSTATUS status;
4715 char *value;
4716 int rc;
4717 uint32 nextRid = 0;
4718 const char *dn;
4720 TALLOC_CTX *mem_ctx;
4722 mem_ctx = talloc_new(NULL);
4723 if (mem_ctx == NULL) {
4724 DEBUG(0, ("talloc_new failed\n"));
4725 return NT_STATUS_NO_MEMORY;
4728 status = smbldap_search_domain_info(smbldap_state, &result,
4729 get_global_sam_name(), False);
4730 if (!NT_STATUS_IS_OK(status)) {
4731 DEBUG(3, ("Could not get domain info: %s\n",
4732 nt_errstr(status)));
4733 goto done;
4736 talloc_autofree_ldapmsg(mem_ctx, result);
4738 entry = ldap_first_entry(priv2ld(priv), result);
4739 if (entry == NULL) {
4740 DEBUG(0, ("Could not get domain info entry\n"));
4741 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4742 goto done;
4745 /* Find the largest of the three attributes "sambaNextRid",
4746 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4747 concept of differentiating between user and group rids, and will
4748 use only "sambaNextRid" in the future. But for compatibility
4749 reasons I look if others have chosen different strategies -- VL */
4751 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4752 "sambaNextRid", mem_ctx);
4753 if (value != NULL) {
4754 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4755 nextRid = MAX(nextRid, tmp);
4758 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4759 "sambaNextUserRid", mem_ctx);
4760 if (value != NULL) {
4761 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4762 nextRid = MAX(nextRid, tmp);
4765 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4766 "sambaNextGroupRid", mem_ctx);
4767 if (value != NULL) {
4768 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4769 nextRid = MAX(nextRid, tmp);
4772 if (nextRid == 0) {
4773 nextRid = BASE_RID-1;
4776 nextRid += 1;
4778 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4779 talloc_asprintf(mem_ctx, "%d", nextRid));
4780 talloc_autofree_ldapmod(mem_ctx, mods);
4782 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4783 status = NT_STATUS_NO_MEMORY;
4784 goto done;
4787 rc = smbldap_modify(smbldap_state, dn, mods);
4789 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4790 * please retry" */
4792 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4794 done:
4795 if (NT_STATUS_IS_OK(status)) {
4796 *rid = nextRid;
4799 TALLOC_FREE(mem_ctx);
4800 return status;
4803 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32 *rid)
4805 int i;
4807 for (i=0; i<10; i++) {
4808 NTSTATUS result = ldapsam_get_new_rid(
4809 (struct ldapsam_privates *)methods->private_data, rid);
4810 if (NT_STATUS_IS_OK(result)) {
4811 return result;
4814 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4815 return result;
4818 /* The ldap update failed (maybe a race condition), retry */
4821 /* Tried 10 times, fail. */
4822 return NT_STATUS_ACCESS_DENIED;
4825 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4827 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4828 return NT_STATUS_IS_OK(result) ? True : False;
4831 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4832 const DOM_SID *sid,
4833 union unid_t *id, enum lsa_SidType *type)
4835 struct ldapsam_privates *priv =
4836 (struct ldapsam_privates *)methods->private_data;
4837 char *filter;
4838 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4839 NULL };
4840 LDAPMessage *result = NULL;
4841 LDAPMessage *entry = NULL;
4842 bool ret = False;
4843 char *value;
4844 int rc;
4846 TALLOC_CTX *mem_ctx;
4848 mem_ctx = talloc_new(NULL);
4849 if (mem_ctx == NULL) {
4850 DEBUG(0, ("talloc_new failed\n"));
4851 return False;
4854 filter = talloc_asprintf(mem_ctx,
4855 "(&(sambaSid=%s)"
4856 "(|(objectClass=%s)(objectClass=%s)))",
4857 sid_string_talloc(mem_ctx, sid),
4858 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4859 if (filter == NULL) {
4860 DEBUG(5, ("talloc_asprintf failed\n"));
4861 goto done;
4864 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4865 attrs, &result);
4866 if (rc != LDAP_SUCCESS) {
4867 goto done;
4869 talloc_autofree_ldapmsg(mem_ctx, result);
4871 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4872 DEBUG(10, ("Got %d entries, expected one\n",
4873 ldap_count_entries(priv2ld(priv), result)));
4874 goto done;
4877 entry = ldap_first_entry(priv2ld(priv), result);
4879 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4880 "sambaGroupType", mem_ctx);
4882 if (value != NULL) {
4883 const char *gid_str;
4884 /* It's a group */
4886 gid_str = smbldap_talloc_single_attribute(
4887 priv2ld(priv), entry, "gidNumber", mem_ctx);
4888 if (gid_str == NULL) {
4889 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4890 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4891 entry)));
4892 goto done;
4895 id->gid = strtoul(gid_str, NULL, 10);
4896 *type = (enum lsa_SidType)strtoul(value, NULL, 10);
4897 ret = True;
4898 goto done;
4901 /* It must be a user */
4903 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4904 "uidNumber", mem_ctx);
4905 if (value == NULL) {
4906 DEBUG(1, ("Could not find uidNumber in %s\n",
4907 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4908 goto done;
4911 id->uid = strtoul(value, NULL, 10);
4912 *type = SID_NAME_USER;
4914 ret = True;
4915 done:
4916 TALLOC_FREE(mem_ctx);
4917 return ret;
4921 * The following functions is called only if
4922 * ldapsam:trusted and ldapsam:editposix are
4923 * set to true
4927 * ldapsam_create_user creates a new
4928 * posixAccount and sambaSamAccount object
4929 * in the ldap users subtree
4931 * The uid is allocated by winbindd.
4934 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
4935 TALLOC_CTX *tmp_ctx, const char *name,
4936 uint32 acb_info, uint32 *rid)
4938 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
4939 LDAPMessage *entry = NULL;
4940 LDAPMessage *result = NULL;
4941 uint32 num_result;
4942 bool is_machine = False;
4943 bool add_posix = False;
4944 LDAPMod **mods = NULL;
4945 struct samu *user;
4946 char *filter;
4947 char *username;
4948 char *homedir;
4949 char *gidstr;
4950 char *uidstr;
4951 char *shell;
4952 const char *dn = NULL;
4953 DOM_SID group_sid;
4954 DOM_SID user_sid;
4955 gid_t gid = -1;
4956 uid_t uid = -1;
4957 NTSTATUS ret;
4958 int rc;
4960 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
4961 acb_info & ACB_WSTRUST ||
4962 acb_info & ACB_SVRTRUST ||
4963 acb_info & ACB_DOMTRUST) {
4964 is_machine = True;
4967 username = escape_ldap_string_alloc(name);
4968 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
4969 username, LDAP_OBJ_POSIXACCOUNT);
4970 SAFE_FREE(username);
4972 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
4973 if (rc != LDAP_SUCCESS) {
4974 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
4975 return NT_STATUS_UNSUCCESSFUL;
4977 talloc_autofree_ldapmsg(tmp_ctx, result);
4979 num_result = ldap_count_entries(priv2ld(ldap_state), result);
4981 if (num_result > 1) {
4982 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
4983 return NT_STATUS_INTERNAL_DB_CORRUPTION;
4986 if (num_result == 1) {
4987 char *tmp;
4988 /* check if it is just a posix account.
4989 * or if there is a sid attached to this entry
4992 entry = ldap_first_entry(priv2ld(ldap_state), result);
4993 if (!entry) {
4994 return NT_STATUS_UNSUCCESSFUL;
4997 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
4998 if (tmp) {
4999 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5000 return NT_STATUS_USER_EXISTS;
5003 /* it is just a posix account, retrieve the dn for later use */
5004 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5005 if (!dn) {
5006 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5007 return NT_STATUS_NO_MEMORY;
5011 if (num_result == 0) {
5012 add_posix = True;
5015 /* Create the basic samu structure and generate the mods for the ldap commit */
5016 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5017 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5018 return ret;
5021 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5023 user = samu_new(tmp_ctx);
5024 if (!user) {
5025 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5026 return NT_STATUS_NO_MEMORY;
5029 if (!pdb_set_username(user, name, PDB_SET)) {
5030 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5031 return NT_STATUS_UNSUCCESSFUL;
5033 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5034 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5035 return NT_STATUS_UNSUCCESSFUL;
5037 if (is_machine) {
5038 if (acb_info & ACB_NORMAL) {
5039 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5040 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5041 return NT_STATUS_UNSUCCESSFUL;
5043 } else {
5044 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5045 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5046 return NT_STATUS_UNSUCCESSFUL;
5049 } else {
5050 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5051 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5052 return NT_STATUS_UNSUCCESSFUL;
5056 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5057 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5058 return NT_STATUS_UNSUCCESSFUL;
5061 if (!init_ldap_from_sam(ldap_state, NULL, &mods, user, element_is_set_or_changed)) {
5062 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5063 return NT_STATUS_UNSUCCESSFUL;
5066 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5067 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5069 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5071 if (add_posix) {
5072 char *escape_name;
5074 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5076 /* retrieve the Domain Users group gid */
5077 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_GROUP_RID_USERS) ||
5078 !sid_to_gid(&group_sid, &gid)) {
5079 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5080 return NT_STATUS_INVALID_PRIMARY_GROUP;
5083 /* lets allocate a new userid for this user */
5084 if (!winbind_allocate_uid(&uid)) {
5085 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5086 return NT_STATUS_UNSUCCESSFUL;
5090 if (is_machine) {
5091 /* TODO: choose a more appropriate default for machines */
5092 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5093 shell = talloc_strdup(tmp_ctx, "/bin/false");
5094 } else {
5095 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5096 shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5098 uidstr = talloc_asprintf(tmp_ctx, "%d", uid);
5099 gidstr = talloc_asprintf(tmp_ctx, "%d", gid);
5101 escape_name = escape_rdn_val_string_alloc(name);
5102 if (!escape_name) {
5103 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5104 return NT_STATUS_NO_MEMORY;
5107 if (is_machine) {
5108 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
5109 } else {
5110 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
5113 SAFE_FREE(escape_name);
5115 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5116 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5117 return NT_STATUS_NO_MEMORY;
5120 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5121 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5122 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5123 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5124 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5125 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5126 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5129 talloc_autofree_ldapmod(tmp_ctx, mods);
5131 if (add_posix) {
5132 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5133 } else {
5134 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5137 if (rc != LDAP_SUCCESS) {
5138 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5139 return NT_STATUS_UNSUCCESSFUL;
5142 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5144 flush_pwnam_cache();
5146 return NT_STATUS_OK;
5149 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5151 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5152 LDAPMessage *result = NULL;
5153 LDAPMessage *entry = NULL;
5154 int num_result;
5155 const char *dn;
5156 char *filter;
5157 int rc;
5159 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5161 filter = talloc_asprintf(tmp_ctx,
5162 "(&(uid=%s)"
5163 "(objectClass=%s)"
5164 "(objectClass=%s))",
5165 pdb_get_username(sam_acct),
5166 LDAP_OBJ_POSIXACCOUNT,
5167 LDAP_OBJ_SAMBASAMACCOUNT);
5168 if (filter == NULL) {
5169 return NT_STATUS_NO_MEMORY;
5172 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5173 if (rc != LDAP_SUCCESS) {
5174 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5175 return NT_STATUS_UNSUCCESSFUL;
5177 talloc_autofree_ldapmsg(tmp_ctx, result);
5179 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5181 if (num_result == 0) {
5182 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5183 return NT_STATUS_NO_SUCH_USER;
5186 if (num_result > 1) {
5187 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5188 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5191 entry = ldap_first_entry(priv2ld(ldap_state), result);
5192 if (!entry) {
5193 return NT_STATUS_UNSUCCESSFUL;
5196 /* it is just a posix account, retrieve the dn for later use */
5197 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5198 if (!dn) {
5199 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5200 return NT_STATUS_NO_MEMORY;
5203 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5204 if (rc != LDAP_SUCCESS) {
5205 return NT_STATUS_UNSUCCESSFUL;
5208 flush_pwnam_cache();
5210 return NT_STATUS_OK;
5214 * ldapsam_create_group creates a new
5215 * posixGroup and sambaGroupMapping object
5216 * in the ldap groups subtree
5218 * The gid is allocated by winbindd.
5221 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5222 TALLOC_CTX *tmp_ctx,
5223 const char *name,
5224 uint32 *rid)
5226 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5227 NTSTATUS ret;
5228 LDAPMessage *entry = NULL;
5229 LDAPMessage *result = NULL;
5230 uint32 num_result;
5231 bool is_new_entry = False;
5232 LDAPMod **mods = NULL;
5233 char *filter;
5234 char *groupsidstr;
5235 char *groupname;
5236 char *grouptype;
5237 char *gidstr;
5238 const char *dn = NULL;
5239 DOM_SID group_sid;
5240 gid_t gid = -1;
5241 int rc;
5243 groupname = escape_ldap_string_alloc(name);
5244 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5245 groupname, LDAP_OBJ_POSIXGROUP);
5246 SAFE_FREE(groupname);
5248 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5249 if (rc != LDAP_SUCCESS) {
5250 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5251 return NT_STATUS_UNSUCCESSFUL;
5253 talloc_autofree_ldapmsg(tmp_ctx, result);
5255 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5257 if (num_result > 1) {
5258 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5259 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5262 if (num_result == 1) {
5263 char *tmp;
5264 /* check if it is just a posix group.
5265 * or if there is a sid attached to this entry
5268 entry = ldap_first_entry(priv2ld(ldap_state), result);
5269 if (!entry) {
5270 return NT_STATUS_UNSUCCESSFUL;
5273 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5274 if (tmp) {
5275 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5276 return NT_STATUS_GROUP_EXISTS;
5279 /* it is just a posix group, retrieve the gid and the dn for later use */
5280 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5281 if (!tmp) {
5282 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5283 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5286 gid = strtoul(tmp, NULL, 10);
5288 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5289 if (!dn) {
5290 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5291 return NT_STATUS_NO_MEMORY;
5295 if (num_result == 0) {
5296 char *escape_name;
5298 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5300 is_new_entry = True;
5302 /* lets allocate a new groupid for this group */
5303 if (!winbind_allocate_gid(&gid)) {
5304 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5305 return NT_STATUS_UNSUCCESSFUL;
5308 gidstr = talloc_asprintf(tmp_ctx, "%d", gid);
5310 escape_name = escape_rdn_val_string_alloc(name);
5311 if (!escape_name) {
5312 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5313 return NT_STATUS_NO_MEMORY;
5316 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
5318 SAFE_FREE(escape_name);
5320 if (!gidstr || !dn) {
5321 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5322 return NT_STATUS_NO_MEMORY;
5325 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5326 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5327 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5330 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5331 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5332 return ret;
5335 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5337 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5338 &group_sid));
5339 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5341 if (!groupsidstr || !grouptype) {
5342 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5343 return NT_STATUS_NO_MEMORY;
5346 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5347 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5348 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5349 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5350 talloc_autofree_ldapmod(tmp_ctx, mods);
5352 if (is_new_entry) {
5353 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5354 #if 0
5355 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5356 /* This call may fail with rfc2307bis schema */
5357 /* Retry adding a structural class */
5358 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5359 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5361 #endif
5362 } else {
5363 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5366 if (rc != LDAP_SUCCESS) {
5367 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5368 return NT_STATUS_UNSUCCESSFUL;
5371 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5373 return NT_STATUS_OK;
5376 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32 rid)
5378 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5379 LDAPMessage *result = NULL;
5380 LDAPMessage *entry = NULL;
5381 int num_result;
5382 const char *dn;
5383 char *gidstr;
5384 char *filter;
5385 DOM_SID group_sid;
5386 int rc;
5388 /* get the group sid */
5389 sid_compose(&group_sid, get_global_sam_sid(), rid);
5391 filter = talloc_asprintf(tmp_ctx,
5392 "(&(sambaSID=%s)"
5393 "(objectClass=%s)"
5394 "(objectClass=%s))",
5395 sid_string_talloc(tmp_ctx, &group_sid),
5396 LDAP_OBJ_POSIXGROUP,
5397 LDAP_OBJ_GROUPMAP);
5398 if (filter == NULL) {
5399 return NT_STATUS_NO_MEMORY;
5402 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5403 if (rc != LDAP_SUCCESS) {
5404 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5405 return NT_STATUS_UNSUCCESSFUL;
5407 talloc_autofree_ldapmsg(tmp_ctx, result);
5409 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5411 if (num_result == 0) {
5412 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5413 return NT_STATUS_NO_SUCH_GROUP;
5416 if (num_result > 1) {
5417 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5418 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5421 entry = ldap_first_entry(priv2ld(ldap_state), result);
5422 if (!entry) {
5423 return NT_STATUS_UNSUCCESSFUL;
5426 /* here it is, retrieve the dn for later use */
5427 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5428 if (!dn) {
5429 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5430 return NT_STATUS_NO_MEMORY;
5433 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5434 if (!gidstr) {
5435 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5436 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5439 /* check no user have this group marked as primary group */
5440 filter = talloc_asprintf(tmp_ctx,
5441 "(&(gidNumber=%s)"
5442 "(objectClass=%s)"
5443 "(objectClass=%s))",
5444 gidstr,
5445 LDAP_OBJ_POSIXACCOUNT,
5446 LDAP_OBJ_SAMBASAMACCOUNT);
5448 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5449 if (rc != LDAP_SUCCESS) {
5450 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5451 return NT_STATUS_UNSUCCESSFUL;
5453 talloc_autofree_ldapmsg(tmp_ctx, result);
5455 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5457 if (num_result != 0) {
5458 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5459 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5462 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5463 if (rc != LDAP_SUCCESS) {
5464 return NT_STATUS_UNSUCCESSFUL;
5467 return NT_STATUS_OK;
5470 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5471 TALLOC_CTX *tmp_ctx,
5472 uint32 group_rid,
5473 uint32 member_rid,
5474 int modop)
5476 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5477 LDAPMessage *entry = NULL;
5478 LDAPMessage *result = NULL;
5479 uint32 num_result;
5480 LDAPMod **mods = NULL;
5481 char *filter;
5482 char *uidstr;
5483 const char *dn = NULL;
5484 DOM_SID group_sid;
5485 DOM_SID member_sid;
5486 int rc;
5488 switch (modop) {
5489 case LDAP_MOD_ADD:
5490 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5491 break;
5492 case LDAP_MOD_DELETE:
5493 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5494 break;
5495 default:
5496 return NT_STATUS_UNSUCCESSFUL;
5499 /* get member sid */
5500 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5502 /* get the group sid */
5503 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5505 filter = talloc_asprintf(tmp_ctx,
5506 "(&(sambaSID=%s)"
5507 "(objectClass=%s)"
5508 "(objectClass=%s))",
5509 sid_string_talloc(tmp_ctx, &member_sid),
5510 LDAP_OBJ_POSIXACCOUNT,
5511 LDAP_OBJ_SAMBASAMACCOUNT);
5512 if (filter == NULL) {
5513 return NT_STATUS_NO_MEMORY;
5516 /* get the member uid */
5517 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5518 if (rc != LDAP_SUCCESS) {
5519 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5520 return NT_STATUS_UNSUCCESSFUL;
5522 talloc_autofree_ldapmsg(tmp_ctx, result);
5524 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5526 if (num_result == 0) {
5527 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5528 return NT_STATUS_NO_SUCH_MEMBER;
5531 if (num_result > 1) {
5532 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5533 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5536 entry = ldap_first_entry(priv2ld(ldap_state), result);
5537 if (!entry) {
5538 return NT_STATUS_UNSUCCESSFUL;
5541 if (modop == LDAP_MOD_DELETE) {
5542 /* check if we are trying to remove the member from his primary group */
5543 char *gidstr;
5544 gid_t user_gid, group_gid;
5546 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5547 if (!gidstr) {
5548 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5549 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5552 user_gid = strtoul(gidstr, NULL, 10);
5554 if (!sid_to_gid(&group_sid, &group_gid)) {
5555 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5556 return NT_STATUS_UNSUCCESSFUL;
5559 if (user_gid == group_gid) {
5560 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5561 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5565 /* here it is, retrieve the uid for later use */
5566 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5567 if (!uidstr) {
5568 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5569 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5572 filter = talloc_asprintf(tmp_ctx,
5573 "(&(sambaSID=%s)"
5574 "(objectClass=%s)"
5575 "(objectClass=%s))",
5576 sid_string_talloc(tmp_ctx, &group_sid),
5577 LDAP_OBJ_POSIXGROUP,
5578 LDAP_OBJ_GROUPMAP);
5580 /* get the group */
5581 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5582 if (rc != LDAP_SUCCESS) {
5583 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5584 return NT_STATUS_UNSUCCESSFUL;
5586 talloc_autofree_ldapmsg(tmp_ctx, result);
5588 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5590 if (num_result == 0) {
5591 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5592 return NT_STATUS_NO_SUCH_GROUP;
5595 if (num_result > 1) {
5596 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5597 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5600 entry = ldap_first_entry(priv2ld(ldap_state), result);
5601 if (!entry) {
5602 return NT_STATUS_UNSUCCESSFUL;
5605 /* here it is, retrieve the dn for later use */
5606 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5607 if (!dn) {
5608 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5609 return NT_STATUS_NO_MEMORY;
5612 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5614 talloc_autofree_ldapmod(tmp_ctx, mods);
5616 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5617 if (rc != LDAP_SUCCESS) {
5618 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5619 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5620 return NT_STATUS_MEMBER_IN_GROUP;
5622 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5623 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5624 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5626 return NT_STATUS_UNSUCCESSFUL;
5629 return NT_STATUS_OK;
5632 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5633 TALLOC_CTX *tmp_ctx,
5634 uint32 group_rid,
5635 uint32 member_rid)
5637 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5639 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5640 TALLOC_CTX *tmp_ctx,
5641 uint32 group_rid,
5642 uint32 member_rid)
5644 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5647 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5648 TALLOC_CTX *mem_ctx,
5649 struct samu *sampass)
5651 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5652 LDAPMessage *entry = NULL;
5653 LDAPMessage *result = NULL;
5654 uint32 num_result;
5655 LDAPMod **mods = NULL;
5656 char *filter;
5657 char *escape_username;
5658 char *gidstr;
5659 const char *dn = NULL;
5660 gid_t gid;
5661 int rc;
5663 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5665 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5666 DEBUG(0,("ldapsam_set_primary_group: failed to retieve gid from user's group SID!\n"));
5667 return NT_STATUS_UNSUCCESSFUL;
5669 gidstr = talloc_asprintf(mem_ctx, "%d", gid);
5670 if (!gidstr) {
5671 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5672 return NT_STATUS_NO_MEMORY;
5675 escape_username = escape_ldap_string_alloc(pdb_get_username(sampass));
5676 if (escape_username== NULL) {
5677 return NT_STATUS_NO_MEMORY;
5680 filter = talloc_asprintf(mem_ctx,
5681 "(&(uid=%s)"
5682 "(objectClass=%s)"
5683 "(objectClass=%s))",
5684 escape_username,
5685 LDAP_OBJ_POSIXACCOUNT,
5686 LDAP_OBJ_SAMBASAMACCOUNT);
5688 SAFE_FREE(escape_username);
5690 if (filter == NULL) {
5691 return NT_STATUS_NO_MEMORY;
5694 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5695 if (rc != LDAP_SUCCESS) {
5696 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5697 return NT_STATUS_UNSUCCESSFUL;
5699 talloc_autofree_ldapmsg(mem_ctx, result);
5701 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5703 if (num_result == 0) {
5704 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5705 return NT_STATUS_NO_SUCH_USER;
5708 if (num_result > 1) {
5709 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5710 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5713 entry = ldap_first_entry(priv2ld(ldap_state), result);
5714 if (!entry) {
5715 return NT_STATUS_UNSUCCESSFUL;
5718 /* retrieve the dn for later use */
5719 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5720 if (!dn) {
5721 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5722 return NT_STATUS_NO_MEMORY;
5725 /* remove the old one, and add the new one, this way we do not risk races */
5726 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
5728 if (mods == NULL) {
5729 return NT_STATUS_OK;
5732 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5734 if (rc != LDAP_SUCCESS) {
5735 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
5736 pdb_get_username(sampass), gidstr));
5737 return NT_STATUS_UNSUCCESSFUL;
5740 flush_pwnam_cache();
5742 return NT_STATUS_OK;
5746 /**********************************************************************
5747 trusted domains functions
5748 *********************************************************************/
5750 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
5751 const char *domain)
5753 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
5754 ldap_state->domain_dn);
5757 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
5758 const char *domain, LDAPMessage **entry)
5760 int rc;
5761 char *filter;
5762 int scope = LDAP_SCOPE_SUBTREE;
5763 const char **attrs = NULL; /* NULL: get all attrs */
5764 int attrsonly = 0; /* 0: return values too */
5765 LDAPMessage *result = NULL;
5766 char *trusted_dn;
5767 uint32 num_result;
5769 filter = talloc_asprintf(talloc_tos(),
5770 "(&(objectClass=%s)(sambaDomainName=%s))",
5771 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
5773 trusted_dn = trusteddom_dn(ldap_state, domain);
5774 if (trusted_dn == NULL) {
5775 return False;
5777 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
5778 filter, attrs, attrsonly, &result);
5780 if (rc == LDAP_NO_SUCH_OBJECT) {
5781 *entry = NULL;
5782 return True;
5785 if (rc != LDAP_SUCCESS) {
5786 return False;
5789 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5791 if (num_result > 1) {
5792 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
5793 "sambaTrustedDomainPassword object for domain '%s'"
5794 "?!\n", domain));
5795 return False;
5798 if (num_result == 0) {
5799 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
5800 "sambaTrustedDomainPassword object for domain %s.\n",
5801 domain));
5802 *entry = NULL;
5803 } else {
5804 *entry = ldap_first_entry(priv2ld(ldap_state), result);
5807 return True;
5810 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
5811 const char *domain,
5812 char** pwd,
5813 DOM_SID *sid,
5814 time_t *pass_last_set_time)
5816 struct ldapsam_privates *ldap_state =
5817 (struct ldapsam_privates *)methods->private_data;
5818 LDAPMessage *entry = NULL;
5820 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
5822 if (!get_trusteddom_pw_int(ldap_state, domain, &entry) ||
5823 (entry == NULL))
5825 return False;
5828 /* password */
5829 if (pwd != NULL) {
5830 char *pwd_str;
5831 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5832 entry, "sambaClearTextPassword", talloc_tos());
5833 if (pwd_str == NULL) {
5834 return False;
5836 /* trusteddom_pw routines do not use talloc yet... */
5837 *pwd = SMB_STRDUP(pwd_str);
5838 if (*pwd == NULL) {
5839 return False;
5843 /* last change time */
5844 if (pass_last_set_time != NULL) {
5845 char *time_str;
5846 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5847 entry, "sambaPwdLastSet", talloc_tos());
5848 if (time_str == NULL) {
5849 return False;
5851 *pass_last_set_time = (time_t)atol(time_str);
5854 /* domain sid */
5855 if (sid != NULL) {
5856 char *sid_str;
5857 DOM_SID *dom_sid;
5858 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5859 entry, "sambaSID",
5860 talloc_tos());
5861 if (sid_str == NULL) {
5862 return False;
5864 dom_sid = string_sid_talloc(talloc_tos(), sid_str);
5865 if (dom_sid == NULL) {
5866 return False;
5868 sid_copy(sid, dom_sid);
5871 return True;
5874 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
5875 const char* domain,
5876 const char* pwd,
5877 const DOM_SID *sid)
5879 struct ldapsam_privates *ldap_state =
5880 (struct ldapsam_privates *)methods->private_data;
5881 LDAPMessage *entry = NULL;
5882 LDAPMod **mods = NULL;
5883 char *prev_pwd = NULL;
5884 char *trusted_dn = NULL;
5885 int rc;
5887 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
5890 * get the current entry (if there is one) in order to put the
5891 * current password into the previous password attribute
5893 if (!get_trusteddom_pw_int(ldap_state, domain, &entry)) {
5894 return False;
5897 mods = NULL;
5898 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
5899 "sambaTrustedDomainPassword");
5900 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
5901 domain);
5902 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
5903 sid_string_tos(sid));
5904 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
5905 talloc_asprintf(talloc_tos(), "%li", time(NULL)));
5906 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
5907 "sambaClearTextPassword", pwd);
5908 if (entry != NULL) {
5909 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5910 entry, "sambaClearTextPassword", talloc_tos());
5911 if (prev_pwd != NULL) {
5912 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
5913 "sambaPreviousClearTextPassword",
5914 prev_pwd);
5918 trusted_dn = trusteddom_dn(ldap_state, domain);
5919 if (trusted_dn == NULL) {
5920 return False;
5922 if (entry == NULL) {
5923 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
5924 } else {
5925 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
5928 if (rc != LDAP_SUCCESS) {
5929 DEBUG(1, ("error writing trusted domain password!\n"));
5930 return False;
5933 return True;
5936 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
5937 const char *domain)
5939 int rc;
5940 struct ldapsam_privates *ldap_state =
5941 (struct ldapsam_privates *)methods->private_data;
5942 LDAPMessage *entry = NULL;
5943 const char *trusted_dn;
5945 if (!get_trusteddom_pw_int(ldap_state, domain, &entry)) {
5946 return False;
5949 if (entry == NULL) {
5950 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
5951 "%s\n", domain));
5952 return True;
5955 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
5956 entry);
5957 if (trusted_dn == NULL) {
5958 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
5959 return False;
5962 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
5963 if (rc != LDAP_SUCCESS) {
5964 return False;
5967 return True;
5970 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
5971 TALLOC_CTX *mem_ctx,
5972 uint32 *num_domains,
5973 struct trustdom_info ***domains)
5975 int rc;
5976 struct ldapsam_privates *ldap_state =
5977 (struct ldapsam_privates *)methods->private_data;
5978 char *filter;
5979 int scope = LDAP_SCOPE_SUBTREE;
5980 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
5981 int attrsonly = 0; /* 0: return values too */
5982 LDAPMessage *result = NULL;
5983 LDAPMessage *entry = NULL;
5985 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
5986 LDAP_OBJ_TRUSTDOM_PASSWORD);
5988 rc = smbldap_search(ldap_state->smbldap_state,
5989 ldap_state->domain_dn,
5990 scope,
5991 filter,
5992 attrs,
5993 attrsonly,
5994 &result);
5996 if (rc != LDAP_SUCCESS) {
5997 return NT_STATUS_UNSUCCESSFUL;
6000 *num_domains = 0;
6001 if (!(*domains = TALLOC_ARRAY(mem_ctx, struct trustdom_info *, 1))) {
6002 DEBUG(1, ("talloc failed\n"));
6003 return NT_STATUS_NO_MEMORY;
6006 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6007 entry != NULL;
6008 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6010 char *dom_name, *dom_sid_str;
6011 struct trustdom_info *dom_info;
6013 dom_info = TALLOC_P(*domains, struct trustdom_info);
6014 if (dom_info == NULL) {
6015 DEBUG(1, ("talloc failed\n"));
6016 return NT_STATUS_NO_MEMORY;
6019 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6020 entry,
6021 "sambaDomainName",
6022 talloc_tos());
6023 if (dom_name == NULL) {
6024 DEBUG(1, ("talloc failed\n"));
6025 return NT_STATUS_NO_MEMORY;
6027 dom_info->name = dom_name;
6029 dom_sid_str = smbldap_talloc_single_attribute(
6030 priv2ld(ldap_state), entry, "sambaSID",
6031 talloc_tos());
6032 if (dom_sid_str == NULL) {
6033 DEBUG(1, ("talloc failed\n"));
6034 return NT_STATUS_NO_MEMORY;
6036 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6037 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6038 dom_sid_str));
6039 return NT_STATUS_UNSUCCESSFUL;
6042 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6043 domains, num_domains);
6045 if (*domains == NULL) {
6046 DEBUG(1, ("talloc failed\n"));
6047 return NT_STATUS_NO_MEMORY;
6051 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6052 return NT_STATUS_OK;
6056 /**********************************************************************
6057 Housekeeping
6058 *********************************************************************/
6060 static void free_private_data(void **vp)
6062 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6064 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6066 if ((*ldap_state)->result != NULL) {
6067 ldap_msgfree((*ldap_state)->result);
6068 (*ldap_state)->result = NULL;
6070 if ((*ldap_state)->domain_dn != NULL) {
6071 SAFE_FREE((*ldap_state)->domain_dn);
6074 *ldap_state = NULL;
6076 /* No need to free any further, as it is talloc()ed */
6079 /*********************************************************************
6080 Intitalise the parts of the pdb_methods structure that are common to
6081 all pdb_ldap modes
6082 *********************************************************************/
6084 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6086 NTSTATUS nt_status;
6087 struct ldapsam_privates *ldap_state;
6089 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6090 return nt_status;
6093 (*pdb_method)->name = "ldapsam";
6095 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6096 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6097 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6098 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6099 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6100 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6102 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6103 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6104 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6105 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6106 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6107 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6108 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6110 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6111 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6113 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6115 (*pdb_method)->rid_algorithm = ldapsam_rid_algorithm;
6116 (*pdb_method)->new_rid = ldapsam_new_rid;
6118 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6119 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6120 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6121 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6123 /* TODO: Setup private data and free */
6125 if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
6126 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6127 return NT_STATUS_NO_MEMORY;
6130 nt_status = smbldap_init(*pdb_method, pdb_get_event_context(),
6131 location, &ldap_state->smbldap_state);
6133 if ( !NT_STATUS_IS_OK(nt_status) ) {
6134 return nt_status;
6137 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6138 return NT_STATUS_NO_MEMORY;
6141 (*pdb_method)->private_data = ldap_state;
6143 (*pdb_method)->free_private_data = free_private_data;
6145 return NT_STATUS_OK;
6148 /**********************************************************************
6149 Initialise the 'compat' mode for pdb_ldap
6150 *********************************************************************/
6152 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
6154 NTSTATUS nt_status;
6155 struct ldapsam_privates *ldap_state;
6156 char *uri = talloc_strdup( NULL, location );
6158 trim_char( uri, '\"', '\"' );
6159 nt_status = pdb_init_ldapsam_common( pdb_method, uri );
6160 if ( uri )
6161 TALLOC_FREE( uri );
6163 if ( !NT_STATUS_IS_OK(nt_status) ) {
6164 return nt_status;
6167 (*pdb_method)->name = "ldapsam_compat";
6169 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6170 ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
6172 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6174 return NT_STATUS_OK;
6177 /**********************************************************************
6178 Initialise the normal mode for pdb_ldap
6179 *********************************************************************/
6181 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
6183 NTSTATUS nt_status;
6184 struct ldapsam_privates *ldap_state = NULL;
6185 uint32 alg_rid_base;
6186 char *alg_rid_base_string = NULL;
6187 LDAPMessage *result = NULL;
6188 LDAPMessage *entry = NULL;
6189 DOM_SID ldap_domain_sid;
6190 DOM_SID secrets_domain_sid;
6191 char *domain_sid_string = NULL;
6192 char *dn = NULL;
6193 char *uri = talloc_strdup( NULL, location );
6195 trim_char( uri, '\"', '\"' );
6196 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6197 if (uri) {
6198 TALLOC_FREE(uri);
6201 if (!NT_STATUS_IS_OK(nt_status)) {
6202 return nt_status;
6205 (*pdb_method)->name = "ldapsam";
6207 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6208 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6209 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6210 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6211 (*pdb_method)->search_users = ldapsam_search_users;
6212 (*pdb_method)->search_groups = ldapsam_search_groups;
6213 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6215 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6216 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6217 (*pdb_method)->enum_group_memberships =
6218 ldapsam_enum_group_memberships;
6219 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6220 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6222 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6223 (*pdb_method)->create_user = ldapsam_create_user;
6224 (*pdb_method)->delete_user = ldapsam_delete_user;
6225 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6226 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6227 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6228 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6229 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6233 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6234 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6236 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6238 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6239 &result,
6240 ldap_state->domain_name, True);
6242 if ( !NT_STATUS_IS_OK(nt_status) ) {
6243 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
6244 "info, nor add one to the domain\n"));
6245 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
6246 "will be unable to allocate new users/groups, "
6247 "and will risk BDCs having inconsistant SIDs\n"));
6248 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6249 return NT_STATUS_OK;
6252 /* Given that the above might fail, everything below this must be
6253 * optional */
6255 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6256 result);
6257 if (!entry) {
6258 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6259 "entry\n"));
6260 ldap_msgfree(result);
6261 return NT_STATUS_UNSUCCESSFUL;
6264 dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
6265 if (!dn) {
6266 ldap_msgfree(result);
6267 return NT_STATUS_UNSUCCESSFUL;
6270 ldap_state->domain_dn = smb_xstrdup(dn);
6271 ldap_memfree(dn);
6273 domain_sid_string = smbldap_talloc_single_attribute(
6274 ldap_state->smbldap_state->ldap_struct,
6275 entry,
6276 get_userattr_key2string(ldap_state->schema_ver,
6277 LDAP_ATTR_USER_SID),
6278 talloc_tos());
6280 if (domain_sid_string) {
6281 bool found_sid;
6282 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6283 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6284 "read as a valid SID\n", domain_sid_string));
6285 ldap_msgfree(result);
6286 TALLOC_FREE(domain_sid_string);
6287 return NT_STATUS_INVALID_PARAMETER;
6289 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6290 &secrets_domain_sid);
6291 if (!found_sid || !sid_equal(&secrets_domain_sid,
6292 &ldap_domain_sid)) {
6293 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6294 "%s based on pdb_ldap results %s -> %s\n",
6295 ldap_state->domain_name,
6296 sid_string_dbg(&secrets_domain_sid),
6297 sid_string_dbg(&ldap_domain_sid)));
6299 /* reset secrets.tdb sid */
6300 secrets_store_domain_sid(ldap_state->domain_name,
6301 &ldap_domain_sid);
6302 DEBUG(1, ("New global sam SID: %s\n",
6303 sid_string_dbg(get_global_sam_sid())));
6305 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6306 TALLOC_FREE(domain_sid_string);
6309 alg_rid_base_string = smbldap_talloc_single_attribute(
6310 ldap_state->smbldap_state->ldap_struct,
6311 entry,
6312 get_attr_key2string( dominfo_attr_list,
6313 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6314 talloc_tos());
6315 if (alg_rid_base_string) {
6316 alg_rid_base = (uint32)atol(alg_rid_base_string);
6317 if (alg_rid_base != algorithmic_rid_base()) {
6318 DEBUG(0, ("The value of 'algorithmic RID base' has "
6319 "changed since the LDAP\n"
6320 "database was initialised. Aborting. \n"));
6321 ldap_msgfree(result);
6322 TALLOC_FREE(alg_rid_base_string);
6323 return NT_STATUS_UNSUCCESSFUL;
6325 TALLOC_FREE(alg_rid_base_string);
6327 ldap_msgfree(result);
6329 return NT_STATUS_OK;
6332 NTSTATUS pdb_ldap_init(void)
6334 NTSTATUS nt_status;
6335 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6336 return nt_status;
6338 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
6339 return nt_status;
6341 /* Let pdb_nds register backends */
6342 pdb_nds_init();
6344 return NT_STATUS_OK;