r13622: Allow to rename machine accounts in a Samba Domain. This still uses the
[Samba/nascimento.git] / source3 / passdb / pdb_ldap.c
bloba29097031aad26348ebe888633ebeb6af890db2f
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
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
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 static fstring objclass_filter;
164 switch( schema_ver ) {
165 case SCHEMAVER_SAMBAACCOUNT:
166 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
167 break;
168 case SCHEMAVER_SAMBASAMACCOUNT:
169 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
170 break;
171 default:
172 DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
173 break;
176 return objclass_filter;
179 /*****************************************************************
180 Scan a sequence number off OpenLDAP's syncrepl contextCSN
181 ******************************************************************/
183 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
185 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
186 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
187 LDAPMessage *msg = NULL;
188 LDAPMessage *entry = NULL;
189 TALLOC_CTX *mem_ctx;
190 char **values = NULL;
191 int rc, num_result, num_values, rid;
192 pstring suffix;
193 fstring tok;
194 const char *p;
195 const char **attrs;
197 /* Unfortunatly there is no proper way to detect syncrepl-support in
198 * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
199 * but do not show up in the root-DSE yet. Neither we can query the
200 * subschema-context for the syncProviderSubentry or syncConsumerSubentry
201 * objectclass. Currently we require lp_ldap_suffix() to show up as
202 * namingContext. - Guenther
205 if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
206 return ntstatus;
209 if (!seq_num) {
210 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
211 return ntstatus;
214 if (!smbldap_has_naming_context(ldap_state->smbldap_state, lp_ldap_suffix())) {
215 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
216 "as top-level namingContext\n", lp_ldap_suffix()));
217 return ntstatus;
220 mem_ctx = talloc_init("ldapsam_get_seq_num");
222 if (mem_ctx == NULL)
223 return NT_STATUS_NO_MEMORY;
225 attrs = TALLOC_ARRAY(mem_ctx, const char *, 2);
227 /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
228 rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
229 if (rid > 0) {
231 /* consumer syncreplCookie: */
232 /* csn=20050126161620Z#0000001#00#00000 */
233 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
234 attrs[1] = NULL;
235 pstr_sprintf( suffix, "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
237 } else {
239 /* provider contextCSN */
240 /* 20050126161620Z#000009#00#000000 */
241 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
242 attrs[1] = NULL;
243 pstr_sprintf( suffix, "cn=ldapsync,%s", lp_ldap_suffix());
247 rc = smbldap_search(ldap_state->smbldap_state, suffix,
248 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
250 if (rc != LDAP_SUCCESS) {
251 goto done;
254 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
255 if (num_result != 1) {
256 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
257 goto done;
260 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
261 if (entry == NULL) {
262 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
263 goto done;
266 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
267 if (values == NULL) {
268 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
269 goto done;
272 num_values = ldap_count_values(values);
273 if (num_values == 0) {
274 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
275 goto done;
278 p = values[0];
279 if (!next_token(&p, tok, "#", sizeof(tok))) {
280 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
281 goto done;
284 p = tok;
285 if (!strncmp(p, "csn=", strlen("csn=")))
286 p += strlen("csn=");
288 DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
290 *seq_num = generalized_to_unix_time(p);
292 /* very basic sanity check */
293 if (*seq_num <= 0) {
294 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n",
295 (int)*seq_num));
296 goto done;
299 ntstatus = NT_STATUS_OK;
301 done:
302 if (values != NULL)
303 ldap_value_free(values);
304 if (msg != NULL)
305 ldap_msgfree(msg);
306 if (mem_ctx)
307 talloc_destroy(mem_ctx);
309 return ntstatus;
312 /*******************************************************************
313 Run the search by name.
314 ******************************************************************/
316 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
317 const char *user,
318 LDAPMessage ** result,
319 const char **attr)
321 pstring filter;
322 char *escape_user = escape_ldap_string_alloc(user);
324 if (!escape_user) {
325 return LDAP_NO_MEMORY;
329 * in the filter expression, replace %u with the real name
330 * so in ldap filter, %u MUST exist :-)
332 pstr_sprintf(filter, "(&%s%s)", "(uid=%u)",
333 get_objclass_filter(ldap_state->schema_ver));
336 * have to use this here because $ is filtered out
337 * in pstring_sub
341 all_string_sub(filter, "%u", escape_user, sizeof(pstring));
342 SAFE_FREE(escape_user);
344 return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
347 /*******************************************************************
348 Run the search by rid.
349 ******************************************************************/
351 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
352 uint32 rid, LDAPMessage ** result,
353 const char **attr)
355 pstring filter;
356 int rc;
358 pstr_sprintf(filter, "(&(rid=%i)%s)", rid,
359 get_objclass_filter(ldap_state->schema_ver));
361 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
363 return rc;
366 /*******************************************************************
367 Run the search by SID.
368 ******************************************************************/
370 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
371 const DOM_SID *sid, LDAPMessage ** result,
372 const char **attr)
374 pstring filter;
375 int rc;
376 fstring sid_string;
378 pstr_sprintf(filter, "(&(%s=%s)%s)",
379 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
380 sid_to_string(sid_string, sid),
381 get_objclass_filter(ldap_state->schema_ver));
383 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
385 return rc;
388 /*******************************************************************
389 Delete complete object or objectclass and attrs from
390 object found in search_result depending on lp_ldap_delete_dn
391 ******************************************************************/
393 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
394 TALLOC_CTX *mem_ctx,
395 LDAPMessage *entry,
396 const char *objectclass,
397 const char **attrs)
399 LDAPMod **mods = NULL;
400 char *name;
401 const char *dn;
402 BerElement *ptr = NULL;
404 dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
405 if (dn == NULL) {
406 return LDAP_NO_MEMORY;
409 if (lp_ldap_delete_dn()) {
410 return smbldap_delete(priv->smbldap_state, dn);
413 /* Ok, delete only the SAM attributes */
415 for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
416 name != NULL;
417 name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
418 const char **attrib;
420 /* We are only allowed to delete the attributes that
421 really exist. */
423 for (attrib = attrs; *attrib != NULL; attrib++) {
424 if (strequal(*attrib, name)) {
425 DEBUG(10, ("ldapsam_delete_entry: deleting "
426 "attribute %s\n", name));
427 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
428 NULL);
431 ldap_memfree(name);
434 if (ptr != NULL) {
435 ber_free(ptr, 0);
438 smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
439 talloc_autofree_ldapmod(mem_ctx, mods);
441 return smbldap_modify(priv->smbldap_state, dn, mods);
444 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
446 pstring temp;
447 struct tm tm;
449 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
450 get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
451 temp))
452 return (time_t) 0;
454 strptime(temp, "%Y%m%d%H%M%SZ", &tm);
455 tzset();
456 return timegm(&tm);
459 /**********************************************************************
460 Initialize struct samu from an LDAP query.
461 (Based on init_sam_from_buffer in pdb_tdb.c)
462 *********************************************************************/
464 static BOOL init_sam_from_ldap(struct ldapsam_privates *ldap_state,
465 struct samu * sampass,
466 LDAPMessage * entry)
468 time_t logon_time,
469 logoff_time,
470 kickoff_time,
471 pass_last_set_time,
472 pass_can_change_time,
473 pass_must_change_time,
474 ldap_entry_time,
475 bad_password_time;
476 pstring username,
477 domain,
478 nt_username,
479 fullname,
480 homedir,
481 dir_drive,
482 logon_script,
483 profile_path,
484 acct_desc,
485 workstations;
486 char munged_dial[2048];
487 uint32 user_rid;
488 uint8 smblmpwd[LM_HASH_LEN],
489 smbntpwd[NT_HASH_LEN];
490 BOOL use_samba_attrs = True;
491 uint16 acct_ctrl = 0,
492 logon_divs;
493 uint16 bad_password_count = 0,
494 logon_count = 0;
495 uint32 hours_len;
496 uint8 hours[MAX_HOURS_LEN];
497 pstring temp;
498 LOGIN_CACHE *cache_entry = NULL;
499 uint32 pwHistLen;
500 pstring tmpstring;
501 BOOL expand_explicit = lp_passdb_expand_explicit();
504 * do a little initialization
506 username[0] = '\0';
507 domain[0] = '\0';
508 nt_username[0] = '\0';
509 fullname[0] = '\0';
510 homedir[0] = '\0';
511 dir_drive[0] = '\0';
512 logon_script[0] = '\0';
513 profile_path[0] = '\0';
514 acct_desc[0] = '\0';
515 munged_dial[0] = '\0';
516 workstations[0] = '\0';
519 if (sampass == NULL || ldap_state == NULL || entry == NULL) {
520 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
521 return False;
524 if (priv2ld(ldap_state) == NULL) {
525 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
526 "ldap_struct is NULL!\n"));
527 return False;
530 if (!smbldap_get_single_pstring(priv2ld(ldap_state), entry, "uid",
531 username)) {
532 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
533 "this user!\n"));
534 return False;
537 DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
539 pstrcpy(nt_username, username);
541 pstrcpy(domain, ldap_state->domain_name);
543 pdb_set_username(sampass, username, PDB_SET);
545 pdb_set_domain(sampass, domain, PDB_DEFAULT);
546 pdb_set_nt_username(sampass, nt_username, PDB_SET);
548 /* deal with different attributes between the schema first */
550 if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
551 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
552 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) {
553 pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
556 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
557 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_SID), temp)) {
558 pdb_set_group_sid_from_string(sampass, temp, PDB_SET);
559 } else {
560 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
562 } else {
563 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
564 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) {
565 user_rid = (uint32)atol(temp);
566 pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
569 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
570 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_RID), temp)) {
571 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
572 } else {
573 uint32 group_rid;
575 group_rid = (uint32)atol(temp);
577 /* for some reason, we often have 0 as a primary group RID.
578 Make sure that we treat this just as a 'default' value */
580 if ( group_rid > 0 )
581 pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
582 else
583 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
587 if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
588 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n",
589 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
590 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
591 username));
592 return False;
595 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
596 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) {
597 /* leave as default */
598 } else {
599 pass_last_set_time = (time_t) atol(temp);
600 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
603 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
604 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) {
605 /* leave as default */
606 } else {
607 logon_time = (time_t) atol(temp);
608 pdb_set_logon_time(sampass, logon_time, PDB_SET);
611 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
612 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) {
613 /* leave as default */
614 } else {
615 logoff_time = (time_t) atol(temp);
616 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
619 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
620 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) {
621 /* leave as default */
622 } else {
623 kickoff_time = (time_t) atol(temp);
624 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
627 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
628 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) {
629 /* leave as default */
630 } else {
631 pass_can_change_time = (time_t) atol(temp);
632 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
635 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
636 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) {
637 /* leave as default */
638 } else {
639 pass_must_change_time = (time_t) atol(temp);
640 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
643 /* recommend that 'gecos' and 'displayName' should refer to the same
644 * attribute OID. userFullName depreciated, only used by Samba
645 * primary rules of LDAP: don't make a new attribute when one is already defined
646 * that fits your needs; using cn then displayName rather than 'userFullName'
649 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
650 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), fullname)) {
651 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
652 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) {
653 /* leave as default */
654 } else {
655 pdb_set_fullname(sampass, fullname, PDB_SET);
657 } else {
658 pdb_set_fullname(sampass, fullname, PDB_SET);
661 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
662 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive))
664 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
665 } else {
666 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
669 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
670 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir))
672 pdb_set_homedir( sampass,
673 talloc_sub_basic(sampass, username, lp_logon_home()),
674 PDB_DEFAULT );
675 } else {
676 pstrcpy( tmpstring, homedir );
677 if (expand_explicit) {
678 standard_sub_basic( username, tmpstring,
679 sizeof(tmpstring) );
681 pdb_set_homedir(sampass, tmpstring, PDB_SET);
684 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
685 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script))
687 pdb_set_logon_script( sampass,
688 talloc_sub_basic(sampass, username, lp_logon_script()),
689 PDB_DEFAULT );
690 } else {
691 pstrcpy( tmpstring, logon_script );
692 if (expand_explicit) {
693 standard_sub_basic( username, tmpstring,
694 sizeof(tmpstring) );
696 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
699 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
700 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path))
702 pdb_set_profile_path( sampass,
703 talloc_sub_basic( sampass, username, lp_logon_path()),
704 PDB_DEFAULT );
705 } else {
706 pstrcpy( tmpstring, profile_path );
707 if (expand_explicit) {
708 standard_sub_basic( username, tmpstring,
709 sizeof(tmpstring) );
711 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
714 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
715 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), acct_desc))
717 /* leave as default */
718 } else {
719 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
722 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
723 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), workstations)) {
724 /* leave as default */;
725 } else {
726 pdb_set_workstations(sampass, workstations, PDB_SET);
729 if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
730 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), munged_dial, sizeof(munged_dial))) {
731 /* leave as default */;
732 } else {
733 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
736 /* FIXME: hours stuff should be cleaner */
738 logon_divs = 168;
739 hours_len = 21;
740 memset(hours, 0xff, hours_len);
742 if (ldap_state->is_nds_ldap) {
743 char *user_dn;
744 size_t pwd_len;
745 char clear_text_pw[512];
747 /* Make call to Novell eDirectory ldap extension to get clear text password.
748 NOTE: This will only work if we have an SSL connection to eDirectory. */
749 user_dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
750 if (user_dn != NULL) {
751 DEBUG(3, ("init_sam_from_ldap: smbldap_get_dn(%s) returned '%s'\n", username, user_dn));
753 pwd_len = sizeof(clear_text_pw);
754 if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
755 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
756 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
757 return False;
758 ZERO_STRUCT(smblmpwd);
759 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
760 return False;
761 ZERO_STRUCT(smbntpwd);
762 use_samba_attrs = False;
764 } else {
765 DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
769 if (use_samba_attrs) {
770 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
771 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) {
772 /* leave as default */
773 } else {
774 pdb_gethexpwd(temp, smblmpwd);
775 memset((char *)temp, '\0', strlen(temp)+1);
776 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
777 return False;
778 ZERO_STRUCT(smblmpwd);
781 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
782 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), temp)) {
783 /* leave as default */
784 } else {
785 pdb_gethexpwd(temp, smbntpwd);
786 memset((char *)temp, '\0', strlen(temp)+1);
787 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
788 return False;
789 ZERO_STRUCT(smbntpwd);
793 pwHistLen = 0;
795 pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
796 if (pwHistLen > 0){
797 uint8 *pwhist = NULL;
798 int i;
800 /* We can only store (sizeof(pstring)-1)/64 password history entries. */
801 pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
803 if ((pwhist = SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN)) == NULL){
804 DEBUG(0, ("init_sam_from_ldap: malloc failed!\n"));
805 return False;
807 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
809 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
810 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), temp)) {
811 /* leave as default - zeros */
812 } else {
813 BOOL hex_failed = False;
814 for (i = 0; i < pwHistLen; i++){
815 /* Get the 16 byte salt. */
816 if (!pdb_gethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
817 hex_failed = True;
818 break;
820 /* Get the 16 byte MD5 hash of salt+passwd. */
821 if (!pdb_gethexpwd(&temp[(i*64)+32],
822 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN])) {
823 hex_failed = True;
824 break;
827 if (hex_failed) {
828 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
829 username));
830 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
833 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
834 SAFE_FREE(pwhist);
835 return False;
837 SAFE_FREE(pwhist);
840 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
841 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
842 acct_ctrl |= ACB_NORMAL;
843 } else {
844 acct_ctrl = pdb_decode_acct_ctrl(temp);
846 if (acct_ctrl == 0)
847 acct_ctrl |= ACB_NORMAL;
849 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
852 pdb_set_hours_len(sampass, hours_len, PDB_SET);
853 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
855 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
856 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
857 /* leave as default */
858 } else {
859 bad_password_count = (uint32) atol(temp);
860 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
863 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
864 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
865 /* leave as default */
866 } else {
867 bad_password_time = (time_t) atol(temp);
868 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
872 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
873 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
874 /* leave as default */
875 } else {
876 logon_count = (uint32) atol(temp);
877 pdb_set_logon_count(sampass, logon_count, PDB_SET);
880 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
882 if(!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
883 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_HOURS), temp)) {
884 /* leave as default */
885 } else {
886 pdb_gethexhours(temp, hours);
887 memset((char *)temp, '\0', strlen(temp) +1);
888 pdb_set_hours(sampass, hours, PDB_SET);
889 ZERO_STRUCT(hours);
892 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
893 if (smbldap_get_single_pstring(priv2ld(ldap_state), entry,
894 "uidNumber", temp)) {
895 /* We've got a uid, feed the cache */
896 uid_t uid = strtoul(temp, NULL, 10);
897 store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
901 /* check the timestamp of the cache vs ldap entry */
902 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
903 entry)))
904 return True;
906 /* see if we have newer updates */
907 if (!(cache_entry = login_cache_read(sampass))) {
908 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
909 (unsigned int)pdb_get_bad_password_count(sampass),
910 (unsigned int)pdb_get_bad_password_time(sampass)));
911 return True;
914 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
915 (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp,
916 (unsigned int)cache_entry->bad_password_time));
918 if (ldap_entry_time > cache_entry->entry_timestamp) {
919 /* cache is older than directory , so
920 we need to delete the entry but allow the
921 fields to be written out */
922 login_cache_delentry(sampass);
923 } else {
924 /* read cache in */
925 pdb_set_acct_ctrl(sampass,
926 pdb_get_acct_ctrl(sampass) |
927 (cache_entry->acct_ctrl & ACB_AUTOLOCK),
928 PDB_SET);
929 pdb_set_bad_password_count(sampass,
930 cache_entry->bad_password_count,
931 PDB_SET);
932 pdb_set_bad_password_time(sampass,
933 cache_entry->bad_password_time,
934 PDB_SET);
937 SAFE_FREE(cache_entry);
938 return True;
941 /**********************************************************************
942 Initialize the ldap db from a struct samu. Called on update.
943 (Based on init_buffer_from_sam in pdb_tdb.c)
944 *********************************************************************/
946 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state,
947 LDAPMessage *existing,
948 LDAPMod *** mods, struct samu * sampass,
949 BOOL (*need_update)(const struct samu *,
950 enum pdb_elements))
952 pstring temp;
953 uint32 rid;
955 if (mods == NULL || sampass == NULL) {
956 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
957 return False;
960 *mods = NULL;
963 * took out adding "objectclass: sambaAccount"
964 * do this on a per-mod basis
966 if (need_update(sampass, PDB_USERNAME))
967 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
968 "uid", pdb_get_username(sampass));
970 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
972 /* only update the RID if we actually need to */
973 if (need_update(sampass, PDB_USERSID)) {
974 fstring sid_string;
975 fstring dom_sid_string;
976 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
978 switch ( ldap_state->schema_ver ) {
979 case SCHEMAVER_SAMBAACCOUNT:
980 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
981 DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
982 sid_to_string(sid_string, user_sid),
983 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
984 return False;
986 slprintf(temp, sizeof(temp) - 1, "%i", rid);
987 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
988 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
989 temp);
990 break;
992 case SCHEMAVER_SAMBASAMACCOUNT:
993 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
994 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
995 sid_to_string(sid_string, user_sid));
996 break;
998 default:
999 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1000 break;
1004 /* we don't need to store the primary group RID - so leaving it
1005 'free' to hang off the unix primary group makes life easier */
1007 if (need_update(sampass, PDB_GROUPSID)) {
1008 fstring sid_string;
1009 fstring dom_sid_string;
1010 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1012 switch ( ldap_state->schema_ver ) {
1013 case SCHEMAVER_SAMBAACCOUNT:
1014 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1015 DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1016 sid_to_string(sid_string, group_sid),
1017 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
1018 return False;
1021 slprintf(temp, sizeof(temp) - 1, "%i", rid);
1022 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1023 get_userattr_key2string(ldap_state->schema_ver,
1024 LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1025 break;
1027 case SCHEMAVER_SAMBASAMACCOUNT:
1028 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1029 get_userattr_key2string(ldap_state->schema_ver,
1030 LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
1031 break;
1033 default:
1034 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1035 break;
1040 /* displayName, cn, and gecos should all be the same
1041 * most easily accomplished by giving them the same OID
1042 * gecos isn't set here b/c it should be handled by the
1043 * add-user script
1044 * We change displayName only and fall back to cn if
1045 * it does not exist.
1048 if (need_update(sampass, PDB_FULLNAME))
1049 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1050 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME),
1051 pdb_get_fullname(sampass));
1053 if (need_update(sampass, PDB_ACCTDESC))
1054 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1055 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC),
1056 pdb_get_acct_desc(sampass));
1058 if (need_update(sampass, PDB_WORKSTATIONS))
1059 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1060 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS),
1061 pdb_get_workstations(sampass));
1063 if (need_update(sampass, PDB_MUNGEDDIAL))
1064 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1065 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL),
1066 pdb_get_munged_dial(sampass));
1068 if (need_update(sampass, PDB_SMBHOME))
1069 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1070 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH),
1071 pdb_get_homedir(sampass));
1073 if (need_update(sampass, PDB_DRIVE))
1074 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1075 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE),
1076 pdb_get_dir_drive(sampass));
1078 if (need_update(sampass, PDB_LOGONSCRIPT))
1079 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1080 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT),
1081 pdb_get_logon_script(sampass));
1083 if (need_update(sampass, PDB_PROFILE))
1084 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1085 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH),
1086 pdb_get_profile_path(sampass));
1088 slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
1089 if (need_update(sampass, PDB_LOGONTIME))
1090 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1091 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1093 slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
1094 if (need_update(sampass, PDB_LOGOFFTIME))
1095 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1096 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1098 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
1099 if (need_update(sampass, PDB_KICKOFFTIME))
1100 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1101 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1103 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
1104 if (need_update(sampass, PDB_CANCHANGETIME))
1105 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1106 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1108 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
1109 if (need_update(sampass, PDB_MUSTCHANGETIME))
1110 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1111 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1114 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1115 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1117 if (need_update(sampass, PDB_LMPASSWD)) {
1118 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1119 if (lm_pw) {
1120 pdb_sethexpwd(temp, lm_pw,
1121 pdb_get_acct_ctrl(sampass));
1122 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1123 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1124 temp);
1125 } else {
1126 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1127 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1128 NULL);
1131 if (need_update(sampass, PDB_NTPASSWD)) {
1132 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1133 if (nt_pw) {
1134 pdb_sethexpwd(temp, nt_pw,
1135 pdb_get_acct_ctrl(sampass));
1136 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1137 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1138 temp);
1139 } else {
1140 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1141 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1142 NULL);
1146 if (need_update(sampass, PDB_PWHISTORY)) {
1147 uint32 pwHistLen = 0;
1148 pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1149 if (pwHistLen == 0) {
1150 /* Remove any password history from the LDAP store. */
1151 memset(temp, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1152 temp[64] = '\0';
1153 } else {
1154 int i;
1155 uint32 currHistLen = 0;
1156 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1157 if (pwhist != NULL) {
1158 /* We can only store (sizeof(pstring)-1)/64 password history entries. */
1159 pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
1160 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1161 /* Store the salt. */
1162 pdb_sethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1163 /* Followed by the md5 hash of salt + md4 hash */
1164 pdb_sethexpwd(&temp[(i*64)+32],
1165 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1166 DEBUG(100, ("temp=%s\n", temp));
1170 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1171 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1172 temp);
1175 if (need_update(sampass, PDB_PASSLASTSET)) {
1176 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
1177 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1178 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1179 temp);
1183 if (need_update(sampass, PDB_HOURS)) {
1184 const uint8 *hours = pdb_get_hours(sampass);
1185 if (hours) {
1186 pdb_sethexhours(temp, hours);
1187 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1188 existing,
1189 mods,
1190 get_userattr_key2string(ldap_state->schema_ver,
1191 LDAP_ATTR_LOGON_HOURS),
1192 temp);
1196 if (need_update(sampass, PDB_ACCTCTRL))
1197 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1198 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1199 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1201 /* password lockout cache:
1202 - If we are now autolocking or clearing, we write to ldap
1203 - If we are clearing, we delete the cache entry
1204 - If the count is > 0, we update the cache
1206 This even means when autolocking, we cache, just in case the
1207 update doesn't work, and we have to cache the autolock flag */
1209 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1210 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1211 uint16 badcount = pdb_get_bad_password_count(sampass);
1212 time_t badtime = pdb_get_bad_password_time(sampass);
1213 uint32 pol;
1214 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1216 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1217 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1219 if ((badcount >= pol) || (badcount == 0)) {
1220 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1221 (unsigned int)badcount, (unsigned int)badtime));
1222 slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1223 smbldap_make_mod(
1224 ldap_state->smbldap_state->ldap_struct,
1225 existing, mods,
1226 get_userattr_key2string(
1227 ldap_state->schema_ver,
1228 LDAP_ATTR_BAD_PASSWORD_COUNT),
1229 temp);
1231 slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1232 smbldap_make_mod(
1233 ldap_state->smbldap_state->ldap_struct,
1234 existing, mods,
1235 get_userattr_key2string(
1236 ldap_state->schema_ver,
1237 LDAP_ATTR_BAD_PASSWORD_TIME),
1238 temp);
1240 if (badcount == 0) {
1241 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1242 login_cache_delentry(sampass);
1243 } else {
1244 LOGIN_CACHE cache_entry;
1246 cache_entry.entry_timestamp = time(NULL);
1247 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1248 cache_entry.bad_password_count = badcount;
1249 cache_entry.bad_password_time = badtime;
1251 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1252 login_cache_write(sampass, cache_entry);
1256 return True;
1259 /**********************************************************************
1260 Connect to LDAP server for password enumeration.
1261 *********************************************************************/
1263 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update, uint16 acb_mask)
1265 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1266 int rc;
1267 pstring filter, suffix;
1268 const char **attr_list;
1269 BOOL machine_mask = False, user_mask = False;
1271 pstr_sprintf( filter, "(&%s%s)", "(uid=%u)",
1272 get_objclass_filter(ldap_state->schema_ver));
1273 all_string_sub(filter, "%u", "*", sizeof(pstring));
1275 machine_mask = ((acb_mask != 0) && (acb_mask & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)));
1276 user_mask = ((acb_mask != 0) && (acb_mask & ACB_NORMAL));
1278 if (machine_mask) {
1279 pstrcpy(suffix, lp_ldap_machine_suffix());
1280 } else if (user_mask) {
1281 pstrcpy(suffix, lp_ldap_user_suffix());
1282 } else {
1283 pstrcpy(suffix, lp_ldap_suffix());
1286 DEBUG(10,("ldapsam_setsampwent: LDAP Query for acb_mask 0x%x will use suffix %s\n",
1287 acb_mask, suffix));
1289 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1290 rc = smbldap_search(ldap_state->smbldap_state, suffix, LDAP_SCOPE_SUBTREE, filter,
1291 attr_list, 0, &ldap_state->result);
1292 TALLOC_FREE( attr_list );
1294 if (rc != LDAP_SUCCESS) {
1295 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1296 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", suffix, filter));
1297 ldap_msgfree(ldap_state->result);
1298 ldap_state->result = NULL;
1299 return NT_STATUS_UNSUCCESSFUL;
1302 DEBUG(2, ("ldapsam_setsampwent: %d entries in the base %s\n",
1303 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
1304 ldap_state->result), suffix));
1306 ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1307 ldap_state->result);
1308 ldap_state->index = 0;
1310 return NT_STATUS_OK;
1313 /**********************************************************************
1314 End enumeration of the LDAP password list.
1315 *********************************************************************/
1317 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1319 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1320 if (ldap_state->result) {
1321 ldap_msgfree(ldap_state->result);
1322 ldap_state->result = NULL;
1326 /**********************************************************************
1327 Get the next entry in the LDAP password database.
1328 *********************************************************************/
1330 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods,
1331 struct samu *user)
1333 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1334 struct ldapsam_privates *ldap_state =
1335 (struct ldapsam_privates *)my_methods->private_data;
1336 BOOL bret = False;
1338 while (!bret) {
1339 if (!ldap_state->entry)
1340 return ret;
1342 ldap_state->index++;
1343 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1345 ldap_state->entry = ldap_next_entry(priv2ld(ldap_state),
1346 ldap_state->entry);
1349 return NT_STATUS_OK;
1352 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1353 const char *new_attr)
1355 int i;
1357 if (new_attr == NULL) {
1358 return;
1361 for (i=0; (*attr_list)[i] != NULL; i++) {
1365 (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1366 const char *, i+2);
1367 SMB_ASSERT((*attr_list) != NULL);
1368 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1369 (*attr_list)[i+1] = NULL;
1372 /**********************************************************************
1373 Get struct samu entry from LDAP by username.
1374 *********************************************************************/
1376 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1378 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1379 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1380 LDAPMessage *result = NULL;
1381 LDAPMessage *entry = NULL;
1382 int count;
1383 const char ** attr_list;
1384 int rc;
1386 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1387 append_attr(user, &attr_list,
1388 get_userattr_key2string(ldap_state->schema_ver,
1389 LDAP_ATTR_MOD_TIMESTAMP));
1390 append_attr(user, &attr_list, "uidNumber");
1391 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1392 attr_list);
1393 TALLOC_FREE( attr_list );
1395 if ( rc != LDAP_SUCCESS )
1396 return NT_STATUS_NO_SUCH_USER;
1398 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1400 if (count < 1) {
1401 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1402 ldap_msgfree(result);
1403 return NT_STATUS_NO_SUCH_USER;
1404 } else if (count > 1) {
1405 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1406 ldap_msgfree(result);
1407 return NT_STATUS_NO_SUCH_USER;
1410 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1411 if (entry) {
1412 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1413 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1414 ldap_msgfree(result);
1415 return NT_STATUS_NO_SUCH_USER;
1417 pdb_set_backend_private_data(user, result, NULL,
1418 my_methods, PDB_CHANGED);
1419 talloc_autofree_ldapmsg(user, result);
1420 ret = NT_STATUS_OK;
1421 } else {
1422 ldap_msgfree(result);
1424 return ret;
1427 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1428 const DOM_SID *sid, LDAPMessage **result)
1430 int rc = -1;
1431 const char ** attr_list;
1432 uint32 rid;
1434 switch ( ldap_state->schema_ver ) {
1435 case SCHEMAVER_SAMBASAMACCOUNT: {
1436 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1437 if (tmp_ctx == NULL) {
1438 return LDAP_NO_MEMORY;
1441 attr_list = get_userattr_list(tmp_ctx,
1442 ldap_state->schema_ver);
1443 append_attr(tmp_ctx, &attr_list,
1444 get_userattr_key2string(
1445 ldap_state->schema_ver,
1446 LDAP_ATTR_MOD_TIMESTAMP));
1447 append_attr(tmp_ctx, &attr_list, "uidNumber");
1448 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1449 result, attr_list);
1450 TALLOC_FREE(tmp_ctx);
1452 if ( rc != LDAP_SUCCESS )
1453 return rc;
1454 break;
1457 case SCHEMAVER_SAMBAACCOUNT:
1458 if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1459 return rc;
1462 attr_list = get_userattr_list(NULL,
1463 ldap_state->schema_ver);
1464 rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1465 TALLOC_FREE( attr_list );
1467 if ( rc != LDAP_SUCCESS )
1468 return rc;
1469 break;
1471 return rc;
1474 /**********************************************************************
1475 Get struct samu entry from LDAP by SID.
1476 *********************************************************************/
1478 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1480 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1481 LDAPMessage *result = NULL;
1482 LDAPMessage *entry = NULL;
1483 int count;
1484 int rc;
1485 fstring sid_string;
1487 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1488 sid, &result);
1489 if (rc != LDAP_SUCCESS)
1490 return NT_STATUS_NO_SUCH_USER;
1492 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1494 if (count < 1) {
1495 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1496 count));
1497 ldap_msgfree(result);
1498 return NT_STATUS_NO_SUCH_USER;
1499 } else if (count > 1) {
1500 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1501 count));
1502 ldap_msgfree(result);
1503 return NT_STATUS_NO_SUCH_USER;
1506 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1507 if (!entry) {
1508 ldap_msgfree(result);
1509 return NT_STATUS_NO_SUCH_USER;
1512 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1513 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1514 ldap_msgfree(result);
1515 return NT_STATUS_NO_SUCH_USER;
1518 pdb_set_backend_private_data(user, result, NULL,
1519 my_methods, PDB_CHANGED);
1520 talloc_autofree_ldapmsg(user, result);
1521 return NT_STATUS_OK;
1524 static BOOL ldapsam_can_pwchange_exop(struct smbldap_state *ldap_state)
1526 return smbldap_has_extension(ldap_state, LDAP_EXOP_MODIFY_PASSWD);
1529 /********************************************************************
1530 Do the actual modification - also change a plaintext passord if
1531 it it set.
1532 **********************************************************************/
1534 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1535 struct samu *newpwd, char *dn,
1536 LDAPMod **mods, int ldap_op,
1537 BOOL (*need_update)(const struct samu *, enum pdb_elements))
1539 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1540 int rc;
1542 if (!my_methods || !newpwd || !dn) {
1543 return NT_STATUS_INVALID_PARAMETER;
1546 if (!mods) {
1547 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1548 /* may be password change below however */
1549 } else {
1550 switch(ldap_op) {
1551 case LDAP_MOD_ADD:
1552 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1553 "objectclass",
1554 LDAP_OBJ_ACCOUNT);
1555 rc = smbldap_add(ldap_state->smbldap_state,
1556 dn, mods);
1557 break;
1558 case LDAP_MOD_REPLACE:
1559 rc = smbldap_modify(ldap_state->smbldap_state,
1560 dn ,mods);
1561 break;
1562 default:
1563 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1564 ldap_op));
1565 return NT_STATUS_INVALID_PARAMETER;
1568 if (rc!=LDAP_SUCCESS) {
1569 return NT_STATUS_UNSUCCESSFUL;
1573 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1574 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1575 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1576 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1577 BerElement *ber;
1578 struct berval *bv;
1579 char *retoid = NULL;
1580 struct berval *retdata = NULL;
1581 char *utf8_password;
1582 char *utf8_dn;
1584 if (!ldap_state->is_nds_ldap) {
1585 if (!ldapsam_can_pwchange_exop(ldap_state->smbldap_state)) {
1586 DEBUG(2, ("ldap password change requested, but LDAP "
1587 "server does not support it -- ignoring\n"));
1588 return NT_STATUS_OK;
1592 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1593 return NT_STATUS_NO_MEMORY;
1596 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1597 return NT_STATUS_NO_MEMORY;
1600 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1601 DEBUG(0,("ber_alloc_t returns NULL\n"));
1602 SAFE_FREE(utf8_password);
1603 return NT_STATUS_UNSUCCESSFUL;
1606 ber_printf (ber, "{");
1607 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1608 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1609 ber_printf (ber, "N}");
1611 if ((rc = ber_flatten (ber, &bv))<0) {
1612 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1613 ber_free(ber,1);
1614 SAFE_FREE(utf8_dn);
1615 SAFE_FREE(utf8_password);
1616 return NT_STATUS_UNSUCCESSFUL;
1619 SAFE_FREE(utf8_dn);
1620 SAFE_FREE(utf8_password);
1621 ber_free(ber, 1);
1623 if (!ldap_state->is_nds_ldap) {
1624 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1625 LDAP_EXOP_MODIFY_PASSWD,
1626 bv, NULL, NULL, &retoid,
1627 &retdata);
1628 } else {
1629 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1630 pdb_get_plaintext_passwd(newpwd));
1632 if (rc != LDAP_SUCCESS) {
1633 char *ld_error = NULL;
1635 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1636 DEBUG(3, ("Could not set userPassword "
1637 "attribute due to an objectClass "
1638 "violation -- ignoring\n"));
1639 ber_bvfree(bv);
1640 return NT_STATUS_OK;
1643 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1644 &ld_error);
1645 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1646 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1647 SAFE_FREE(ld_error);
1648 ber_bvfree(bv);
1649 return NT_STATUS_UNSUCCESSFUL;
1650 } else {
1651 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1652 #ifdef DEBUG_PASSWORD
1653 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1654 #endif
1655 if (retdata)
1656 ber_bvfree(retdata);
1657 if (retoid)
1658 ldap_memfree(retoid);
1660 ber_bvfree(bv);
1662 return NT_STATUS_OK;
1665 /**********************************************************************
1666 Delete entry from LDAP for username.
1667 *********************************************************************/
1669 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1670 struct samu * sam_acct)
1672 struct ldapsam_privates *priv =
1673 (struct ldapsam_privates *)my_methods->private_data;
1674 const char *sname;
1675 int rc;
1676 LDAPMessage *msg, *entry;
1677 NTSTATUS result = NT_STATUS_NO_MEMORY;
1678 const char **attr_list;
1679 TALLOC_CTX *mem_ctx;
1681 if (!sam_acct) {
1682 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1683 return NT_STATUS_INVALID_PARAMETER;
1686 sname = pdb_get_username(sam_acct);
1688 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1689 "LDAP.\n", sname));
1691 mem_ctx = talloc_new(NULL);
1692 if (mem_ctx == NULL) {
1693 DEBUG(0, ("talloc_new failed\n"));
1694 goto done;
1697 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1698 if (attr_list == NULL) {
1699 goto done;
1702 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1704 if ((rc != LDAP_SUCCESS) ||
1705 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1706 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1707 DEBUG(5, ("Could not find user %s\n", sname));
1708 result = NT_STATUS_NO_SUCH_USER;
1709 goto done;
1712 rc = ldapsam_delete_entry(
1713 priv, mem_ctx, entry,
1714 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1715 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1716 attr_list);
1718 result = (rc == LDAP_SUCCESS) ?
1719 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1721 done:
1722 TALLOC_FREE(mem_ctx);
1723 return result;
1726 /**********************************************************************
1727 Helper function to determine for update_sam_account whether
1728 we need LDAP modification.
1729 *********************************************************************/
1731 static BOOL element_is_changed(const struct samu *sampass,
1732 enum pdb_elements element)
1734 return IS_SAM_CHANGED(sampass, element);
1737 /**********************************************************************
1738 Update struct samu.
1739 *********************************************************************/
1741 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1743 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1744 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1745 int rc = 0;
1746 char *dn;
1747 LDAPMessage *result = NULL;
1748 LDAPMessage *entry = NULL;
1749 LDAPMod **mods = NULL;
1750 const char **attr_list;
1752 result = pdb_get_backend_private_data(newpwd, my_methods);
1753 if (!result) {
1754 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1755 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1756 TALLOC_FREE( attr_list );
1757 if (rc != LDAP_SUCCESS) {
1758 return NT_STATUS_UNSUCCESSFUL;
1760 pdb_set_backend_private_data(newpwd, result, NULL,
1761 my_methods, PDB_CHANGED);
1762 talloc_autofree_ldapmsg(newpwd, result);
1765 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1766 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1767 return NT_STATUS_UNSUCCESSFUL;
1770 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1771 dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1772 if (!dn) {
1773 return NT_STATUS_UNSUCCESSFUL;
1776 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1778 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1779 element_is_changed)) {
1780 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1781 SAFE_FREE(dn);
1782 if (mods != NULL)
1783 ldap_mods_free(mods,True);
1784 return NT_STATUS_UNSUCCESSFUL;
1787 if (mods == NULL) {
1788 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1789 pdb_get_username(newpwd)));
1790 SAFE_FREE(dn);
1791 return NT_STATUS_OK;
1794 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1795 ldap_mods_free(mods,True);
1796 SAFE_FREE(dn);
1798 if (!NT_STATUS_IS_OK(ret)) {
1799 return ret;
1802 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1803 pdb_get_username(newpwd)));
1804 return NT_STATUS_OK;
1807 /***************************************************************************
1808 Renames a struct samu
1809 - The "rename user script" has full responsibility for changing everything
1810 ***************************************************************************/
1812 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1813 struct samu *old_acct,
1814 const char *newname)
1816 const char *oldname;
1817 int rc;
1818 pstring rename_script;
1820 if (!old_acct) {
1821 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1822 return NT_STATUS_INVALID_PARAMETER;
1824 if (!newname) {
1825 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1826 return NT_STATUS_INVALID_PARAMETER;
1829 oldname = pdb_get_username(old_acct);
1831 /* rename the posix user */
1832 pstrcpy(rename_script, lp_renameuser_script());
1834 if (!(*rename_script))
1835 return NT_STATUS_ACCESS_DENIED;
1837 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
1838 oldname, newname));
1840 /* we have to allow the account name to end with a '$' */
1841 string_sub2(rename_script, "%unew", newname, sizeof(pstring),
1842 True, False, True);
1843 string_sub2(rename_script, "%uold", oldname, sizeof(pstring),
1844 True, False, True);
1845 rc = smbrun(rename_script, NULL);
1847 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
1848 rename_script, rc));
1850 if (rc)
1851 return NT_STATUS_UNSUCCESSFUL;
1853 return NT_STATUS_OK;
1856 /**********************************************************************
1857 Helper function to determine for update_sam_account whether
1858 we need LDAP modification.
1859 *********************************************************************/
1861 static BOOL element_is_set_or_changed(const struct samu *sampass,
1862 enum pdb_elements element)
1864 return (IS_SAM_SET(sampass, element) ||
1865 IS_SAM_CHANGED(sampass, element));
1868 /**********************************************************************
1869 Add struct samu to LDAP.
1870 *********************************************************************/
1872 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1874 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1875 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1876 int rc;
1877 LDAPMessage *result = NULL;
1878 LDAPMessage *entry = NULL;
1879 pstring dn;
1880 LDAPMod **mods = NULL;
1881 int ldap_op = LDAP_MOD_REPLACE;
1882 uint32 num_result;
1883 const char **attr_list;
1884 char *escape_user;
1885 const char *username = pdb_get_username(newpwd);
1886 const DOM_SID *sid = pdb_get_user_sid(newpwd);
1887 pstring filter;
1888 fstring sid_string;
1890 if (!username || !*username) {
1891 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1892 return NT_STATUS_INVALID_PARAMETER;
1895 /* free this list after the second search or in case we exit on failure */
1896 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1898 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1900 if (rc != LDAP_SUCCESS) {
1901 TALLOC_FREE( attr_list );
1902 return NT_STATUS_UNSUCCESSFUL;
1905 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1906 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
1907 username));
1908 ldap_msgfree(result);
1909 TALLOC_FREE( attr_list );
1910 return NT_STATUS_UNSUCCESSFUL;
1912 ldap_msgfree(result);
1913 result = NULL;
1915 if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1916 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1917 sid, &result);
1918 if (rc == LDAP_SUCCESS) {
1919 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1920 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n",
1921 sid_to_string(sid_string, sid)));
1922 TALLOC_FREE( attr_list );
1923 ldap_msgfree(result);
1924 return NT_STATUS_UNSUCCESSFUL;
1926 ldap_msgfree(result);
1930 /* does the entry already exist but without a samba attributes?
1931 we need to return the samba attributes here */
1933 escape_user = escape_ldap_string_alloc( username );
1934 pstrcpy( filter, "(uid=%u)" );
1935 all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1936 SAFE_FREE( escape_user );
1938 rc = smbldap_search_suffix(ldap_state->smbldap_state,
1939 filter, attr_list, &result);
1940 if ( rc != LDAP_SUCCESS ) {
1941 TALLOC_FREE( attr_list );
1942 return NT_STATUS_UNSUCCESSFUL;
1945 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1947 if (num_result > 1) {
1948 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1949 TALLOC_FREE( attr_list );
1950 ldap_msgfree(result);
1951 return NT_STATUS_UNSUCCESSFUL;
1954 /* Check if we need to update an existing entry */
1955 if (num_result == 1) {
1956 char *tmp;
1958 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1959 ldap_op = LDAP_MOD_REPLACE;
1960 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1961 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1962 if (!tmp) {
1963 TALLOC_FREE( attr_list );
1964 ldap_msgfree(result);
1965 return NT_STATUS_UNSUCCESSFUL;
1967 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1968 SAFE_FREE(tmp);
1970 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1972 /* There might be a SID for this account already - say an idmap entry */
1974 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
1975 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1976 sid_to_string(sid_string, sid),
1977 LDAP_OBJ_IDMAP_ENTRY,
1978 LDAP_OBJ_SID_ENTRY);
1980 /* free old result before doing a new search */
1981 if (result != NULL) {
1982 ldap_msgfree(result);
1983 result = NULL;
1985 rc = smbldap_search_suffix(ldap_state->smbldap_state,
1986 filter, attr_list, &result);
1988 if ( rc != LDAP_SUCCESS ) {
1989 TALLOC_FREE( attr_list );
1990 return NT_STATUS_UNSUCCESSFUL;
1993 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1995 if (num_result > 1) {
1996 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1997 TALLOC_FREE( attr_list );
1998 ldap_msgfree(result);
1999 return NT_STATUS_UNSUCCESSFUL;
2002 /* Check if we need to update an existing entry */
2003 if (num_result == 1) {
2004 char *tmp;
2006 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2007 ldap_op = LDAP_MOD_REPLACE;
2008 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2009 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2010 if (!tmp) {
2011 TALLOC_FREE( attr_list );
2012 ldap_msgfree(result);
2013 return NT_STATUS_UNSUCCESSFUL;
2015 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
2016 SAFE_FREE(tmp);
2020 TALLOC_FREE( attr_list );
2022 if (num_result == 0) {
2023 /* Check if we need to add an entry */
2024 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2025 ldap_op = LDAP_MOD_ADD;
2026 if (username[strlen(username)-1] == '$') {
2027 slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
2028 } else {
2029 slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
2033 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2034 element_is_set_or_changed)) {
2035 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2036 ldap_msgfree(result);
2037 if (mods != NULL)
2038 ldap_mods_free(mods,True);
2039 return NT_STATUS_UNSUCCESSFUL;
2042 ldap_msgfree(result);
2044 if (mods == NULL) {
2045 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2046 return NT_STATUS_UNSUCCESSFUL;
2048 switch ( ldap_state->schema_ver ) {
2049 case SCHEMAVER_SAMBAACCOUNT:
2050 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2051 break;
2052 case SCHEMAVER_SAMBASAMACCOUNT:
2053 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2054 break;
2055 default:
2056 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2057 break;
2060 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2061 if (!NT_STATUS_IS_OK(ret)) {
2062 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2063 pdb_get_username(newpwd),dn));
2064 ldap_mods_free(mods, True);
2065 return ret;
2068 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2069 ldap_mods_free(mods, True);
2071 return NT_STATUS_OK;
2074 /**********************************************************************
2075 *********************************************************************/
2077 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2078 const char *filter,
2079 LDAPMessage ** result)
2081 int scope = LDAP_SCOPE_SUBTREE;
2082 int rc;
2083 const char **attr_list;
2085 attr_list = get_attr_list(NULL, groupmap_attr_list);
2086 rc = smbldap_search(ldap_state->smbldap_state,
2087 lp_ldap_group_suffix (), scope,
2088 filter, attr_list, 0, result);
2089 TALLOC_FREE(attr_list);
2091 return rc;
2094 /**********************************************************************
2095 *********************************************************************/
2097 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
2098 GROUP_MAP *map, LDAPMessage *entry)
2100 pstring temp;
2102 if (ldap_state == NULL || map == NULL || entry == NULL ||
2103 ldap_state->smbldap_state->ldap_struct == NULL) {
2104 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2105 return False;
2108 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
2109 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
2110 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2111 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2112 return False;
2114 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2116 map->gid = (gid_t)atol(temp);
2118 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
2119 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2120 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2121 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2122 return False;
2125 if (!string_to_sid(&map->sid, temp)) {
2126 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2127 return False;
2130 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
2131 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2132 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2133 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2134 return False;
2136 map->sid_name_use = (enum SID_NAME_USE)atol(temp);
2138 if ((map->sid_name_use < SID_NAME_USER) ||
2139 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2140 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2141 return False;
2144 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
2145 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2146 temp[0] = '\0';
2147 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
2148 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp))
2150 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2151 for gidNumber(%lu)\n",(unsigned long)map->gid));
2152 return False;
2155 fstrcpy(map->nt_name, temp);
2157 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
2158 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2159 temp[0] = '\0';
2161 fstrcpy(map->comment, temp);
2163 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
2164 store_gid_sid_cache(&map->sid, map->gid);
2167 return True;
2170 /**********************************************************************
2171 *********************************************************************/
2173 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2174 const char *filter,
2175 GROUP_MAP *map)
2177 struct ldapsam_privates *ldap_state =
2178 (struct ldapsam_privates *)methods->private_data;
2179 LDAPMessage *result = NULL;
2180 LDAPMessage *entry = NULL;
2181 int count;
2183 if (ldapsam_search_one_group(ldap_state, filter, &result)
2184 != LDAP_SUCCESS) {
2185 return NT_STATUS_NO_SUCH_GROUP;
2188 count = ldap_count_entries(priv2ld(ldap_state), result);
2190 if (count < 1) {
2191 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2192 ldap_msgfree(result);
2193 return NT_STATUS_NO_SUCH_GROUP;
2196 if (count > 1) {
2197 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2198 "count=%d\n", filter, count));
2199 ldap_msgfree(result);
2200 return NT_STATUS_NO_SUCH_GROUP;
2203 entry = ldap_first_entry(priv2ld(ldap_state), result);
2205 if (!entry) {
2206 ldap_msgfree(result);
2207 return NT_STATUS_UNSUCCESSFUL;
2210 if (!init_group_from_ldap(ldap_state, map, entry)) {
2211 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2212 "group filter %s\n", filter));
2213 ldap_msgfree(result);
2214 return NT_STATUS_NO_SUCH_GROUP;
2217 ldap_msgfree(result);
2218 return NT_STATUS_OK;
2221 /**********************************************************************
2222 *********************************************************************/
2224 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2225 DOM_SID sid)
2227 pstring filter;
2229 pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2230 LDAP_OBJ_GROUPMAP,
2231 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2232 sid_string_static(&sid));
2234 return ldapsam_getgroup(methods, filter, map);
2237 /**********************************************************************
2238 *********************************************************************/
2240 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2241 gid_t gid)
2243 pstring filter;
2245 pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
2246 LDAP_OBJ_GROUPMAP,
2247 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2248 (unsigned long)gid);
2250 return ldapsam_getgroup(methods, filter, map);
2253 /**********************************************************************
2254 *********************************************************************/
2256 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2257 const char *name)
2259 pstring filter;
2260 char *escape_name = escape_ldap_string_alloc(name);
2262 if (!escape_name) {
2263 return NT_STATUS_NO_MEMORY;
2266 pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2267 LDAP_OBJ_GROUPMAP,
2268 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2269 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2271 SAFE_FREE(escape_name);
2273 return ldapsam_getgroup(methods, filter, map);
2276 static void add_rid_to_array_unique(TALLOC_CTX *mem_ctx,
2277 uint32 rid, uint32 **pp_rids, size_t *p_num)
2279 size_t i;
2281 for (i=0; i<*p_num; i++) {
2282 if ((*pp_rids)[i] == rid)
2283 return;
2286 *pp_rids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_rids, uint32, *p_num+1);
2288 if (*pp_rids == NULL)
2289 return;
2291 (*pp_rids)[*p_num] = rid;
2292 *p_num += 1;
2295 static BOOL ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2296 LDAPMessage *entry,
2297 const DOM_SID *domain_sid,
2298 uint32 *rid)
2300 fstring str;
2301 DOM_SID sid;
2303 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2304 str, sizeof(str)-1)) {
2305 DEBUG(10, ("Could not find sambaSID attribute\n"));
2306 return False;
2309 if (!string_to_sid(&sid, str)) {
2310 DEBUG(10, ("Could not convert string %s to sid\n", str));
2311 return False;
2314 if (sid_compare_domain(&sid, domain_sid) != 0) {
2315 DEBUG(10, ("SID %s is not in expected domain %s\n",
2316 str, sid_string_static(domain_sid)));
2317 return False;
2320 if (!sid_peek_rid(&sid, rid)) {
2321 DEBUG(10, ("Could not peek into RID\n"));
2322 return False;
2325 return True;
2328 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2329 TALLOC_CTX *mem_ctx,
2330 const DOM_SID *group,
2331 uint32 **pp_member_rids,
2332 size_t *p_num_members)
2334 struct ldapsam_privates *ldap_state =
2335 (struct ldapsam_privates *)methods->private_data;
2336 struct smbldap_state *conn = ldap_state->smbldap_state;
2337 pstring filter;
2338 int rc, count;
2339 LDAPMessage *msg = NULL;
2340 LDAPMessage *entry;
2341 char **values = NULL;
2342 char **memberuid;
2343 char *sid_filter = NULL;
2344 char *tmp;
2345 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2347 *pp_member_rids = NULL;
2348 *p_num_members = 0;
2350 pstr_sprintf(filter,
2351 "(&(objectClass=sambaSamAccount)"
2352 "(sambaPrimaryGroupSid=%s))",
2353 sid_string_static(group));
2356 const char *attrs[] = { "sambaSID", NULL };
2357 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2358 LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2359 &msg);
2362 if (rc != LDAP_SUCCESS)
2363 goto done;
2365 for (entry = ldap_first_entry(conn->ldap_struct, msg);
2366 entry != NULL;
2367 entry = ldap_next_entry(conn->ldap_struct, entry))
2369 uint32 rid;
2371 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2372 entry,
2373 get_global_sam_sid(),
2374 &rid)) {
2375 DEBUG(2, ("Could not find sid from ldap entry\n"));
2376 continue;
2379 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2380 p_num_members);
2383 if (msg != NULL)
2384 ldap_msgfree(msg);
2386 pstr_sprintf(filter,
2387 "(&(objectClass=sambaGroupMapping)"
2388 "(objectClass=posixGroup)"
2389 "(sambaSID=%s))",
2390 sid_string_static(group));
2393 const char *attrs[] = { "memberUid", NULL };
2394 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2395 LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2396 &msg);
2399 if (rc != LDAP_SUCCESS)
2400 goto done;
2402 count = ldap_count_entries(conn->ldap_struct, msg);
2404 if (count > 1) {
2405 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2406 sid_string_static(group)));
2407 goto done;
2410 if (count == 0) {
2411 result = NT_STATUS_OK;
2412 goto done;
2415 entry = ldap_first_entry(conn->ldap_struct, msg);
2416 if (entry == NULL)
2417 goto done;
2419 values = ldap_get_values(conn->ldap_struct, msg, "memberUid");
2420 if (values == NULL) {
2421 result = NT_STATUS_OK;
2422 goto done;
2425 sid_filter = SMB_STRDUP("(&(objectClass=sambaSamAccount)(|");
2426 if (sid_filter == NULL) {
2427 result = NT_STATUS_NO_MEMORY;
2428 goto done;
2431 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2432 tmp = sid_filter;
2433 asprintf(&sid_filter, "%s(uid=%s)", tmp, *memberuid);
2434 free(tmp);
2435 if (sid_filter == NULL) {
2436 result = NT_STATUS_NO_MEMORY;
2437 goto done;
2441 tmp = sid_filter;
2442 asprintf(&sid_filter, "%s))", sid_filter);
2443 free(tmp);
2444 if (sid_filter == NULL) {
2445 result = NT_STATUS_NO_MEMORY;
2446 goto done;
2450 const char *attrs[] = { "sambaSID", NULL };
2451 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2452 LDAP_SCOPE_SUBTREE, sid_filter, attrs, 0,
2453 &msg);
2456 if (rc != LDAP_SUCCESS)
2457 goto done;
2459 for (entry = ldap_first_entry(conn->ldap_struct, msg);
2460 entry != NULL;
2461 entry = ldap_next_entry(conn->ldap_struct, entry))
2463 fstring str;
2464 DOM_SID sid;
2465 uint32 rid;
2467 if (!smbldap_get_single_attribute(conn->ldap_struct,
2468 entry, "sambaSID",
2469 str, sizeof(str)-1))
2470 continue;
2472 if (!string_to_sid(&sid, str))
2473 goto done;
2475 if (!sid_check_is_in_our_domain(&sid)) {
2476 DEBUG(1, ("Inconsistent SAM -- group member uid not "
2477 "in our domain\n"));
2478 continue;
2481 sid_peek_rid(&sid, &rid);
2483 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2484 p_num_members);
2487 result = NT_STATUS_OK;
2489 done:
2490 SAFE_FREE(sid_filter);
2492 if (values != NULL)
2493 ldap_value_free(values);
2495 if (msg != NULL)
2496 ldap_msgfree(msg);
2498 return result;
2501 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2502 TALLOC_CTX *mem_ctx,
2503 struct samu *user,
2504 DOM_SID **pp_sids,
2505 gid_t **pp_gids,
2506 size_t *p_num_groups)
2508 struct ldapsam_privates *ldap_state =
2509 (struct ldapsam_privates *)methods->private_data;
2510 struct smbldap_state *conn = ldap_state->smbldap_state;
2511 pstring filter;
2512 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2513 char *escape_name;
2514 int rc;
2515 LDAPMessage *msg = NULL;
2516 LDAPMessage *entry;
2517 NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2518 size_t num_sids, num_gids;
2519 gid_t primary_gid;
2521 *pp_sids = NULL;
2522 num_sids = 0;
2524 if (!sid_to_gid(pdb_get_group_sid(user), &primary_gid)) {
2525 DEBUG(1, ("sid_to_gid failed for user's primary group\n"));
2526 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2529 escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2531 if (escape_name == NULL)
2532 return NT_STATUS_NO_MEMORY;
2534 pstr_sprintf(filter, "(&(objectClass=posixGroup)"
2535 "(|(memberUid=%s)(gidNumber=%d)))",
2536 escape_name, primary_gid);
2538 rc = smbldap_search(conn, lp_ldap_group_suffix(),
2539 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &msg);
2541 if (rc != LDAP_SUCCESS)
2542 goto done;
2544 num_gids = 0;
2545 *pp_gids = NULL;
2547 num_sids = 0;
2548 *pp_sids = NULL;
2550 /* We need to add the primary group as the first gid/sid */
2552 add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids);
2554 /* This sid will be replaced later */
2556 add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids, &num_sids);
2558 for (entry = ldap_first_entry(conn->ldap_struct, msg);
2559 entry != NULL;
2560 entry = ldap_next_entry(conn->ldap_struct, entry))
2562 fstring str;
2563 DOM_SID sid;
2564 gid_t gid;
2565 char *end;
2567 if (!smbldap_get_single_attribute(conn->ldap_struct,
2568 entry, "sambaSID",
2569 str, sizeof(str)-1))
2570 continue;
2572 if (!string_to_sid(&sid, str))
2573 goto done;
2575 if (!smbldap_get_single_attribute(conn->ldap_struct,
2576 entry, "gidNumber",
2577 str, sizeof(str)-1))
2578 continue;
2580 gid = strtoul(str, &end, 10);
2582 if (PTR_DIFF(end, str) != strlen(str))
2583 goto done;
2585 if (gid == primary_gid) {
2586 sid_copy(&(*pp_sids)[0], &sid);
2587 } else {
2588 add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2589 &num_gids);
2590 add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2591 &num_sids);
2595 if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2596 DEBUG(3, ("primary group of [%s] not found\n",
2597 pdb_get_username(user)));
2598 goto done;
2601 *p_num_groups = num_sids;
2603 result = NT_STATUS_OK;
2605 done:
2607 SAFE_FREE(escape_name);
2608 if (msg != NULL)
2609 ldap_msgfree(msg);
2611 return result;
2614 /**********************************************************************
2615 * Augment a posixGroup object with a sambaGroupMapping domgroup
2616 *********************************************************************/
2618 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2619 struct ldapsam_privates *ldap_state,
2620 GROUP_MAP *map)
2622 const char *filter, *dn;
2623 LDAPMessage *msg, *entry;
2624 LDAPMod **mods;
2625 int rc;
2627 filter = talloc_asprintf(mem_ctx,
2628 "(&(objectClass=posixGroup)(gidNumber=%u))",
2629 map->gid);
2630 if (filter == NULL) {
2631 return NT_STATUS_NO_MEMORY;
2634 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2635 get_attr_list(mem_ctx, groupmap_attr_list),
2636 &msg);
2637 talloc_autofree_ldapmsg(mem_ctx, msg);
2639 if ((rc != LDAP_SUCCESS) ||
2640 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2641 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2642 return NT_STATUS_NO_SUCH_GROUP;
2645 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2646 if (dn == NULL) {
2647 return NT_STATUS_NO_MEMORY;
2650 mods = NULL;
2651 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2652 "sambaGroupMapping");
2653 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2654 sid_string_static(&map->sid));
2655 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2656 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2657 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2658 map->nt_name);
2659 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2660 map->comment);
2661 talloc_autofree_ldapmod(mem_ctx, mods);
2663 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2664 if (rc != LDAP_SUCCESS) {
2665 return NT_STATUS_ACCESS_DENIED;
2668 return NT_STATUS_OK;
2671 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2672 GROUP_MAP *map)
2674 struct ldapsam_privates *ldap_state =
2675 (struct ldapsam_privates *)methods->private_data;
2676 LDAPMessage *msg = NULL;
2677 LDAPMod **mods = NULL;
2678 const char *attrs[] = { NULL };
2679 char *filter;
2681 char *dn;
2682 TALLOC_CTX *mem_ctx;
2683 NTSTATUS result;
2685 DOM_SID sid;
2687 int rc;
2689 mem_ctx = talloc_new(NULL);
2690 if (mem_ctx == NULL) {
2691 DEBUG(0, ("talloc_new failed\n"));
2692 return NT_STATUS_NO_MEMORY;
2695 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
2696 sid_string_static(&map->sid));
2697 if (filter == NULL) {
2698 result = NT_STATUS_NO_MEMORY;
2699 goto done;
2702 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
2703 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
2704 talloc_autofree_ldapmsg(mem_ctx, msg);
2706 if ((rc == LDAP_SUCCESS) &&
2707 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
2709 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
2710 "group mapping entry\n",
2711 sid_string_static(&map->sid)));
2712 result = NT_STATUS_GROUP_EXISTS;
2713 goto done;
2716 switch (map->sid_name_use) {
2718 case SID_NAME_DOM_GRP:
2719 /* To map a domain group we need to have a posix group
2720 to attach to. */
2721 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
2722 goto done;
2723 break;
2725 case SID_NAME_ALIAS:
2726 if (!sid_check_is_in_our_domain(&map->sid)) {
2727 DEBUG(3, ("Refusing to map sid %s as an alias, not "
2728 "in our domain\n",
2729 sid_string_static(&map->sid)));
2730 result = NT_STATUS_INVALID_PARAMETER;
2731 goto done;
2733 break;
2735 case SID_NAME_WKN_GRP:
2736 if (!sid_check_is_in_builtin(&map->sid)) {
2737 DEBUG(3, ("Refusing to map sid %s as an alias, not "
2738 "in builtin domain\n",
2739 sid_string_static(&map->sid)));
2740 result = NT_STATUS_INVALID_PARAMETER;
2741 goto done;
2743 break;
2745 default:
2746 DEBUG(3, ("Got invalid use '%s' for mapping\n",
2747 sid_type_lookup(map->sid_name_use)));
2748 result = NT_STATUS_INVALID_PARAMETER;
2749 goto done;
2752 /* Domain groups have been mapped in a separate routine, we have to
2753 * create an alias now */
2755 if (map->gid == -1) {
2756 DEBUG(10, ("Refusing to map gid==-1\n"));
2757 result = NT_STATUS_INVALID_PARAMETER;
2758 goto done;
2761 if (pdb_gid_to_sid(map->gid, &sid)) {
2762 DEBUG(3, ("Gid %d is already mapped to SID %s, refusing to "
2763 "add\n", map->gid, sid_string_static(&sid)));
2764 result = NT_STATUS_GROUP_EXISTS;
2765 goto done;
2768 /* Ok, enough checks done. It's still racy to go ahead now, but that's
2769 * the best we can get out of LDAP. */
2771 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
2772 sid_string_static(&map->sid),
2773 lp_ldap_group_suffix());
2774 if (dn == NULL) {
2775 result = NT_STATUS_NO_MEMORY;
2776 goto done;
2779 mods = NULL;
2781 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2782 "sambaSidEntry");
2783 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2784 "sambaGroupMapping");
2786 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
2787 sid_string_static(&map->sid));
2788 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
2789 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2790 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
2791 map->nt_name);
2792 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
2793 map->comment);
2794 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
2795 talloc_asprintf(mem_ctx, "%u", map->gid));
2796 talloc_autofree_ldapmod(mem_ctx, mods);
2798 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
2800 result = (rc == LDAP_SUCCESS) ?
2801 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
2803 done:
2804 TALLOC_FREE(mem_ctx);
2805 return result;
2808 /**********************************************************************
2809 * Update a group mapping entry. We're quite strict about what can be changed:
2810 * Only the description and displayname may be changed. It simply does not
2811 * make any sense to change the SID, gid or the type in a mapping.
2812 *********************************************************************/
2814 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2815 GROUP_MAP *map)
2817 struct ldapsam_privates *ldap_state =
2818 (struct ldapsam_privates *)methods->private_data;
2819 int rc;
2820 const char *filter, *dn;
2821 LDAPMessage *msg = NULL;
2822 LDAPMessage *entry = NULL;
2823 LDAPMod **mods = NULL;
2824 TALLOC_CTX *mem_ctx;
2825 NTSTATUS result;
2827 mem_ctx = talloc_new(NULL);
2828 if (mem_ctx == NULL) {
2829 DEBUG(0, ("talloc_new failed\n"));
2830 return NT_STATUS_NO_MEMORY;
2833 /* Make 100% sure that sid, gid and type are not changed by looking up
2834 * exactly the values we're given in LDAP. */
2836 filter = talloc_asprintf(mem_ctx, "(&(objectClass=sambaGroupMapping)"
2837 "(sambaSid=%s)(gidNumber=%u)"
2838 "(sambaGroupType=%d))",
2839 sid_string_static(&map->sid), map->gid,
2840 map->sid_name_use);
2841 if (filter == NULL) {
2842 result = NT_STATUS_NO_MEMORY;
2843 goto done;
2846 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2847 get_attr_list(mem_ctx, groupmap_attr_list),
2848 &msg);
2849 talloc_autofree_ldapmsg(mem_ctx, msg);
2851 if ((rc != LDAP_SUCCESS) ||
2852 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2853 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2854 result = NT_STATUS_NO_SUCH_GROUP;
2855 goto done;
2858 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2860 if (dn == NULL) {
2861 result = NT_STATUS_NO_MEMORY;
2862 goto done;
2865 mods = NULL;
2866 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2867 map->nt_name);
2868 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2869 map->comment);
2870 talloc_autofree_ldapmod(mem_ctx, mods);
2872 if (mods == NULL) {
2873 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
2874 "nothing to do\n"));
2875 result = NT_STATUS_OK;
2876 goto done;
2879 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2881 if (rc != LDAP_SUCCESS) {
2882 result = NT_STATUS_ACCESS_DENIED;
2883 goto done;
2886 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
2887 "group %lu in LDAP\n", (unsigned long)map->gid));
2889 result = NT_STATUS_OK;
2891 done:
2892 TALLOC_FREE(mem_ctx);
2893 return result;
2896 /**********************************************************************
2897 *********************************************************************/
2899 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2900 DOM_SID sid)
2902 struct ldapsam_privates *priv =
2903 (struct ldapsam_privates *)methods->private_data;
2904 LDAPMessage *msg, *entry;
2905 int rc;
2906 NTSTATUS result;
2907 TALLOC_CTX *mem_ctx;
2908 char *filter;
2910 mem_ctx = talloc_new(NULL);
2911 if (mem_ctx == NULL) {
2912 DEBUG(0, ("talloc_new failed\n"));
2913 return NT_STATUS_NO_MEMORY;
2916 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
2917 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
2918 sid_string_static(&sid));
2919 if (filter == NULL) {
2920 result = NT_STATUS_NO_MEMORY;
2921 goto done;
2923 rc = smbldap_search_suffix(priv->smbldap_state, filter,
2924 get_attr_list(mem_ctx, groupmap_attr_list),
2925 &msg);
2926 talloc_autofree_ldapmsg(mem_ctx, msg);
2928 if ((rc != LDAP_SUCCESS) ||
2929 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
2930 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
2931 result = NT_STATUS_NO_SUCH_GROUP;
2932 goto done;
2935 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
2936 get_attr_list(mem_ctx,
2937 groupmap_attr_list_to_delete));
2939 if ((rc == LDAP_NAMING_VIOLATION) ||
2940 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
2941 const char *attrs[] = { "sambaGroupType", "description",
2942 "displayName", "sambaSIDList",
2943 NULL };
2945 /* Second try. Don't delete the sambaSID attribute, this is
2946 for "old" entries that are tacked on a winbind
2947 sambaIdmapEntry. */
2949 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
2950 LDAP_OBJ_GROUPMAP, attrs);
2953 if ((rc == LDAP_NAMING_VIOLATION) ||
2954 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
2955 const char *attrs[] = { "sambaGroupType", "description",
2956 "displayName", "sambaSIDList",
2957 "gidNumber", NULL };
2959 /* Third try. This is a post-3.0.21 alias (containing only
2960 * sambaSidEntry and sambaGroupMapping classes), we also have
2961 * to delete the gidNumber attribute, only the sambaSidEntry
2962 * remains */
2964 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
2965 LDAP_OBJ_GROUPMAP, attrs);
2968 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
2970 done:
2971 TALLOC_FREE(mem_ctx);
2972 return result;
2975 /**********************************************************************
2976 *********************************************************************/
2978 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
2979 BOOL update)
2981 struct ldapsam_privates *ldap_state =
2982 (struct ldapsam_privates *)my_methods->private_data;
2983 fstring filter;
2984 int rc;
2985 const char **attr_list;
2987 pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2988 attr_list = get_attr_list( NULL, groupmap_attr_list );
2989 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2990 LDAP_SCOPE_SUBTREE, filter,
2991 attr_list, 0, &ldap_state->result);
2992 TALLOC_FREE(attr_list);
2994 if (rc != LDAP_SUCCESS) {
2995 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
2996 ldap_err2string(rc)));
2997 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
2998 lp_ldap_group_suffix(), filter));
2999 ldap_msgfree(ldap_state->result);
3000 ldap_state->result = NULL;
3001 return NT_STATUS_UNSUCCESSFUL;
3004 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3005 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3006 ldap_state->result)));
3008 ldap_state->entry =
3009 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3010 ldap_state->result);
3011 ldap_state->index = 0;
3013 return NT_STATUS_OK;
3016 /**********************************************************************
3017 *********************************************************************/
3019 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3021 ldapsam_endsampwent(my_methods);
3024 /**********************************************************************
3025 *********************************************************************/
3027 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3028 GROUP_MAP *map)
3030 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3031 struct ldapsam_privates *ldap_state =
3032 (struct ldapsam_privates *)my_methods->private_data;
3033 BOOL bret = False;
3035 while (!bret) {
3036 if (!ldap_state->entry)
3037 return ret;
3039 ldap_state->index++;
3040 bret = init_group_from_ldap(ldap_state, map,
3041 ldap_state->entry);
3043 ldap_state->entry =
3044 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3045 ldap_state->entry);
3048 return NT_STATUS_OK;
3051 /**********************************************************************
3052 *********************************************************************/
3054 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3055 enum SID_NAME_USE sid_name_use,
3056 GROUP_MAP **pp_rmap,
3057 size_t *p_num_entries,
3058 BOOL unix_only)
3060 GROUP_MAP map;
3061 GROUP_MAP *mapt;
3062 size_t entries = 0;
3064 *p_num_entries = 0;
3065 *pp_rmap = NULL;
3067 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3068 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3069 "passdb\n"));
3070 return NT_STATUS_ACCESS_DENIED;
3073 while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3074 if (sid_name_use != SID_NAME_UNKNOWN &&
3075 sid_name_use != map.sid_name_use) {
3076 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3077 "not of the requested type\n", map.nt_name));
3078 continue;
3080 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3081 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3082 "non mapped\n", map.nt_name));
3083 continue;
3086 mapt=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3087 if (!mapt) {
3088 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3089 "enlarge group map!\n"));
3090 SAFE_FREE(*pp_rmap);
3091 return NT_STATUS_UNSUCCESSFUL;
3093 else
3094 (*pp_rmap) = mapt;
3096 mapt[entries] = map;
3098 entries += 1;
3101 ldapsam_endsamgrent(methods);
3103 *p_num_entries = entries;
3105 return NT_STATUS_OK;
3108 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3109 const DOM_SID *alias,
3110 const DOM_SID *member,
3111 int modop)
3113 struct ldapsam_privates *ldap_state =
3114 (struct ldapsam_privates *)methods->private_data;
3115 char *dn;
3116 LDAPMessage *result = NULL;
3117 LDAPMessage *entry = NULL;
3118 int count;
3119 LDAPMod **mods = NULL;
3120 int rc;
3121 enum SID_NAME_USE type = SID_NAME_USE_NONE;
3123 pstring filter;
3125 if (sid_check_is_in_builtin(alias)) {
3126 type = SID_NAME_WKN_GRP;
3129 if (sid_check_is_in_our_domain(alias)) {
3130 type = SID_NAME_ALIAS;
3133 if (type == SID_NAME_USE_NONE) {
3134 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3135 sid_string_static(alias)));
3136 return NT_STATUS_NO_SUCH_ALIAS;
3139 pstr_sprintf(filter,
3140 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3141 LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3142 type);
3144 if (ldapsam_search_one_group(ldap_state, filter,
3145 &result) != LDAP_SUCCESS)
3146 return NT_STATUS_NO_SUCH_ALIAS;
3148 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3149 result);
3151 if (count < 1) {
3152 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3153 ldap_msgfree(result);
3154 return NT_STATUS_NO_SUCH_ALIAS;
3157 if (count > 1) {
3158 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3159 "filter %s: count=%d\n", filter, count));
3160 ldap_msgfree(result);
3161 return NT_STATUS_NO_SUCH_ALIAS;
3164 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3165 result);
3167 if (!entry) {
3168 ldap_msgfree(result);
3169 return NT_STATUS_UNSUCCESSFUL;
3172 dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
3173 if (!dn) {
3174 ldap_msgfree(result);
3175 return NT_STATUS_UNSUCCESSFUL;
3178 smbldap_set_mod(&mods, modop,
3179 get_attr_key2string(groupmap_attr_list,
3180 LDAP_ATTR_SID_LIST),
3181 sid_string_static(member));
3183 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3185 ldap_mods_free(mods, True);
3186 ldap_msgfree(result);
3187 SAFE_FREE(dn);
3189 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3190 return NT_STATUS_MEMBER_IN_ALIAS;
3193 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3194 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3197 if (rc != LDAP_SUCCESS) {
3198 return NT_STATUS_UNSUCCESSFUL;
3201 return NT_STATUS_OK;
3204 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3205 const DOM_SID *alias,
3206 const DOM_SID *member)
3208 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3211 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3212 const DOM_SID *alias,
3213 const DOM_SID *member)
3215 return ldapsam_modify_aliasmem(methods, alias, member,
3216 LDAP_MOD_DELETE);
3219 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3220 const DOM_SID *alias,
3221 DOM_SID **pp_members,
3222 size_t *p_num_members)
3224 struct ldapsam_privates *ldap_state =
3225 (struct ldapsam_privates *)methods->private_data;
3226 LDAPMessage *result = NULL;
3227 LDAPMessage *entry = NULL;
3228 int count;
3229 char **values;
3230 int i;
3231 pstring filter;
3232 size_t num_members = 0;
3233 enum SID_NAME_USE type = SID_NAME_USE_NONE;
3235 *pp_members = NULL;
3236 *p_num_members = 0;
3238 if (sid_check_is_in_builtin(alias)) {
3239 type = SID_NAME_WKN_GRP;
3242 if (sid_check_is_in_our_domain(alias)) {
3243 type = SID_NAME_ALIAS;
3246 if (type == SID_NAME_USE_NONE) {
3247 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3248 sid_string_static(alias)));
3249 return NT_STATUS_NO_SUCH_ALIAS;
3252 pstr_sprintf(filter,
3253 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3254 LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3255 type);
3257 if (ldapsam_search_one_group(ldap_state, filter,
3258 &result) != LDAP_SUCCESS)
3259 return NT_STATUS_NO_SUCH_ALIAS;
3261 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3262 result);
3264 if (count < 1) {
3265 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3266 ldap_msgfree(result);
3267 return NT_STATUS_NO_SUCH_ALIAS;
3270 if (count > 1) {
3271 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3272 "filter %s: count=%d\n", filter, count));
3273 ldap_msgfree(result);
3274 return NT_STATUS_NO_SUCH_ALIAS;
3277 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3278 result);
3280 if (!entry) {
3281 ldap_msgfree(result);
3282 return NT_STATUS_UNSUCCESSFUL;
3285 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3286 entry,
3287 get_attr_key2string(groupmap_attr_list,
3288 LDAP_ATTR_SID_LIST));
3290 if (values == NULL) {
3291 ldap_msgfree(result);
3292 return NT_STATUS_OK;
3295 count = ldap_count_values(values);
3297 for (i=0; i<count; i++) {
3298 DOM_SID member;
3300 if (!string_to_sid(&member, values[i]))
3301 continue;
3303 add_sid_to_array(NULL, &member, pp_members, &num_members);
3306 *p_num_members = num_members;
3307 ldap_value_free(values);
3308 ldap_msgfree(result);
3310 return NT_STATUS_OK;
3313 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3314 TALLOC_CTX *mem_ctx,
3315 const DOM_SID *domain_sid,
3316 const DOM_SID *members,
3317 size_t num_members,
3318 uint32 **pp_alias_rids,
3319 size_t *p_num_alias_rids)
3321 struct ldapsam_privates *ldap_state =
3322 (struct ldapsam_privates *)methods->private_data;
3323 LDAP *ldap_struct;
3325 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3327 LDAPMessage *result = NULL;
3328 LDAPMessage *entry = NULL;
3329 int i;
3330 int rc;
3331 char *filter;
3332 enum SID_NAME_USE type = SID_NAME_USE_NONE;
3334 if (sid_check_is_builtin(domain_sid)) {
3335 type = SID_NAME_WKN_GRP;
3338 if (sid_check_is_domain(domain_sid)) {
3339 type = SID_NAME_ALIAS;
3342 if (type == SID_NAME_USE_NONE) {
3343 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3344 sid_string_static(domain_sid)));
3345 return NT_STATUS_UNSUCCESSFUL;
3348 filter = talloc_asprintf(mem_ctx,
3349 "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3350 LDAP_OBJ_GROUPMAP, type);
3352 for (i=0; i<num_members; i++)
3353 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3354 filter,
3355 sid_string_static(&members[i]));
3357 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3359 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3360 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3362 if (rc != LDAP_SUCCESS)
3363 return NT_STATUS_UNSUCCESSFUL;
3365 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3367 for (entry = ldap_first_entry(ldap_struct, result);
3368 entry != NULL;
3369 entry = ldap_next_entry(ldap_struct, entry))
3371 fstring sid_str;
3372 DOM_SID sid;
3373 uint32 rid;
3375 if (!smbldap_get_single_attribute(ldap_struct, entry,
3376 LDAP_ATTRIBUTE_SID,
3377 sid_str,
3378 sizeof(sid_str)-1))
3379 continue;
3381 if (!string_to_sid(&sid, sid_str))
3382 continue;
3384 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3385 continue;
3387 add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3388 p_num_alias_rids);
3391 ldap_msgfree(result);
3392 return NT_STATUS_OK;
3395 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3396 int policy_index,
3397 uint32 value)
3399 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3400 int rc;
3401 LDAPMod **mods = NULL;
3402 fstring value_string;
3403 const char *policy_attr = NULL;
3405 struct ldapsam_privates *ldap_state =
3406 (struct ldapsam_privates *)methods->private_data;
3408 const char *attrs[2];
3410 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3412 if (!ldap_state->domain_dn) {
3413 return NT_STATUS_INVALID_PARAMETER;
3416 policy_attr = get_account_policy_attr(policy_index);
3417 if (policy_attr == NULL) {
3418 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3419 "policy\n"));
3420 return ntstatus;
3423 attrs[0] = policy_attr;
3424 attrs[1] = NULL;
3426 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3428 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3430 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3431 mods);
3433 ldap_mods_free(mods, True);
3435 if (rc != LDAP_SUCCESS) {
3436 return ntstatus;
3439 if (!cache_account_policy_set(policy_index, value)) {
3440 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3441 "update local tdb cache\n"));
3442 return ntstatus;
3445 return NT_STATUS_OK;
3448 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3449 int policy_index, uint32 value)
3451 if (!account_policy_migrated(False)) {
3452 return (account_policy_set(policy_index, value)) ?
3453 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3456 return ldapsam_set_account_policy_in_ldap(methods, policy_index,
3457 value);
3460 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3461 int policy_index,
3462 uint32 *value)
3464 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3465 LDAPMessage *result = NULL;
3466 LDAPMessage *entry = NULL;
3467 int count;
3468 int rc;
3469 char **vals = NULL;
3470 const char *policy_attr = NULL;
3472 struct ldapsam_privates *ldap_state =
3473 (struct ldapsam_privates *)methods->private_data;
3475 const char *attrs[2];
3477 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3479 if (!ldap_state->domain_dn) {
3480 return NT_STATUS_INVALID_PARAMETER;
3483 policy_attr = get_account_policy_attr(policy_index);
3484 if (!policy_attr) {
3485 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3486 "policy index: %d\n", policy_index));
3487 return ntstatus;
3490 attrs[0] = policy_attr;
3491 attrs[1] = NULL;
3493 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3494 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3495 &result);
3497 if (rc != LDAP_SUCCESS) {
3498 return ntstatus;
3501 count = ldap_count_entries(priv2ld(ldap_state), result);
3502 if (count < 1) {
3503 goto out;
3506 entry = ldap_first_entry(priv2ld(ldap_state), result);
3507 if (entry == NULL) {
3508 goto out;
3511 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3512 if (vals == NULL) {
3513 goto out;
3516 *value = (uint32)atol(vals[0]);
3518 ntstatus = NT_STATUS_OK;
3520 out:
3521 if (vals)
3522 ldap_value_free(vals);
3523 ldap_msgfree(result);
3525 return ntstatus;
3528 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3530 - if user hasn't decided to use account policies inside LDAP just reuse the
3531 old tdb values
3533 - if there is a valid cache entry, return that
3534 - if there is an LDAP entry, update cache and return
3535 - otherwise set to default, update cache and return
3537 Guenther
3539 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3540 int policy_index, uint32 *value)
3542 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3544 if (!account_policy_migrated(False)) {
3545 return (account_policy_get(policy_index, value))
3546 ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3549 if (cache_account_policy_get(policy_index, value)) {
3550 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3551 "cache\n"));
3552 return NT_STATUS_OK;
3555 ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index,
3556 value);
3557 if (NT_STATUS_IS_OK(ntstatus)) {
3558 goto update_cache;
3561 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3562 "ldap\n"));
3564 #if 0
3565 /* should we automagically migrate old tdb value here ? */
3566 if (account_policy_get(policy_index, value))
3567 goto update_ldap;
3569 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3570 "default\n", policy_index));
3571 #endif
3573 if (!account_policy_get_default(policy_index, value)) {
3574 return ntstatus;
3577 /* update_ldap: */
3579 ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3580 if (!NT_STATUS_IS_OK(ntstatus)) {
3581 return ntstatus;
3584 update_cache:
3586 if (!cache_account_policy_set(policy_index, *value)) {
3587 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3588 "tdb as a cache\n"));
3589 return NT_STATUS_UNSUCCESSFUL;
3592 return NT_STATUS_OK;
3595 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3596 const DOM_SID *domain_sid,
3597 int num_rids,
3598 uint32 *rids,
3599 const char **names,
3600 uint32 *attrs)
3602 struct ldapsam_privates *ldap_state =
3603 (struct ldapsam_privates *)methods->private_data;
3604 LDAPMessage *msg = NULL;
3605 LDAPMessage *entry;
3606 char *allsids = NULL;
3607 int i, rc, num_mapped;
3608 NTSTATUS result = NT_STATUS_NO_MEMORY;
3609 TALLOC_CTX *mem_ctx;
3610 LDAP *ld;
3611 BOOL is_builtin;
3613 mem_ctx = talloc_new(NULL);
3614 if (mem_ctx == NULL) {
3615 DEBUG(0, ("talloc_new failed\n"));
3616 goto done;
3619 if (!sid_check_is_builtin(domain_sid) &&
3620 !sid_check_is_domain(domain_sid)) {
3621 result = NT_STATUS_INVALID_PARAMETER;
3622 goto done;
3625 for (i=0; i<num_rids; i++)
3626 attrs[i] = SID_NAME_UNKNOWN;
3628 allsids = talloc_strdup(mem_ctx, "");
3629 if (allsids == NULL) {
3630 goto done;
3633 for (i=0; i<num_rids; i++) {
3634 DOM_SID sid;
3635 sid_copy(&sid, domain_sid);
3636 sid_append_rid(&sid, rids[i]);
3637 allsids = talloc_asprintf_append(allsids, "(sambaSid=%s)",
3638 sid_string_static(&sid));
3639 if (allsids == NULL) {
3640 goto done;
3644 /* First look for users */
3647 char *filter;
3648 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
3650 filter = talloc_asprintf(
3651 mem_ctx, ("(&(objectClass=sambaSamAccount)(|%s))"),
3652 allsids);
3654 if (filter == NULL) {
3655 goto done;
3658 rc = smbldap_search(ldap_state->smbldap_state,
3659 lp_ldap_user_suffix(),
3660 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3661 &msg);
3662 talloc_autofree_ldapmsg(mem_ctx, msg);
3665 if (rc != LDAP_SUCCESS)
3666 goto done;
3668 ld = ldap_state->smbldap_state->ldap_struct;
3669 num_mapped = 0;
3671 for (entry = ldap_first_entry(ld, msg);
3672 entry != NULL;
3673 entry = ldap_next_entry(ld, entry)) {
3674 uint32 rid;
3675 int rid_index;
3676 const char *name;
3678 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3679 &rid)) {
3680 DEBUG(2, ("Could not find sid from ldap entry\n"));
3681 continue;
3684 name = smbldap_talloc_single_attribute(ld, entry, "uid",
3685 names);
3686 if (name == NULL) {
3687 DEBUG(2, ("Could not retrieve uid attribute\n"));
3688 continue;
3691 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3692 if (rid == rids[rid_index])
3693 break;
3696 if (rid_index == num_rids) {
3697 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3698 continue;
3701 attrs[rid_index] = SID_NAME_USER;
3702 names[rid_index] = name;
3703 num_mapped += 1;
3706 if (num_mapped == num_rids) {
3707 /* No need to look for groups anymore -- we're done */
3708 result = NT_STATUS_OK;
3709 goto done;
3712 /* Same game for groups */
3715 char *filter;
3716 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
3717 "sambaGroupType", NULL };
3719 filter = talloc_asprintf(
3720 mem_ctx, "(&(objectClass=sambaGroupMapping)(|%s))",
3721 allsids);
3722 if (filter == NULL) {
3723 goto done;
3726 rc = smbldap_search(ldap_state->smbldap_state,
3727 lp_ldap_group_suffix(),
3728 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3729 &msg);
3730 talloc_autofree_ldapmsg(mem_ctx, msg);
3733 if (rc != LDAP_SUCCESS)
3734 goto done;
3736 /* ldap_struct might have changed due to a reconnect */
3738 ld = ldap_state->smbldap_state->ldap_struct;
3740 /* For consistency checks, we already checked we're only domain or builtin */
3742 is_builtin = sid_check_is_builtin(domain_sid);
3744 for (entry = ldap_first_entry(ld, msg);
3745 entry != NULL;
3746 entry = ldap_next_entry(ld, entry))
3748 uint32 rid;
3749 int rid_index;
3750 const char *attr;
3751 enum SID_NAME_USE type;
3752 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
3754 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
3755 mem_ctx);
3756 if (attr == NULL) {
3757 DEBUG(2, ("Could not extract type from ldap entry %s\n",
3758 dn));
3759 continue;
3762 type = atol(attr);
3764 /* Consistency checks */
3765 if ((is_builtin && (type != SID_NAME_WKN_GRP)) ||
3766 (!is_builtin && ((type != SID_NAME_ALIAS) &&
3767 (type != SID_NAME_DOM_GRP)))) {
3768 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
3771 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3772 &rid)) {
3773 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
3774 continue;
3777 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
3779 if (attr == NULL) {
3780 DEBUG(10, ("Could not retrieve 'cn' attribute from %s\n",
3781 dn));
3782 attr = smbldap_talloc_single_attribute(
3783 ld, entry, "displayName", names);
3786 if (attr == NULL) {
3787 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
3788 dn));
3789 continue;
3792 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3793 if (rid == rids[rid_index])
3794 break;
3797 if (rid_index == num_rids) {
3798 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3799 continue;
3802 attrs[rid_index] = type;
3803 names[rid_index] = attr;
3804 num_mapped += 1;
3807 result = NT_STATUS_NONE_MAPPED;
3809 if (num_mapped > 0)
3810 result = (num_mapped == num_rids) ?
3811 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
3812 done:
3813 TALLOC_FREE(mem_ctx);
3814 return result;
3817 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
3819 char *filter = NULL;
3820 char *escaped = NULL;
3821 char *result = NULL;
3823 asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
3824 "(uid=%u)");
3825 if (filter == NULL) goto done;
3827 escaped = escape_ldap_string_alloc(username);
3828 if (escaped == NULL) goto done;
3830 result = talloc_string_sub(mem_ctx, filter, "%u", username);
3832 done:
3833 SAFE_FREE(filter);
3834 SAFE_FREE(escaped);
3836 return result;
3839 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
3841 int i, num = 0;
3842 va_list ap;
3843 const char **result;
3845 va_start(ap, mem_ctx);
3846 while (va_arg(ap, const char *) != NULL)
3847 num += 1;
3848 va_end(ap);
3850 result = TALLOC_ARRAY(mem_ctx, const char *, num+1);
3852 va_start(ap, mem_ctx);
3853 for (i=0; i<num; i++)
3854 result[i] = talloc_strdup(mem_ctx, va_arg(ap, const char*));
3855 va_end(ap);
3857 result[num] = NULL;
3858 return result;
3861 struct ldap_search_state {
3862 struct smbldap_state *connection;
3864 uint16 acct_flags;
3865 uint16 group_type;
3867 const char *base;
3868 int scope;
3869 const char *filter;
3870 const char **attrs;
3871 int attrsonly;
3872 void *pagedresults_cookie;
3874 LDAPMessage *entries, *current_entry;
3875 BOOL (*ldap2displayentry)(struct ldap_search_state *state,
3876 TALLOC_CTX *mem_ctx,
3877 LDAP *ld, LDAPMessage *entry,
3878 struct samr_displayentry *result);
3881 static BOOL ldapsam_search_firstpage(struct pdb_search *search)
3883 struct ldap_search_state *state = search->private_data;
3884 LDAP *ld;
3885 int rc = LDAP_OPERATIONS_ERROR;
3887 state->entries = NULL;
3889 if (state->connection->paged_results) {
3890 rc = smbldap_search_paged(state->connection, state->base,
3891 state->scope, state->filter,
3892 state->attrs, state->attrsonly,
3893 lp_ldap_page_size(), &state->entries,
3894 &state->pagedresults_cookie);
3897 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
3899 if (state->entries != NULL) {
3900 /* Left over from unsuccessful paged attempt */
3901 ldap_msgfree(state->entries);
3902 state->entries = NULL;
3905 rc = smbldap_search(state->connection, state->base,
3906 state->scope, state->filter, state->attrs,
3907 state->attrsonly, &state->entries);
3909 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3910 return False;
3912 /* Ok, the server was lying. It told us it could do paged
3913 * searches when it could not. */
3914 state->connection->paged_results = False;
3917 ld = state->connection->ldap_struct;
3918 if ( ld == NULL) {
3919 DEBUG(5, ("Don't have an LDAP connection right after a "
3920 "search\n"));
3921 return False;
3923 state->current_entry = ldap_first_entry(ld, state->entries);
3925 if (state->current_entry == NULL) {
3926 ldap_msgfree(state->entries);
3927 state->entries = NULL;
3930 return True;
3933 static BOOL ldapsam_search_nextpage(struct pdb_search *search)
3935 struct ldap_search_state *state = search->private_data;
3936 int rc;
3938 if (!state->connection->paged_results) {
3939 /* There is no next page when there are no paged results */
3940 return False;
3943 rc = smbldap_search_paged(state->connection, state->base,
3944 state->scope, state->filter, state->attrs,
3945 state->attrsonly, lp_ldap_page_size(),
3946 &state->entries,
3947 &state->pagedresults_cookie);
3949 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3950 return False;
3952 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
3954 if (state->current_entry == NULL) {
3955 ldap_msgfree(state->entries);
3956 state->entries = NULL;
3959 return True;
3962 static BOOL ldapsam_search_next_entry(struct pdb_search *search,
3963 struct samr_displayentry *entry)
3965 struct ldap_search_state *state = search->private_data;
3966 BOOL result;
3968 retry:
3969 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
3970 return False;
3972 if ((state->entries == NULL) &&
3973 !ldapsam_search_nextpage(search))
3974 return False;
3976 result = state->ldap2displayentry(state, search->mem_ctx, state->connection->ldap_struct,
3977 state->current_entry, entry);
3979 if (!result) {
3980 char *dn;
3981 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
3982 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
3983 if (dn != NULL) ldap_memfree(dn);
3986 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
3988 if (state->current_entry == NULL) {
3989 ldap_msgfree(state->entries);
3990 state->entries = NULL;
3993 if (!result) goto retry;
3995 return True;
3998 static void ldapsam_search_end(struct pdb_search *search)
4000 struct ldap_search_state *state = search->private_data;
4001 int rc;
4003 if (state->pagedresults_cookie == NULL)
4004 return;
4006 if (state->entries != NULL)
4007 ldap_msgfree(state->entries);
4009 state->entries = NULL;
4010 state->current_entry = NULL;
4012 if (!state->connection->paged_results)
4013 return;
4015 /* Tell the LDAP server we're not interested in the rest anymore. */
4017 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4018 state->filter, state->attrs,
4019 state->attrsonly, 0, &state->entries,
4020 &state->pagedresults_cookie);
4022 if (rc != LDAP_SUCCESS)
4023 DEBUG(5, ("Could not end search properly\n"));
4025 return;
4028 static BOOL ldapuser2displayentry(struct ldap_search_state *state,
4029 TALLOC_CTX *mem_ctx,
4030 LDAP *ld, LDAPMessage *entry,
4031 struct samr_displayentry *result)
4033 char **vals;
4034 DOM_SID sid;
4035 uint16 acct_flags;
4037 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4038 if ((vals == NULL) || (vals[0] == NULL)) {
4039 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4040 return False;
4042 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4043 ldap_value_free(vals);
4045 if ((state->acct_flags != 0) &&
4046 ((state->acct_flags & acct_flags) == 0))
4047 return False;
4049 result->acct_flags = acct_flags;
4050 result->account_name = "";
4051 result->fullname = "";
4052 result->description = "";
4054 vals = ldap_get_values(ld, entry, "uid");
4055 if ((vals == NULL) || (vals[0] == NULL)) {
4056 DEBUG(5, ("\"uid\" not found\n"));
4057 return False;
4059 pull_utf8_talloc(mem_ctx,
4060 CONST_DISCARD(char **, &result->account_name),
4061 vals[0]);
4062 ldap_value_free(vals);
4064 vals = ldap_get_values(ld, entry, "displayName");
4065 if ((vals == NULL) || (vals[0] == NULL))
4066 DEBUG(8, ("\"displayName\" not found\n"));
4067 else
4068 pull_utf8_talloc(mem_ctx,
4069 CONST_DISCARD(char **, &result->fullname),
4070 vals[0]);
4071 ldap_value_free(vals);
4073 vals = ldap_get_values(ld, entry, "description");
4074 if ((vals == NULL) || (vals[0] == NULL))
4075 DEBUG(8, ("\"description\" not found\n"));
4076 else
4077 pull_utf8_talloc(mem_ctx,
4078 CONST_DISCARD(char **, &result->description),
4079 vals[0]);
4080 ldap_value_free(vals);
4082 if ((result->account_name == NULL) ||
4083 (result->fullname == NULL) ||
4084 (result->description == NULL)) {
4085 DEBUG(0, ("talloc failed\n"));
4086 return False;
4089 vals = ldap_get_values(ld, entry, "sambaSid");
4090 if ((vals == NULL) || (vals[0] == NULL)) {
4091 DEBUG(0, ("\"objectSid\" not found\n"));
4092 return False;
4095 if (!string_to_sid(&sid, vals[0])) {
4096 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4097 ldap_value_free(vals);
4098 return False;
4100 ldap_value_free(vals);
4102 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4103 DEBUG(0, ("sid %s does not belong to our domain\n",
4104 sid_string_static(&sid)));
4105 return False;
4108 return True;
4112 static BOOL ldapsam_search_users(struct pdb_methods *methods,
4113 struct pdb_search *search,
4114 uint16 acct_flags)
4116 struct ldapsam_privates *ldap_state = methods->private_data;
4117 struct ldap_search_state *state;
4119 state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4120 if (state == NULL) {
4121 DEBUG(0, ("talloc failed\n"));
4122 return False;
4125 state->connection = ldap_state->smbldap_state;
4127 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4128 state->base = lp_ldap_user_suffix();
4129 else if ((acct_flags != 0) &&
4130 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4131 state->base = lp_ldap_machine_suffix();
4132 else
4133 state->base = lp_ldap_suffix();
4135 state->acct_flags = acct_flags;
4136 state->base = talloc_strdup(search->mem_ctx, state->base);
4137 state->scope = LDAP_SCOPE_SUBTREE;
4138 state->filter = get_ldap_filter(search->mem_ctx, "*");
4139 state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
4140 "displayName", "description",
4141 "sambaAcctFlags", NULL);
4142 state->attrsonly = 0;
4143 state->pagedresults_cookie = NULL;
4144 state->entries = NULL;
4145 state->ldap2displayentry = ldapuser2displayentry;
4147 if ((state->filter == NULL) || (state->attrs == NULL)) {
4148 DEBUG(0, ("talloc failed\n"));
4149 return False;
4152 search->private_data = state;
4153 search->next_entry = ldapsam_search_next_entry;
4154 search->search_end = ldapsam_search_end;
4156 return ldapsam_search_firstpage(search);
4159 static BOOL ldapgroup2displayentry(struct ldap_search_state *state,
4160 TALLOC_CTX *mem_ctx,
4161 LDAP *ld, LDAPMessage *entry,
4162 struct samr_displayentry *result)
4164 char **vals;
4165 DOM_SID sid;
4166 uint16 group_type;
4168 result->account_name = "";
4169 result->fullname = "";
4170 result->description = "";
4173 vals = ldap_get_values(ld, entry, "sambaGroupType");
4174 if ((vals == NULL) || (vals[0] == NULL)) {
4175 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4176 if (vals != NULL) {
4177 ldap_value_free(vals);
4179 return False;
4182 group_type = atoi(vals[0]);
4184 if ((state->group_type != 0) &&
4185 ((state->group_type != group_type))) {
4186 ldap_value_free(vals);
4187 return False;
4190 ldap_value_free(vals);
4192 /* display name is the NT group name */
4194 vals = ldap_get_values(ld, entry, "displayName");
4195 if ((vals == NULL) || (vals[0] == NULL)) {
4196 DEBUG(8, ("\"displayName\" not found\n"));
4198 /* fallback to the 'cn' attribute */
4199 vals = ldap_get_values(ld, entry, "cn");
4200 if ((vals == NULL) || (vals[0] == NULL)) {
4201 DEBUG(5, ("\"cn\" not found\n"));
4202 return False;
4204 pull_utf8_talloc(mem_ctx,
4205 CONST_DISCARD(char **, &result->account_name),
4206 vals[0]);
4208 else {
4209 pull_utf8_talloc(mem_ctx,
4210 CONST_DISCARD(char **, &result->account_name),
4211 vals[0]);
4214 ldap_value_free(vals);
4216 vals = ldap_get_values(ld, entry, "description");
4217 if ((vals == NULL) || (vals[0] == NULL))
4218 DEBUG(8, ("\"description\" not found\n"));
4219 else
4220 pull_utf8_talloc(mem_ctx,
4221 CONST_DISCARD(char **, &result->description),
4222 vals[0]);
4223 ldap_value_free(vals);
4225 if ((result->account_name == NULL) ||
4226 (result->fullname == NULL) ||
4227 (result->description == NULL)) {
4228 DEBUG(0, ("talloc failed\n"));
4229 return False;
4232 vals = ldap_get_values(ld, entry, "sambaSid");
4233 if ((vals == NULL) || (vals[0] == NULL)) {
4234 DEBUG(0, ("\"objectSid\" not found\n"));
4235 if (vals != NULL) {
4236 ldap_value_free(vals);
4238 return False;
4241 if (!string_to_sid(&sid, vals[0])) {
4242 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4243 return False;
4246 ldap_value_free(vals);
4248 switch (group_type) {
4249 case SID_NAME_DOM_GRP:
4250 case SID_NAME_ALIAS:
4252 if (!sid_peek_check_rid(get_global_sam_sid(), &sid,
4253 &result->rid)) {
4254 DEBUG(0, ("%s is not in our domain\n",
4255 sid_string_static(&sid)));
4256 return False;
4258 break;
4260 case SID_NAME_WKN_GRP:
4262 if (!sid_peek_check_rid(&global_sid_Builtin, &sid,
4263 &result->rid)) {
4265 DEBUG(0, ("%s is not in builtin sid\n",
4266 sid_string_static(&sid)));
4267 return False;
4269 break;
4271 default:
4272 DEBUG(0,("unkown group type: %d\n", group_type));
4273 return False;
4276 return True;
4279 static BOOL ldapsam_search_grouptype(struct pdb_methods *methods,
4280 struct pdb_search *search,
4281 enum SID_NAME_USE type)
4283 struct ldapsam_privates *ldap_state = methods->private_data;
4284 struct ldap_search_state *state;
4286 state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4287 if (state == NULL) {
4288 DEBUG(0, ("talloc failed\n"));
4289 return False;
4292 state->connection = ldap_state->smbldap_state;
4294 state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
4295 state->connection = ldap_state->smbldap_state;
4296 state->scope = LDAP_SCOPE_SUBTREE;
4297 state->filter = talloc_asprintf(search->mem_ctx,
4298 "(&(objectclass=sambaGroupMapping)"
4299 "(sambaGroupType=%d))", type);
4300 state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
4301 "displayName", "description",
4302 "sambaGroupType", NULL);
4303 state->attrsonly = 0;
4304 state->pagedresults_cookie = NULL;
4305 state->entries = NULL;
4306 state->group_type = type;
4307 state->ldap2displayentry = ldapgroup2displayentry;
4309 if ((state->filter == NULL) || (state->attrs == NULL)) {
4310 DEBUG(0, ("talloc failed\n"));
4311 return False;
4314 search->private_data = state;
4315 search->next_entry = ldapsam_search_next_entry;
4316 search->search_end = ldapsam_search_end;
4318 return ldapsam_search_firstpage(search);
4321 static BOOL ldapsam_search_groups(struct pdb_methods *methods,
4322 struct pdb_search *search)
4324 return ldapsam_search_grouptype(methods, search, SID_NAME_DOM_GRP);
4327 static BOOL ldapsam_search_aliases(struct pdb_methods *methods,
4328 struct pdb_search *search,
4329 const DOM_SID *sid)
4331 if (sid_check_is_domain(sid))
4332 return ldapsam_search_grouptype(methods, search,
4333 SID_NAME_ALIAS);
4335 if (sid_check_is_builtin(sid))
4336 return ldapsam_search_grouptype(methods, search,
4337 SID_NAME_WKN_GRP);
4339 DEBUG(5, ("Don't know SID %s\n", sid_string_static(sid)));
4340 return False;
4343 static BOOL ldapsam_rid_algorithm(struct pdb_methods *methods)
4345 return False;
4348 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4349 uint32 *rid)
4351 struct smbldap_state *smbldap_state = priv->smbldap_state;
4353 LDAPMessage *result = NULL;
4354 LDAPMessage *entry = NULL;
4355 LDAPMod **mods = NULL;
4356 NTSTATUS status;
4357 char *value;
4358 int rc;
4359 uint32 nextRid = 0;
4361 TALLOC_CTX *mem_ctx;
4363 mem_ctx = talloc_new(NULL);
4364 if (mem_ctx == NULL) {
4365 DEBUG(0, ("talloc_new failed\n"));
4366 return NT_STATUS_NO_MEMORY;
4369 status = smbldap_search_domain_info(smbldap_state, &result,
4370 get_global_sam_name(), False);
4371 if (!NT_STATUS_IS_OK(status)) {
4372 DEBUG(3, ("Could not get domain info: %s\n",
4373 nt_errstr(status)));
4374 goto done;
4377 talloc_autofree_ldapmsg(mem_ctx, result);
4379 entry = ldap_first_entry(priv2ld(priv), result);
4380 if (entry == NULL) {
4381 DEBUG(0, ("Could not get domain info entry\n"));
4382 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4383 goto done;
4386 /* Find the largest of the three attributes "sambaNextRid",
4387 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4388 concept of differentiating between user and group rids, and will
4389 use only "sambaNextRid" in the future. But for compatibility
4390 reasons I look if others have chosen different strategies -- VL */
4392 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4393 "sambaNextRid", mem_ctx);
4394 if (value != NULL) {
4395 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4396 nextRid = MAX(nextRid, tmp);
4399 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4400 "sambaNextUserRid", mem_ctx);
4401 if (value != NULL) {
4402 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4403 nextRid = MAX(nextRid, tmp);
4406 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4407 "sambaNextGroupRid", mem_ctx);
4408 if (value != NULL) {
4409 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4410 nextRid = MAX(nextRid, tmp);
4413 if (nextRid == 0) {
4414 nextRid = BASE_RID-1;
4417 nextRid += 1;
4419 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4420 talloc_asprintf(mem_ctx, "%d", nextRid));
4421 talloc_autofree_ldapmod(mem_ctx, mods);
4423 rc = smbldap_modify(smbldap_state,
4424 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry),
4425 mods);
4427 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4428 * please retry" */
4430 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4432 done:
4433 if (NT_STATUS_IS_OK(status)) {
4434 *rid = nextRid;
4437 TALLOC_FREE(mem_ctx);
4438 return status;
4441 static BOOL ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4443 int i;
4445 for (i=0; i<10; i++) {
4446 NTSTATUS result = ldapsam_get_new_rid(methods->private_data,
4447 rid);
4448 if (NT_STATUS_IS_OK(result)) {
4449 return True;
4452 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4453 return False;
4456 /* The ldap update failed (maybe a race condition), retry */
4459 /* Tried 10 times, fail. */
4460 return False;
4463 static BOOL ldapsam_sid_to_id(struct pdb_methods *methods,
4464 const DOM_SID *sid,
4465 union unid_t *id, enum SID_NAME_USE *type)
4467 struct ldapsam_privates *priv = methods->private_data;
4468 char *filter;
4469 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4470 NULL };
4471 LDAPMessage *result = NULL;
4472 LDAPMessage *entry = NULL;
4473 BOOL ret = False;
4474 char *value;
4475 int rc;
4477 TALLOC_CTX *mem_ctx;
4479 mem_ctx = talloc_new(NULL);
4480 if (mem_ctx == NULL) {
4481 DEBUG(0, ("talloc_new failed\n"));
4482 return False;
4485 filter = talloc_asprintf(mem_ctx,
4486 "(&(sambaSid=%s)"
4487 "(|(objectClass=sambaGroupMapping)"
4488 "(objectClass=sambaSamAccount)))",
4489 sid_string_static(sid));
4490 if (filter == NULL) {
4491 DEBUG(5, ("talloc_asprintf failed\n"));
4492 goto done;
4495 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4496 attrs, &result);
4497 if (rc != LDAP_SUCCESS) {
4498 goto done;
4500 talloc_autofree_ldapmsg(mem_ctx, result);
4502 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4503 DEBUG(10, ("Got %d entries, expected one\n",
4504 ldap_count_entries(priv2ld(priv), result)));
4505 goto done;
4508 entry = ldap_first_entry(priv2ld(priv), result);
4510 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4511 "sambaGroupType", mem_ctx);
4513 if (value != NULL) {
4514 const char *gid_str;
4515 /* It's a group */
4517 gid_str = smbldap_talloc_single_attribute(
4518 priv2ld(priv), entry, "gidNumber", mem_ctx);
4519 if (gid_str == NULL) {
4520 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4521 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4522 entry)));
4523 goto done;
4526 id->gid = strtoul(gid_str, NULL, 10);
4527 *type = strtoul(value, NULL, 10);
4528 ret = True;
4529 goto done;
4532 /* It must be a user */
4534 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4535 "uidNumber", mem_ctx);
4536 if (value == NULL) {
4537 DEBUG(1, ("Could not find uidNumber in %s\n",
4538 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4539 goto done;
4542 id->uid = strtoul(value, NULL, 10);
4543 *type = SID_NAME_USER;
4545 ret = True;
4546 done:
4547 TALLOC_FREE(mem_ctx);
4548 return ret;
4551 /**********************************************************************
4552 Housekeeping
4553 *********************************************************************/
4555 static void free_private_data(void **vp)
4557 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
4559 smbldap_free_struct(&(*ldap_state)->smbldap_state);
4561 if ((*ldap_state)->result != NULL) {
4562 ldap_msgfree((*ldap_state)->result);
4563 (*ldap_state)->result = NULL;
4565 if ((*ldap_state)->domain_dn != NULL) {
4566 SAFE_FREE((*ldap_state)->domain_dn);
4569 *ldap_state = NULL;
4571 /* No need to free any further, as it is talloc()ed */
4574 /*********************************************************************
4575 Intitalise the parts of the pdb_methods structure that are common to
4576 all pdb_ldap modes
4577 *********************************************************************/
4579 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
4581 NTSTATUS nt_status;
4582 struct ldapsam_privates *ldap_state;
4584 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
4585 return nt_status;
4588 (*pdb_method)->name = "ldapsam";
4590 (*pdb_method)->setsampwent = ldapsam_setsampwent;
4591 (*pdb_method)->endsampwent = ldapsam_endsampwent;
4592 (*pdb_method)->getsampwent = ldapsam_getsampwent;
4593 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
4594 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
4595 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
4596 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
4597 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
4598 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
4600 (*pdb_method)->getgrsid = ldapsam_getgrsid;
4601 (*pdb_method)->getgrgid = ldapsam_getgrgid;
4602 (*pdb_method)->getgrnam = ldapsam_getgrnam;
4603 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
4604 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
4605 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
4606 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
4608 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
4609 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
4611 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
4613 (*pdb_method)->rid_algorithm = ldapsam_rid_algorithm;
4614 (*pdb_method)->new_rid = ldapsam_new_rid;
4616 /* TODO: Setup private data and free */
4618 if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
4619 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
4620 return NT_STATUS_NO_MEMORY;
4623 nt_status = smbldap_init(*pdb_method, location, &ldap_state->smbldap_state);
4625 if ( !NT_STATUS_IS_OK(nt_status) ) {
4626 return nt_status;
4629 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
4630 return NT_STATUS_NO_MEMORY;
4633 (*pdb_method)->private_data = ldap_state;
4635 (*pdb_method)->free_private_data = free_private_data;
4637 return NT_STATUS_OK;
4640 /**********************************************************************
4641 Initialise the 'compat' mode for pdb_ldap
4642 *********************************************************************/
4644 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
4646 NTSTATUS nt_status;
4647 struct ldapsam_privates *ldap_state;
4648 char *uri = talloc_strdup( NULL, location );
4650 #ifdef WITH_LDAP_SAMCONFIG
4651 if (!uri) {
4652 int ldap_port = lp_ldap_port();
4654 /* remap default port if not using SSL (ie clear or TLS) */
4655 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
4656 ldap_port = 389;
4659 uri = talloc_asprintf(NULL, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
4660 if (!uri) {
4661 return NT_STATUS_NO_MEMORY;
4663 location = uri;
4665 #endif
4667 if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common( pdb_method, uri ))) {
4668 return nt_status;
4671 /* the module itself stores a copy of the location so throw this one away */
4673 if ( uri )
4674 TALLOC_FREE( uri );
4676 (*pdb_method)->name = "ldapsam_compat";
4678 ldap_state = (*pdb_method)->private_data;
4679 ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
4681 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4683 return NT_STATUS_OK;
4686 /**********************************************************************
4687 Initialise the normal mode for pdb_ldap
4688 *********************************************************************/
4690 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
4692 NTSTATUS nt_status;
4693 struct ldapsam_privates *ldap_state;
4694 uint32 alg_rid_base;
4695 pstring alg_rid_base_string;
4696 LDAPMessage *result = NULL;
4697 LDAPMessage *entry = NULL;
4698 DOM_SID ldap_domain_sid;
4699 DOM_SID secrets_domain_sid;
4700 pstring domain_sid_string;
4701 char *dn;
4703 nt_status = pdb_init_ldapsam_common(pdb_method, location);
4704 if (!NT_STATUS_IS_OK(nt_status)) {
4705 return nt_status;
4708 (*pdb_method)->name = "ldapsam";
4710 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
4711 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
4712 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
4713 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
4714 (*pdb_method)->search_users = ldapsam_search_users;
4715 (*pdb_method)->search_groups = ldapsam_search_groups;
4716 (*pdb_method)->search_aliases = ldapsam_search_aliases;
4718 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
4719 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
4720 (*pdb_method)->enum_group_memberships =
4721 ldapsam_enum_group_memberships;
4722 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
4723 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
4726 ldap_state = (*pdb_method)->private_data;
4727 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
4729 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
4731 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
4732 &result,
4733 ldap_state->domain_name, True);
4735 if ( !NT_STATUS_IS_OK(nt_status) ) {
4736 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
4737 "info, nor add one to the domain\n"));
4738 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
4739 "will be unable to allocate new users/groups, "
4740 "and will risk BDCs having inconsistant SIDs\n"));
4741 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4742 return NT_STATUS_OK;
4745 /* Given that the above might fail, everything below this must be
4746 * optional */
4748 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
4749 result);
4750 if (!entry) {
4751 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
4752 "entry\n"));
4753 ldap_msgfree(result);
4754 return NT_STATUS_UNSUCCESSFUL;
4757 dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
4758 if (!dn) {
4759 return NT_STATUS_UNSUCCESSFUL;
4762 ldap_state->domain_dn = smb_xstrdup(dn);
4763 ldap_memfree(dn);
4765 if (smbldap_get_single_pstring(
4766 ldap_state->smbldap_state->ldap_struct,
4767 entry,
4768 get_userattr_key2string(ldap_state->schema_ver,
4769 LDAP_ATTR_USER_SID),
4770 domain_sid_string)) {
4771 BOOL found_sid;
4772 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
4773 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
4774 "read as a valid SID\n", domain_sid_string));
4775 return NT_STATUS_INVALID_PARAMETER;
4777 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
4778 &secrets_domain_sid);
4779 if (!found_sid || !sid_equal(&secrets_domain_sid,
4780 &ldap_domain_sid)) {
4781 fstring new_sid_str, old_sid_str;
4782 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
4783 "%s based on pdb_ldap results %s -> %s\n",
4784 ldap_state->domain_name,
4785 sid_to_string(old_sid_str,
4786 &secrets_domain_sid),
4787 sid_to_string(new_sid_str,
4788 &ldap_domain_sid)));
4790 /* reset secrets.tdb sid */
4791 secrets_store_domain_sid(ldap_state->domain_name,
4792 &ldap_domain_sid);
4793 DEBUG(1, ("New global sam SID: %s\n",
4794 sid_to_string(new_sid_str,
4795 get_global_sam_sid())));
4797 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
4800 if (smbldap_get_single_pstring(
4801 ldap_state->smbldap_state->ldap_struct,
4802 entry,
4803 get_attr_key2string( dominfo_attr_list,
4804 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
4805 alg_rid_base_string)) {
4806 alg_rid_base = (uint32)atol(alg_rid_base_string);
4807 if (alg_rid_base != algorithmic_rid_base()) {
4808 DEBUG(0, ("The value of 'algorithmic RID base' has "
4809 "changed since the LDAP\n"
4810 "database was initialised. Aborting. \n"));
4811 ldap_msgfree(result);
4812 return NT_STATUS_UNSUCCESSFUL;
4815 ldap_msgfree(result);
4817 return NT_STATUS_OK;
4820 NTSTATUS pdb_ldap_init(void)
4822 NTSTATUS nt_status;
4823 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
4824 return nt_status;
4826 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
4827 return nt_status;
4829 /* Let pdb_nds register backends */
4830 pdb_nds_init();
4832 return NT_STATUS_OK;