s3:ldap: don't search when no values where found
[Samba/wip.git] / source3 / passdb / pdb_ldap.c
blob87df75e7fd7499d2800a5afbe3ea2ac55ca739c3
1 /*
2 Unix SMB/CIFS implementation.
3 LDAP protocol helper functions for SAMBA
4 Copyright (C) Jean François Micouleau 1998
5 Copyright (C) Gerald Carter 2001-2003
6 Copyright (C) Shahms King 2001
7 Copyright (C) Andrew Bartlett 2002-2003
8 Copyright (C) Stefan (metze) Metzmacher 2002-2003
9 Copyright (C) Simo Sorce 2006
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 /* TODO:
27 * persistent connections: if using NSS LDAP, many connections are made
28 * however, using only one within Samba would be nice
30 * Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
32 * Other LDAP based login attributes: accountExpires, etc.
33 * (should be the domain of Samba proper, but the sam_password/struct samu
34 * structures don't have fields for some of these attributes)
36 * SSL is done, but can't get the certificate based authentication to work
37 * against on my test platform (Linux 2.4, OpenLDAP 2.x)
40 /* NOTE: this will NOT work against an Active Directory server
41 * due to the fact that the two password fields cannot be retrieved
42 * from a server; recommend using security = domain in this situation
43 * and/or winbind
46 #include "includes.h"
47 #include "../libcli/auth/libcli_auth.h"
49 #undef DBGC_CLASS
50 #define DBGC_CLASS DBGC_PASSDB
52 #include <lber.h>
53 #include <ldap.h>
56 * Work around versions of the LDAP client libs that don't have the OIDs
57 * defined, or have them defined under the old name.
58 * This functionality is really a factor of the server, not the client
62 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
63 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
64 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
65 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
66 #endif
68 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
69 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
70 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
71 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID ((ber_tag_t) 0x80U)
72 #endif
74 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
75 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
76 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
77 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW ((ber_tag_t) 0x82U)
78 #endif
81 #include "smbldap.h"
83 /**********************************************************************
84 Simple helper function to make stuff better readable
85 **********************************************************************/
87 static LDAP *priv2ld(struct ldapsam_privates *priv)
89 return priv->smbldap_state->ldap_struct;
92 /**********************************************************************
93 Get the attribute name given a user schame version.
94 **********************************************************************/
96 static const char* get_userattr_key2string( int schema_ver, int key )
98 switch ( schema_ver ) {
99 case SCHEMAVER_SAMBAACCOUNT:
100 return get_attr_key2string( attrib_map_v22, key );
102 case SCHEMAVER_SAMBASAMACCOUNT:
103 return get_attr_key2string( attrib_map_v30, key );
105 default:
106 DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
107 break;
109 return NULL;
112 /**********************************************************************
113 Return the list of attribute names given a user schema version.
114 **********************************************************************/
116 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
118 switch ( schema_ver ) {
119 case SCHEMAVER_SAMBAACCOUNT:
120 return get_attr_list( mem_ctx, attrib_map_v22 );
122 case SCHEMAVER_SAMBASAMACCOUNT:
123 return get_attr_list( mem_ctx, attrib_map_v30 );
124 default:
125 DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
126 break;
129 return NULL;
132 /**************************************************************************
133 Return the list of attribute names to delete given a user schema version.
134 **************************************************************************/
136 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
137 int schema_ver )
139 switch ( schema_ver ) {
140 case SCHEMAVER_SAMBAACCOUNT:
141 return get_attr_list( mem_ctx,
142 attrib_map_to_delete_v22 );
144 case SCHEMAVER_SAMBASAMACCOUNT:
145 return get_attr_list( mem_ctx,
146 attrib_map_to_delete_v30 );
147 default:
148 DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
149 break;
152 return NULL;
156 /*******************************************************************
157 Generate the LDAP search filter for the objectclass based on the
158 version of the schema we are using.
159 ******************************************************************/
161 static const char* get_objclass_filter( int schema_ver )
163 fstring objclass_filter;
164 char *result;
166 switch( schema_ver ) {
167 case SCHEMAVER_SAMBAACCOUNT:
168 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
169 break;
170 case SCHEMAVER_SAMBASAMACCOUNT:
171 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
172 break;
173 default:
174 DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
175 objclass_filter[0] = '\0';
176 break;
179 result = talloc_strdup(talloc_tos(), objclass_filter);
180 SMB_ASSERT(result != NULL);
181 return result;
184 /*****************************************************************
185 Scan a sequence number off OpenLDAP's syncrepl contextCSN
186 ******************************************************************/
188 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
190 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
191 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
192 LDAPMessage *msg = NULL;
193 LDAPMessage *entry = NULL;
194 TALLOC_CTX *mem_ctx;
195 char **values = NULL;
196 int rc, num_result, num_values, rid;
197 char *suffix = NULL;
198 char *tok;
199 const char *p;
200 const char **attrs;
202 /* Unfortunatly there is no proper way to detect syncrepl-support in
203 * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
204 * but do not show up in the root-DSE yet. Neither we can query the
205 * subschema-context for the syncProviderSubentry or syncConsumerSubentry
206 * objectclass. Currently we require lp_ldap_suffix() to show up as
207 * namingContext. - Guenther
210 if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
211 return ntstatus;
214 if (!seq_num) {
215 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
216 return ntstatus;
219 if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix())) {
220 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
221 "as top-level namingContext\n", lp_ldap_suffix()));
222 return ntstatus;
225 mem_ctx = talloc_init("ldapsam_get_seq_num");
227 if (mem_ctx == NULL)
228 return NT_STATUS_NO_MEMORY;
230 if ((attrs = TALLOC_ARRAY(mem_ctx, const char *, 2)) == NULL) {
231 ntstatus = NT_STATUS_NO_MEMORY;
232 goto done;
235 /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
236 rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
237 if (rid > 0) {
239 /* consumer syncreplCookie: */
240 /* csn=20050126161620Z#0000001#00#00000 */
241 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
242 attrs[1] = NULL;
243 suffix = talloc_asprintf(mem_ctx,
244 "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
245 if (!suffix) {
246 ntstatus = NT_STATUS_NO_MEMORY;
247 goto done;
249 } else {
251 /* provider contextCSN */
252 /* 20050126161620Z#000009#00#000000 */
253 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
254 attrs[1] = NULL;
255 suffix = talloc_asprintf(mem_ctx,
256 "cn=ldapsync,%s", lp_ldap_suffix());
258 if (!suffix) {
259 ntstatus = NT_STATUS_NO_MEMORY;
260 goto done;
264 rc = smbldap_search(ldap_state->smbldap_state, suffix,
265 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
267 if (rc != LDAP_SUCCESS) {
268 goto done;
271 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
272 if (num_result != 1) {
273 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
274 goto done;
277 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
278 if (entry == NULL) {
279 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
280 goto done;
283 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
284 if (values == NULL) {
285 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
286 goto done;
289 num_values = ldap_count_values(values);
290 if (num_values == 0) {
291 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
292 goto done;
295 p = values[0];
296 if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
297 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
298 goto done;
301 p = tok;
302 if (!strncmp(p, "csn=", strlen("csn=")))
303 p += strlen("csn=");
305 DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
307 *seq_num = generalized_to_unix_time(p);
309 /* very basic sanity check */
310 if (*seq_num <= 0) {
311 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n",
312 (int)*seq_num));
313 goto done;
316 ntstatus = NT_STATUS_OK;
318 done:
319 if (values != NULL)
320 ldap_value_free(values);
321 if (msg != NULL)
322 ldap_msgfree(msg);
323 if (mem_ctx)
324 talloc_destroy(mem_ctx);
326 return ntstatus;
329 /*******************************************************************
330 Run the search by name.
331 ******************************************************************/
333 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
334 const char *user,
335 LDAPMessage ** result,
336 const char **attr)
338 char *filter = NULL;
339 char *escape_user = escape_ldap_string(talloc_tos(), user);
340 int ret = -1;
342 if (!escape_user) {
343 return LDAP_NO_MEMORY;
347 * in the filter expression, replace %u with the real name
348 * so in ldap filter, %u MUST exist :-)
350 filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
351 get_objclass_filter(ldap_state->schema_ver));
352 if (!filter) {
353 TALLOC_FREE(escape_user);
354 return LDAP_NO_MEMORY;
357 * have to use this here because $ is filtered out
358 * in string_sub
361 filter = talloc_all_string_sub(talloc_tos(),
362 filter, "%u", escape_user);
363 TALLOC_FREE(escape_user);
364 if (!filter) {
365 return LDAP_NO_MEMORY;
368 ret = smbldap_search_suffix(ldap_state->smbldap_state,
369 filter, attr, result);
370 TALLOC_FREE(filter);
371 return ret;
374 /*******************************************************************
375 Run the search by rid.
376 ******************************************************************/
378 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
379 uint32 rid, LDAPMessage ** result,
380 const char **attr)
382 char *filter = NULL;
383 int rc;
385 filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
386 get_objclass_filter(ldap_state->schema_ver));
387 if (!filter) {
388 return LDAP_NO_MEMORY;
391 rc = smbldap_search_suffix(ldap_state->smbldap_state,
392 filter, attr, result);
393 TALLOC_FREE(filter);
394 return rc;
397 /*******************************************************************
398 Run the search by SID.
399 ******************************************************************/
401 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
402 const DOM_SID *sid, LDAPMessage ** result,
403 const char **attr)
405 char *filter = NULL;
406 int rc;
407 fstring sid_string;
409 filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
410 get_userattr_key2string(ldap_state->schema_ver,
411 LDAP_ATTR_USER_SID),
412 sid_to_fstring(sid_string, sid),
413 get_objclass_filter(ldap_state->schema_ver));
414 if (!filter) {
415 return LDAP_NO_MEMORY;
418 rc = smbldap_search_suffix(ldap_state->smbldap_state,
419 filter, attr, result);
421 TALLOC_FREE(filter);
422 return rc;
425 /*******************************************************************
426 Delete complete object or objectclass and attrs from
427 object found in search_result depending on lp_ldap_delete_dn
428 ******************************************************************/
430 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
431 TALLOC_CTX *mem_ctx,
432 LDAPMessage *entry,
433 const char *objectclass,
434 const char **attrs)
436 LDAPMod **mods = NULL;
437 char *name;
438 const char *dn;
439 BerElement *ptr = NULL;
441 dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
442 if (dn == NULL) {
443 return LDAP_NO_MEMORY;
446 if (lp_ldap_delete_dn()) {
447 return smbldap_delete(priv->smbldap_state, dn);
450 /* Ok, delete only the SAM attributes */
452 for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
453 name != NULL;
454 name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
455 const char **attrib;
457 /* We are only allowed to delete the attributes that
458 really exist. */
460 for (attrib = attrs; *attrib != NULL; attrib++) {
461 if (strequal(*attrib, name)) {
462 DEBUG(10, ("ldapsam_delete_entry: deleting "
463 "attribute %s\n", name));
464 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
465 NULL);
468 ldap_memfree(name);
471 if (ptr != NULL) {
472 ber_free(ptr, 0);
475 smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
476 talloc_autofree_ldapmod(mem_ctx, mods);
478 return smbldap_modify(priv->smbldap_state, dn, mods);
481 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
483 char *temp;
484 struct tm tm;
486 temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
487 get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
488 talloc_tos());
489 if (!temp) {
490 return (time_t) 0;
493 if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
494 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
495 (char*)temp));
496 TALLOC_FREE(temp);
497 return (time_t) 0;
499 TALLOC_FREE(temp);
500 tzset();
501 return timegm(&tm);
504 /**********************************************************************
505 Initialize struct samu from an LDAP query.
506 (Based on init_sam_from_buffer in pdb_tdb.c)
507 *********************************************************************/
509 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
510 struct samu * sampass,
511 LDAPMessage * entry)
513 time_t logon_time,
514 logoff_time,
515 kickoff_time,
516 pass_last_set_time,
517 pass_can_change_time,
518 pass_must_change_time,
519 ldap_entry_time,
520 bad_password_time;
521 char *username = NULL,
522 *domain = NULL,
523 *nt_username = NULL,
524 *fullname = NULL,
525 *homedir = NULL,
526 *dir_drive = NULL,
527 *logon_script = NULL,
528 *profile_path = NULL,
529 *acct_desc = NULL,
530 *workstations = NULL,
531 *munged_dial = NULL;
532 uint32 user_rid;
533 uint8 smblmpwd[LM_HASH_LEN],
534 smbntpwd[NT_HASH_LEN];
535 bool use_samba_attrs = True;
536 uint32 acct_ctrl = 0;
537 uint16 logon_divs;
538 uint16 bad_password_count = 0,
539 logon_count = 0;
540 uint32 hours_len;
541 uint8 hours[MAX_HOURS_LEN];
542 char *temp = NULL;
543 LOGIN_CACHE *cache_entry = NULL;
544 uint32 pwHistLen;
545 bool expand_explicit = lp_passdb_expand_explicit();
546 bool ret = false;
547 TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
549 if (!ctx) {
550 return false;
552 if (sampass == NULL || ldap_state == NULL || entry == NULL) {
553 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
554 goto fn_exit;
557 if (priv2ld(ldap_state) == NULL) {
558 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
559 "ldap_struct is NULL!\n"));
560 goto fn_exit;
563 if (!(username = smbldap_talloc_smallest_attribute(priv2ld(ldap_state),
564 entry,
565 "uid",
566 ctx))) {
567 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
568 "this user!\n"));
569 goto fn_exit;
572 DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
574 nt_username = talloc_strdup(ctx, username);
575 if (!nt_username) {
576 goto fn_exit;
579 domain = talloc_strdup(ctx, ldap_state->domain_name);
580 if (!domain) {
581 goto fn_exit;
584 pdb_set_username(sampass, username, PDB_SET);
586 pdb_set_domain(sampass, domain, PDB_DEFAULT);
587 pdb_set_nt_username(sampass, nt_username, PDB_SET);
589 /* deal with different attributes between the schema first */
591 if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
592 if ((temp = smbldap_talloc_single_attribute(
593 ldap_state->smbldap_state->ldap_struct,
594 entry,
595 get_userattr_key2string(ldap_state->schema_ver,
596 LDAP_ATTR_USER_SID),
597 ctx))!=NULL) {
598 pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
600 } else {
601 if ((temp = smbldap_talloc_single_attribute(
602 ldap_state->smbldap_state->ldap_struct,
603 entry,
604 get_userattr_key2string(ldap_state->schema_ver,
605 LDAP_ATTR_USER_RID),
606 ctx))!=NULL) {
607 user_rid = (uint32)atol(temp);
608 pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
612 if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
613 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n",
614 get_userattr_key2string(ldap_state->schema_ver,
615 LDAP_ATTR_USER_SID),
616 get_userattr_key2string(ldap_state->schema_ver,
617 LDAP_ATTR_USER_RID),
618 username));
619 return False;
622 temp = smbldap_talloc_single_attribute(
623 ldap_state->smbldap_state->ldap_struct,
624 entry,
625 get_userattr_key2string(ldap_state->schema_ver,
626 LDAP_ATTR_PWD_LAST_SET),
627 ctx);
628 if (temp) {
629 pass_last_set_time = (time_t) atol(temp);
630 pdb_set_pass_last_set_time(sampass,
631 pass_last_set_time, PDB_SET);
634 temp = smbldap_talloc_single_attribute(
635 ldap_state->smbldap_state->ldap_struct,
636 entry,
637 get_userattr_key2string(ldap_state->schema_ver,
638 LDAP_ATTR_LOGON_TIME),
639 ctx);
640 if (temp) {
641 logon_time = (time_t) atol(temp);
642 pdb_set_logon_time(sampass, logon_time, PDB_SET);
645 temp = smbldap_talloc_single_attribute(
646 ldap_state->smbldap_state->ldap_struct,
647 entry,
648 get_userattr_key2string(ldap_state->schema_ver,
649 LDAP_ATTR_LOGOFF_TIME),
650 ctx);
651 if (temp) {
652 logoff_time = (time_t) atol(temp);
653 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
656 temp = smbldap_talloc_single_attribute(
657 ldap_state->smbldap_state->ldap_struct,
658 entry,
659 get_userattr_key2string(ldap_state->schema_ver,
660 LDAP_ATTR_KICKOFF_TIME),
661 ctx);
662 if (temp) {
663 kickoff_time = (time_t) atol(temp);
664 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
667 temp = smbldap_talloc_single_attribute(
668 ldap_state->smbldap_state->ldap_struct,
669 entry,
670 get_userattr_key2string(ldap_state->schema_ver,
671 LDAP_ATTR_PWD_CAN_CHANGE),
672 ctx);
673 if (temp) {
674 pass_can_change_time = (time_t) atol(temp);
675 pdb_set_pass_can_change_time(sampass,
676 pass_can_change_time, PDB_SET);
679 temp = smbldap_talloc_single_attribute(
680 ldap_state->smbldap_state->ldap_struct,
681 entry,
682 get_userattr_key2string(ldap_state->schema_ver,
683 LDAP_ATTR_PWD_MUST_CHANGE),
684 ctx);
685 if (temp) {
686 pass_must_change_time = (time_t) atol(temp);
687 pdb_set_pass_must_change_time(sampass,
688 pass_must_change_time, PDB_SET);
691 /* recommend that 'gecos' and 'displayName' should refer to the same
692 * attribute OID. userFullName depreciated, only used by Samba
693 * primary rules of LDAP: don't make a new attribute when one is already defined
694 * that fits your needs; using cn then displayName rather than 'userFullName'
697 fullname = smbldap_talloc_single_attribute(
698 ldap_state->smbldap_state->ldap_struct,
699 entry,
700 get_userattr_key2string(ldap_state->schema_ver,
701 LDAP_ATTR_DISPLAY_NAME),
702 ctx);
703 if (fullname) {
704 pdb_set_fullname(sampass, fullname, PDB_SET);
705 } else {
706 fullname = smbldap_talloc_single_attribute(
707 ldap_state->smbldap_state->ldap_struct,
708 entry,
709 get_userattr_key2string(ldap_state->schema_ver,
710 LDAP_ATTR_CN),
711 ctx);
712 if (fullname) {
713 pdb_set_fullname(sampass, fullname, PDB_SET);
717 dir_drive = smbldap_talloc_single_attribute(
718 ldap_state->smbldap_state->ldap_struct,
719 entry,
720 get_userattr_key2string(ldap_state->schema_ver,
721 LDAP_ATTR_HOME_DRIVE),
722 ctx);
723 if (dir_drive) {
724 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
725 } else {
726 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
729 homedir = smbldap_talloc_single_attribute(
730 ldap_state->smbldap_state->ldap_struct,
731 entry,
732 get_userattr_key2string(ldap_state->schema_ver,
733 LDAP_ATTR_HOME_PATH),
734 ctx);
735 if (homedir) {
736 if (expand_explicit) {
737 homedir = talloc_sub_basic(ctx,
738 username,
739 domain,
740 homedir);
741 if (!homedir) {
742 goto fn_exit;
745 pdb_set_homedir(sampass, homedir, PDB_SET);
746 } else {
747 pdb_set_homedir(sampass,
748 talloc_sub_basic(ctx, username, domain,
749 lp_logon_home()),
750 PDB_DEFAULT);
753 logon_script = smbldap_talloc_single_attribute(
754 ldap_state->smbldap_state->ldap_struct,
755 entry,
756 get_userattr_key2string(ldap_state->schema_ver,
757 LDAP_ATTR_LOGON_SCRIPT),
758 ctx);
759 if (logon_script) {
760 if (expand_explicit) {
761 logon_script = talloc_sub_basic(ctx,
762 username,
763 domain,
764 logon_script);
765 if (!logon_script) {
766 goto fn_exit;
769 pdb_set_logon_script(sampass, logon_script, PDB_SET);
770 } else {
771 pdb_set_logon_script(sampass,
772 talloc_sub_basic(ctx, username, domain,
773 lp_logon_script()),
774 PDB_DEFAULT );
777 profile_path = smbldap_talloc_single_attribute(
778 ldap_state->smbldap_state->ldap_struct,
779 entry,
780 get_userattr_key2string(ldap_state->schema_ver,
781 LDAP_ATTR_PROFILE_PATH),
782 ctx);
783 if (profile_path) {
784 if (expand_explicit) {
785 profile_path = talloc_sub_basic(ctx,
786 username,
787 domain,
788 profile_path);
789 if (!profile_path) {
790 goto fn_exit;
793 pdb_set_profile_path(sampass, profile_path, PDB_SET);
794 } else {
795 pdb_set_profile_path(sampass,
796 talloc_sub_basic(ctx, username, domain,
797 lp_logon_path()),
798 PDB_DEFAULT );
801 acct_desc = smbldap_talloc_single_attribute(
802 ldap_state->smbldap_state->ldap_struct,
803 entry,
804 get_userattr_key2string(ldap_state->schema_ver,
805 LDAP_ATTR_DESC),
806 ctx);
807 if (acct_desc) {
808 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
811 workstations = smbldap_talloc_single_attribute(
812 ldap_state->smbldap_state->ldap_struct,
813 entry,
814 get_userattr_key2string(ldap_state->schema_ver,
815 LDAP_ATTR_USER_WKS),
816 ctx);
817 if (workstations) {
818 pdb_set_workstations(sampass, workstations, PDB_SET);
821 munged_dial = smbldap_talloc_single_attribute(
822 ldap_state->smbldap_state->ldap_struct,
823 entry,
824 get_userattr_key2string(ldap_state->schema_ver,
825 LDAP_ATTR_MUNGED_DIAL),
826 ctx);
827 if (munged_dial) {
828 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
831 /* FIXME: hours stuff should be cleaner */
833 logon_divs = 168;
834 hours_len = 21;
835 memset(hours, 0xff, hours_len);
837 if (ldap_state->is_nds_ldap) {
838 char *user_dn;
839 size_t pwd_len;
840 char clear_text_pw[512];
842 /* Make call to Novell eDirectory ldap extension to get clear text password.
843 NOTE: This will only work if we have an SSL connection to eDirectory. */
844 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
845 if (user_dn != NULL) {
846 DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
848 pwd_len = sizeof(clear_text_pw);
849 if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
850 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
851 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
852 TALLOC_FREE(user_dn);
853 return False;
855 ZERO_STRUCT(smblmpwd);
856 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
857 TALLOC_FREE(user_dn);
858 return False;
860 ZERO_STRUCT(smbntpwd);
861 use_samba_attrs = False;
864 TALLOC_FREE(user_dn);
866 } else {
867 DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
871 if (use_samba_attrs) {
872 temp = smbldap_talloc_single_attribute(
873 ldap_state->smbldap_state->ldap_struct,
874 entry,
875 get_userattr_key2string(ldap_state->schema_ver,
876 LDAP_ATTR_LMPW),
877 ctx);
878 if (temp) {
879 pdb_gethexpwd(temp, smblmpwd);
880 memset((char *)temp, '\0', strlen(temp)+1);
881 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
882 goto fn_exit;
884 ZERO_STRUCT(smblmpwd);
887 temp = smbldap_talloc_single_attribute(
888 ldap_state->smbldap_state->ldap_struct,
889 entry,
890 get_userattr_key2string(ldap_state->schema_ver,
891 LDAP_ATTR_NTPW),
892 ctx);
893 if (temp) {
894 pdb_gethexpwd(temp, smbntpwd);
895 memset((char *)temp, '\0', strlen(temp)+1);
896 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
897 goto fn_exit;
899 ZERO_STRUCT(smbntpwd);
903 pwHistLen = 0;
905 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
906 if (pwHistLen > 0){
907 uint8 *pwhist = NULL;
908 int i;
909 char *history_string = TALLOC_ARRAY(ctx, char,
910 MAX_PW_HISTORY_LEN*64);
912 if (!history_string) {
913 goto fn_exit;
916 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
918 if ((pwhist = TALLOC_ARRAY(ctx, uint8,
919 pwHistLen * PW_HISTORY_ENTRY_LEN)) ==
920 NULL){
921 DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
922 goto fn_exit;
924 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
926 if (smbldap_get_single_attribute(
927 ldap_state->smbldap_state->ldap_struct,
928 entry,
929 get_userattr_key2string(ldap_state->schema_ver,
930 LDAP_ATTR_PWD_HISTORY),
931 history_string,
932 MAX_PW_HISTORY_LEN*64)) {
933 bool hex_failed = false;
934 for (i = 0; i < pwHistLen; i++){
935 /* Get the 16 byte salt. */
936 if (!pdb_gethexpwd(&history_string[i*64],
937 &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
938 hex_failed = true;
939 break;
941 /* Get the 16 byte MD5 hash of salt+passwd. */
942 if (!pdb_gethexpwd(&history_string[(i*64)+32],
943 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
944 PW_HISTORY_SALT_LEN])) {
945 hex_failed = True;
946 break;
949 if (hex_failed) {
950 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
951 username));
952 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
955 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
956 goto fn_exit;
960 temp = smbldap_talloc_single_attribute(
961 ldap_state->smbldap_state->ldap_struct,
962 entry,
963 get_userattr_key2string(ldap_state->schema_ver,
964 LDAP_ATTR_ACB_INFO),
965 ctx);
966 if (temp) {
967 acct_ctrl = pdb_decode_acct_ctrl(temp);
969 if (acct_ctrl == 0) {
970 acct_ctrl |= ACB_NORMAL;
973 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
974 } else {
975 acct_ctrl |= ACB_NORMAL;
978 pdb_set_hours_len(sampass, hours_len, PDB_SET);
979 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
981 temp = smbldap_talloc_single_attribute(
982 ldap_state->smbldap_state->ldap_struct,
983 entry,
984 get_userattr_key2string(ldap_state->schema_ver,
985 LDAP_ATTR_BAD_PASSWORD_COUNT),
986 ctx);
987 if (temp) {
988 bad_password_count = (uint32) atol(temp);
989 pdb_set_bad_password_count(sampass,
990 bad_password_count, PDB_SET);
993 temp = smbldap_talloc_single_attribute(
994 ldap_state->smbldap_state->ldap_struct,
995 entry,
996 get_userattr_key2string(ldap_state->schema_ver,
997 LDAP_ATTR_BAD_PASSWORD_TIME),
998 ctx);
999 if (temp) {
1000 bad_password_time = (time_t) atol(temp);
1001 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
1005 temp = smbldap_talloc_single_attribute(
1006 ldap_state->smbldap_state->ldap_struct,
1007 entry,
1008 get_userattr_key2string(ldap_state->schema_ver,
1009 LDAP_ATTR_LOGON_COUNT),
1010 ctx);
1011 if (temp) {
1012 logon_count = (uint32) atol(temp);
1013 pdb_set_logon_count(sampass, logon_count, PDB_SET);
1016 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
1018 temp = smbldap_talloc_single_attribute(
1019 ldap_state->smbldap_state->ldap_struct,
1020 entry,
1021 get_userattr_key2string(ldap_state->schema_ver,
1022 LDAP_ATTR_LOGON_HOURS),
1023 ctx);
1024 if (temp) {
1025 pdb_gethexhours(temp, hours);
1026 memset((char *)temp, '\0', strlen(temp) +1);
1027 pdb_set_hours(sampass, hours, PDB_SET);
1028 ZERO_STRUCT(hours);
1031 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
1032 temp = smbldap_talloc_single_attribute(
1033 priv2ld(ldap_state),
1034 entry,
1035 "uidNumber",
1036 ctx);
1037 if (temp) {
1038 /* We've got a uid, feed the cache */
1039 uid_t uid = strtoul(temp, NULL, 10);
1040 store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
1044 /* check the timestamp of the cache vs ldap entry */
1045 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1046 entry))) {
1047 ret = true;
1048 goto fn_exit;
1051 /* see if we have newer updates */
1052 if (!(cache_entry = login_cache_read(sampass))) {
1053 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1054 (unsigned int)pdb_get_bad_password_count(sampass),
1055 (unsigned int)pdb_get_bad_password_time(sampass)));
1056 ret = true;
1057 goto fn_exit;
1060 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1061 (unsigned int)ldap_entry_time,
1062 (unsigned int)cache_entry->entry_timestamp,
1063 (unsigned int)cache_entry->bad_password_time));
1065 if (ldap_entry_time > cache_entry->entry_timestamp) {
1066 /* cache is older than directory , so
1067 we need to delete the entry but allow the
1068 fields to be written out */
1069 login_cache_delentry(sampass);
1070 } else {
1071 /* read cache in */
1072 pdb_set_acct_ctrl(sampass,
1073 pdb_get_acct_ctrl(sampass) |
1074 (cache_entry->acct_ctrl & ACB_AUTOLOCK),
1075 PDB_SET);
1076 pdb_set_bad_password_count(sampass,
1077 cache_entry->bad_password_count,
1078 PDB_SET);
1079 pdb_set_bad_password_time(sampass,
1080 cache_entry->bad_password_time,
1081 PDB_SET);
1084 ret = true;
1086 fn_exit:
1088 TALLOC_FREE(ctx);
1089 SAFE_FREE(cache_entry);
1090 return ret;
1093 /**********************************************************************
1094 Initialize the ldap db from a struct samu. Called on update.
1095 (Based on init_buffer_from_sam in pdb_tdb.c)
1096 *********************************************************************/
1098 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1099 LDAPMessage *existing,
1100 LDAPMod *** mods, struct samu * sampass,
1101 bool (*need_update)(const struct samu *,
1102 enum pdb_elements))
1104 char *temp = NULL;
1105 uint32 rid;
1107 if (mods == NULL || sampass == NULL) {
1108 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1109 return False;
1112 *mods = NULL;
1115 * took out adding "objectclass: sambaAccount"
1116 * do this on a per-mod basis
1118 if (need_update(sampass, PDB_USERNAME)) {
1119 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1120 "uid", pdb_get_username(sampass));
1121 if (ldap_state->is_nds_ldap) {
1122 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1123 "cn", pdb_get_username(sampass));
1124 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1125 "sn", pdb_get_username(sampass));
1129 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1131 /* only update the RID if we actually need to */
1132 if (need_update(sampass, PDB_USERSID)) {
1133 fstring sid_string;
1134 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
1136 switch ( ldap_state->schema_ver ) {
1137 case SCHEMAVER_SAMBAACCOUNT:
1138 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
1139 DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1140 sid_string_dbg(user_sid),
1141 sid_string_dbg(
1142 &ldap_state->domain_sid)));
1143 return False;
1145 if (asprintf(&temp, "%i", rid) < 0) {
1146 return false;
1148 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1149 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
1150 temp);
1151 SAFE_FREE(temp);
1152 break;
1154 case SCHEMAVER_SAMBASAMACCOUNT:
1155 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1156 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1157 sid_to_fstring(sid_string, user_sid));
1158 break;
1160 default:
1161 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1162 break;
1166 /* we don't need to store the primary group RID - so leaving it
1167 'free' to hang off the unix primary group makes life easier */
1169 if (need_update(sampass, PDB_GROUPSID)) {
1170 fstring sid_string;
1171 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1173 switch ( ldap_state->schema_ver ) {
1174 case SCHEMAVER_SAMBAACCOUNT:
1175 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1176 DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1177 sid_string_dbg(group_sid),
1178 sid_string_dbg(
1179 &ldap_state->domain_sid)));
1180 return False;
1183 if (asprintf(&temp, "%i", rid) < 0) {
1184 return false;
1186 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1187 get_userattr_key2string(ldap_state->schema_ver,
1188 LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1189 SAFE_FREE(temp);
1190 break;
1192 case SCHEMAVER_SAMBASAMACCOUNT:
1193 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1194 get_userattr_key2string(ldap_state->schema_ver,
1195 LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1196 break;
1198 default:
1199 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1200 break;
1205 /* displayName, cn, and gecos should all be the same
1206 * most easily accomplished by giving them the same OID
1207 * gecos isn't set here b/c it should be handled by the
1208 * add-user script
1209 * We change displayName only and fall back to cn if
1210 * it does not exist.
1213 if (need_update(sampass, PDB_FULLNAME))
1214 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1215 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME),
1216 pdb_get_fullname(sampass));
1218 if (need_update(sampass, PDB_ACCTDESC))
1219 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1220 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC),
1221 pdb_get_acct_desc(sampass));
1223 if (need_update(sampass, PDB_WORKSTATIONS))
1224 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1225 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS),
1226 pdb_get_workstations(sampass));
1228 if (need_update(sampass, PDB_MUNGEDDIAL))
1229 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1230 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL),
1231 pdb_get_munged_dial(sampass));
1233 if (need_update(sampass, PDB_SMBHOME))
1234 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1235 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH),
1236 pdb_get_homedir(sampass));
1238 if (need_update(sampass, PDB_DRIVE))
1239 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1240 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE),
1241 pdb_get_dir_drive(sampass));
1243 if (need_update(sampass, PDB_LOGONSCRIPT))
1244 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1245 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT),
1246 pdb_get_logon_script(sampass));
1248 if (need_update(sampass, PDB_PROFILE))
1249 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1250 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH),
1251 pdb_get_profile_path(sampass));
1253 if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1254 return false;
1256 if (need_update(sampass, PDB_LOGONTIME))
1257 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1258 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1259 SAFE_FREE(temp);
1261 if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1262 return false;
1264 if (need_update(sampass, PDB_LOGOFFTIME))
1265 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1266 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1267 SAFE_FREE(temp);
1269 if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1270 return false;
1272 if (need_update(sampass, PDB_KICKOFFTIME))
1273 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1274 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1275 SAFE_FREE(temp);
1277 if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1278 return false;
1280 if (need_update(sampass, PDB_CANCHANGETIME))
1281 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1282 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1283 SAFE_FREE(temp);
1285 if (asprintf(&temp, "%li", (long int)pdb_get_pass_must_change_time(sampass)) < 0) {
1286 return false;
1288 if (need_update(sampass, PDB_MUSTCHANGETIME))
1289 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1290 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1291 SAFE_FREE(temp);
1293 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1294 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1296 if (need_update(sampass, PDB_LMPASSWD)) {
1297 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1298 if (lm_pw) {
1299 char pwstr[34];
1300 pdb_sethexpwd(pwstr, lm_pw,
1301 pdb_get_acct_ctrl(sampass));
1302 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1303 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1304 pwstr);
1305 } else {
1306 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1307 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1308 NULL);
1311 if (need_update(sampass, PDB_NTPASSWD)) {
1312 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1313 if (nt_pw) {
1314 char pwstr[34];
1315 pdb_sethexpwd(pwstr, nt_pw,
1316 pdb_get_acct_ctrl(sampass));
1317 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1318 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1319 pwstr);
1320 } else {
1321 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1322 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1323 NULL);
1327 if (need_update(sampass, PDB_PWHISTORY)) {
1328 char *pwstr = NULL;
1329 uint32 pwHistLen = 0;
1330 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1332 pwstr = SMB_MALLOC_ARRAY(char, 1024);
1333 if (!pwstr) {
1334 return false;
1336 if (pwHistLen == 0) {
1337 /* Remove any password history from the LDAP store. */
1338 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1339 pwstr[64] = '\0';
1340 } else {
1341 int i;
1342 uint32 currHistLen = 0;
1343 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1344 if (pwhist != NULL) {
1345 /* We can only store (1024-1/64 password history entries. */
1346 pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1347 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1348 /* Store the salt. */
1349 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1350 /* Followed by the md5 hash of salt + md4 hash */
1351 pdb_sethexpwd(&pwstr[(i*64)+32],
1352 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1353 DEBUG(100, ("pwstr=%s\n", pwstr));
1357 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1358 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1359 pwstr);
1360 SAFE_FREE(pwstr);
1363 if (need_update(sampass, PDB_PASSLASTSET)) {
1364 if (asprintf(&temp, "%li",
1365 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1366 return false;
1368 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1369 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1370 temp);
1371 SAFE_FREE(temp);
1375 if (need_update(sampass, PDB_HOURS)) {
1376 const uint8 *hours = pdb_get_hours(sampass);
1377 if (hours) {
1378 char hourstr[44];
1379 pdb_sethexhours(hourstr, hours);
1380 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1381 existing,
1382 mods,
1383 get_userattr_key2string(ldap_state->schema_ver,
1384 LDAP_ATTR_LOGON_HOURS),
1385 hourstr);
1389 if (need_update(sampass, PDB_ACCTCTRL))
1390 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1391 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1392 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1394 /* password lockout cache:
1395 - If we are now autolocking or clearing, we write to ldap
1396 - If we are clearing, we delete the cache entry
1397 - If the count is > 0, we update the cache
1399 This even means when autolocking, we cache, just in case the
1400 update doesn't work, and we have to cache the autolock flag */
1402 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1403 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1404 uint16 badcount = pdb_get_bad_password_count(sampass);
1405 time_t badtime = pdb_get_bad_password_time(sampass);
1406 uint32 pol;
1407 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1409 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1410 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1412 if ((badcount >= pol) || (badcount == 0)) {
1413 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1414 (unsigned int)badcount, (unsigned int)badtime));
1415 if (asprintf(&temp, "%li", (long)badcount) < 0) {
1416 return false;
1418 smbldap_make_mod(
1419 ldap_state->smbldap_state->ldap_struct,
1420 existing, mods,
1421 get_userattr_key2string(
1422 ldap_state->schema_ver,
1423 LDAP_ATTR_BAD_PASSWORD_COUNT),
1424 temp);
1425 SAFE_FREE(temp);
1427 if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1428 return false;
1430 smbldap_make_mod(
1431 ldap_state->smbldap_state->ldap_struct,
1432 existing, mods,
1433 get_userattr_key2string(
1434 ldap_state->schema_ver,
1435 LDAP_ATTR_BAD_PASSWORD_TIME),
1436 temp);
1437 SAFE_FREE(temp);
1439 if (badcount == 0) {
1440 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1441 login_cache_delentry(sampass);
1442 } else {
1443 LOGIN_CACHE cache_entry;
1445 cache_entry.entry_timestamp = time(NULL);
1446 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1447 cache_entry.bad_password_count = badcount;
1448 cache_entry.bad_password_time = badtime;
1450 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1451 login_cache_write(sampass, cache_entry);
1455 return True;
1458 /**********************************************************************
1459 End enumeration of the LDAP password list.
1460 *********************************************************************/
1462 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1464 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1465 if (ldap_state->result) {
1466 ldap_msgfree(ldap_state->result);
1467 ldap_state->result = NULL;
1471 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1472 const char *new_attr)
1474 int i;
1476 if (new_attr == NULL) {
1477 return;
1480 for (i=0; (*attr_list)[i] != NULL; i++) {
1484 (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1485 const char *, i+2);
1486 SMB_ASSERT((*attr_list) != NULL);
1487 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1488 (*attr_list)[i+1] = NULL;
1491 /**********************************************************************
1492 Get struct samu entry from LDAP by username.
1493 *********************************************************************/
1495 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1497 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1498 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1499 LDAPMessage *result = NULL;
1500 LDAPMessage *entry = NULL;
1501 int count;
1502 const char ** attr_list;
1503 int rc;
1505 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1506 append_attr(user, &attr_list,
1507 get_userattr_key2string(ldap_state->schema_ver,
1508 LDAP_ATTR_MOD_TIMESTAMP));
1509 append_attr(user, &attr_list, "uidNumber");
1510 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1511 attr_list);
1512 TALLOC_FREE( attr_list );
1514 if ( rc != LDAP_SUCCESS )
1515 return NT_STATUS_NO_SUCH_USER;
1517 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1519 if (count < 1) {
1520 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1521 ldap_msgfree(result);
1522 return NT_STATUS_NO_SUCH_USER;
1523 } else if (count > 1) {
1524 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1525 ldap_msgfree(result);
1526 return NT_STATUS_NO_SUCH_USER;
1529 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1530 if (entry) {
1531 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1532 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1533 ldap_msgfree(result);
1534 return NT_STATUS_NO_SUCH_USER;
1536 pdb_set_backend_private_data(user, result, NULL,
1537 my_methods, PDB_CHANGED);
1538 talloc_autofree_ldapmsg(user, result);
1539 ret = NT_STATUS_OK;
1540 } else {
1541 ldap_msgfree(result);
1543 return ret;
1546 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1547 const DOM_SID *sid, LDAPMessage **result)
1549 int rc = -1;
1550 const char ** attr_list;
1551 uint32 rid;
1553 switch ( ldap_state->schema_ver ) {
1554 case SCHEMAVER_SAMBASAMACCOUNT: {
1555 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1556 if (tmp_ctx == NULL) {
1557 return LDAP_NO_MEMORY;
1560 attr_list = get_userattr_list(tmp_ctx,
1561 ldap_state->schema_ver);
1562 append_attr(tmp_ctx, &attr_list,
1563 get_userattr_key2string(
1564 ldap_state->schema_ver,
1565 LDAP_ATTR_MOD_TIMESTAMP));
1566 append_attr(tmp_ctx, &attr_list, "uidNumber");
1567 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1568 result, attr_list);
1569 TALLOC_FREE(tmp_ctx);
1571 if ( rc != LDAP_SUCCESS )
1572 return rc;
1573 break;
1576 case SCHEMAVER_SAMBAACCOUNT:
1577 if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1578 return rc;
1581 attr_list = get_userattr_list(NULL,
1582 ldap_state->schema_ver);
1583 rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1584 TALLOC_FREE( attr_list );
1586 if ( rc != LDAP_SUCCESS )
1587 return rc;
1588 break;
1590 return rc;
1593 /**********************************************************************
1594 Get struct samu entry from LDAP by SID.
1595 *********************************************************************/
1597 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1599 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1600 LDAPMessage *result = NULL;
1601 LDAPMessage *entry = NULL;
1602 int count;
1603 int rc;
1605 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1606 sid, &result);
1607 if (rc != LDAP_SUCCESS)
1608 return NT_STATUS_NO_SUCH_USER;
1610 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1612 if (count < 1) {
1613 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1614 "count=%d\n", sid_string_dbg(sid), count));
1615 ldap_msgfree(result);
1616 return NT_STATUS_NO_SUCH_USER;
1617 } else if (count > 1) {
1618 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1619 "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1620 count));
1621 ldap_msgfree(result);
1622 return NT_STATUS_NO_SUCH_USER;
1625 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1626 if (!entry) {
1627 ldap_msgfree(result);
1628 return NT_STATUS_NO_SUCH_USER;
1631 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1632 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1633 ldap_msgfree(result);
1634 return NT_STATUS_NO_SUCH_USER;
1637 pdb_set_backend_private_data(user, result, NULL,
1638 my_methods, PDB_CHANGED);
1639 talloc_autofree_ldapmsg(user, result);
1640 return NT_STATUS_OK;
1643 /********************************************************************
1644 Do the actual modification - also change a plaintext passord if
1645 it it set.
1646 **********************************************************************/
1648 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1649 struct samu *newpwd, char *dn,
1650 LDAPMod **mods, int ldap_op,
1651 bool (*need_update)(const struct samu *, enum pdb_elements))
1653 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1654 int rc;
1656 if (!newpwd || !dn) {
1657 return NT_STATUS_INVALID_PARAMETER;
1660 if (!mods) {
1661 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1662 /* may be password change below however */
1663 } else {
1664 switch(ldap_op) {
1665 case LDAP_MOD_ADD:
1666 if (ldap_state->is_nds_ldap) {
1667 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1668 "objectclass",
1669 "inetOrgPerson");
1670 } else {
1671 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1672 "objectclass",
1673 LDAP_OBJ_ACCOUNT);
1675 rc = smbldap_add(ldap_state->smbldap_state,
1676 dn, mods);
1677 break;
1678 case LDAP_MOD_REPLACE:
1679 rc = smbldap_modify(ldap_state->smbldap_state,
1680 dn ,mods);
1681 break;
1682 default:
1683 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1684 ldap_op));
1685 return NT_STATUS_INVALID_PARAMETER;
1688 if (rc!=LDAP_SUCCESS) {
1689 return NT_STATUS_UNSUCCESSFUL;
1693 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1694 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1695 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1696 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1697 BerElement *ber;
1698 struct berval *bv;
1699 char *retoid = NULL;
1700 struct berval *retdata = NULL;
1701 char *utf8_password;
1702 char *utf8_dn;
1703 size_t converted_size;
1704 int ret;
1706 if (!ldap_state->is_nds_ldap) {
1708 if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct,
1709 LDAP_EXOP_MODIFY_PASSWD)) {
1710 DEBUG(2, ("ldap password change requested, but LDAP "
1711 "server does not support it -- ignoring\n"));
1712 return NT_STATUS_OK;
1716 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1717 pdb_get_plaintext_passwd(newpwd),
1718 &converted_size))
1720 return NT_STATUS_NO_MEMORY;
1723 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1724 TALLOC_FREE(utf8_password);
1725 return NT_STATUS_NO_MEMORY;
1728 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1729 DEBUG(0,("ber_alloc_t returns NULL\n"));
1730 TALLOC_FREE(utf8_password);
1731 TALLOC_FREE(utf8_dn);
1732 return NT_STATUS_UNSUCCESSFUL;
1735 if ((ber_printf (ber, "{") < 0) ||
1736 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1737 utf8_dn) < 0)) {
1738 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1739 "value <0\n"));
1740 ber_free(ber,1);
1741 TALLOC_FREE(utf8_dn);
1742 TALLOC_FREE(utf8_password);
1743 return NT_STATUS_UNSUCCESSFUL;
1746 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1747 ret = ber_printf(ber, "ts}",
1748 LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1749 utf8_password);
1750 } else {
1751 ret = ber_printf(ber, "}");
1754 if (ret < 0) {
1755 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1756 "value <0\n"));
1757 ber_free(ber,1);
1758 TALLOC_FREE(utf8_dn);
1759 TALLOC_FREE(utf8_password);
1760 return NT_STATUS_UNSUCCESSFUL;
1763 if ((rc = ber_flatten (ber, &bv))<0) {
1764 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1765 ber_free(ber,1);
1766 TALLOC_FREE(utf8_dn);
1767 TALLOC_FREE(utf8_password);
1768 return NT_STATUS_UNSUCCESSFUL;
1771 TALLOC_FREE(utf8_dn);
1772 TALLOC_FREE(utf8_password);
1773 ber_free(ber, 1);
1775 if (!ldap_state->is_nds_ldap) {
1776 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1777 LDAP_EXOP_MODIFY_PASSWD,
1778 bv, NULL, NULL, &retoid,
1779 &retdata);
1780 } else {
1781 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1782 pdb_get_plaintext_passwd(newpwd));
1784 if (rc != LDAP_SUCCESS) {
1785 char *ld_error = NULL;
1787 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1788 DEBUG(3, ("Could not set userPassword "
1789 "attribute due to an objectClass "
1790 "violation -- ignoring\n"));
1791 ber_bvfree(bv);
1792 return NT_STATUS_OK;
1795 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1796 &ld_error);
1797 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1798 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1799 SAFE_FREE(ld_error);
1800 ber_bvfree(bv);
1801 #if defined(LDAP_CONSTRAINT_VIOLATION)
1802 if (rc == LDAP_CONSTRAINT_VIOLATION)
1803 return NT_STATUS_PASSWORD_RESTRICTION;
1804 #endif
1805 return NT_STATUS_UNSUCCESSFUL;
1806 } else {
1807 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1808 #ifdef DEBUG_PASSWORD
1809 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1810 #endif
1811 if (retdata)
1812 ber_bvfree(retdata);
1813 if (retoid)
1814 ldap_memfree(retoid);
1816 ber_bvfree(bv);
1818 return NT_STATUS_OK;
1821 /**********************************************************************
1822 Delete entry from LDAP for username.
1823 *********************************************************************/
1825 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1826 struct samu * sam_acct)
1828 struct ldapsam_privates *priv =
1829 (struct ldapsam_privates *)my_methods->private_data;
1830 const char *sname;
1831 int rc;
1832 LDAPMessage *msg, *entry;
1833 NTSTATUS result = NT_STATUS_NO_MEMORY;
1834 const char **attr_list;
1835 TALLOC_CTX *mem_ctx;
1837 if (!sam_acct) {
1838 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1839 return NT_STATUS_INVALID_PARAMETER;
1842 sname = pdb_get_username(sam_acct);
1844 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1845 "LDAP.\n", sname));
1847 mem_ctx = talloc_new(NULL);
1848 if (mem_ctx == NULL) {
1849 DEBUG(0, ("talloc_new failed\n"));
1850 goto done;
1853 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1854 if (attr_list == NULL) {
1855 goto done;
1858 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1860 if ((rc != LDAP_SUCCESS) ||
1861 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1862 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1863 DEBUG(5, ("Could not find user %s\n", sname));
1864 result = NT_STATUS_NO_SUCH_USER;
1865 goto done;
1868 rc = ldapsam_delete_entry(
1869 priv, mem_ctx, entry,
1870 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1871 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1872 attr_list);
1874 result = (rc == LDAP_SUCCESS) ?
1875 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1877 done:
1878 TALLOC_FREE(mem_ctx);
1879 return result;
1882 /**********************************************************************
1883 Helper function to determine for update_sam_account whether
1884 we need LDAP modification.
1885 *********************************************************************/
1887 static bool element_is_changed(const struct samu *sampass,
1888 enum pdb_elements element)
1890 return IS_SAM_CHANGED(sampass, element);
1893 /**********************************************************************
1894 Update struct samu.
1895 *********************************************************************/
1897 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1899 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1900 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1901 int rc = 0;
1902 char *dn;
1903 LDAPMessage *result = NULL;
1904 LDAPMessage *entry = NULL;
1905 LDAPMod **mods = NULL;
1906 const char **attr_list;
1908 result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1909 if (!result) {
1910 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1911 if (pdb_get_username(newpwd) == NULL) {
1912 return NT_STATUS_INVALID_PARAMETER;
1914 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1915 TALLOC_FREE( attr_list );
1916 if (rc != LDAP_SUCCESS) {
1917 return NT_STATUS_UNSUCCESSFUL;
1919 pdb_set_backend_private_data(newpwd, result, NULL,
1920 my_methods, PDB_CHANGED);
1921 talloc_autofree_ldapmsg(newpwd, result);
1924 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1925 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1926 return NT_STATUS_UNSUCCESSFUL;
1929 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1930 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1931 if (!dn) {
1932 return NT_STATUS_UNSUCCESSFUL;
1935 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1937 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1938 element_is_changed)) {
1939 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1940 TALLOC_FREE(dn);
1941 if (mods != NULL)
1942 ldap_mods_free(mods,True);
1943 return NT_STATUS_UNSUCCESSFUL;
1946 if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1947 && (mods == NULL)) {
1948 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1949 pdb_get_username(newpwd)));
1950 TALLOC_FREE(dn);
1951 return NT_STATUS_OK;
1954 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1956 if (mods != NULL) {
1957 ldap_mods_free(mods,True);
1960 TALLOC_FREE(dn);
1963 * We need to set the backend private data to NULL here. For example
1964 * setuserinfo level 25 does a pdb_update_sam_account twice on the
1965 * same one, and with the explicit delete / add logic for attribute
1966 * values the second time we would use the wrong "old" value which
1967 * does not exist in LDAP anymore. Thus the LDAP server would refuse
1968 * the update.
1969 * The existing LDAPMessage is still being auto-freed by the
1970 * destructor.
1972 pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1973 PDB_CHANGED);
1975 if (!NT_STATUS_IS_OK(ret)) {
1976 return ret;
1979 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1980 pdb_get_username(newpwd)));
1981 return NT_STATUS_OK;
1984 /***************************************************************************
1985 Renames a struct samu
1986 - The "rename user script" has full responsibility for changing everything
1987 ***************************************************************************/
1989 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1990 TALLOC_CTX *tmp_ctx,
1991 uint32 group_rid,
1992 uint32 member_rid);
1994 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1995 TALLOC_CTX *mem_ctx,
1996 struct samu *user,
1997 DOM_SID **pp_sids,
1998 gid_t **pp_gids,
1999 size_t *p_num_groups);
2001 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
2002 struct samu *old_acct,
2003 const char *newname)
2005 const char *oldname;
2006 int rc;
2007 char *rename_script = NULL;
2008 fstring oldname_lower, newname_lower;
2010 if (!old_acct) {
2011 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
2012 return NT_STATUS_INVALID_PARAMETER;
2014 if (!newname) {
2015 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
2016 return NT_STATUS_INVALID_PARAMETER;
2019 oldname = pdb_get_username(old_acct);
2021 /* rename the posix user */
2022 rename_script = SMB_STRDUP(lp_renameuser_script());
2023 if (rename_script == NULL) {
2024 return NT_STATUS_NO_MEMORY;
2027 if (!(*rename_script)) {
2028 SAFE_FREE(rename_script);
2029 return NT_STATUS_ACCESS_DENIED;
2032 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2033 oldname, newname));
2035 /* We have to allow the account name to end with a '$'.
2036 Also, follow the semantics in _samr_create_user() and lower case the
2037 posix name but preserve the case in passdb */
2039 fstrcpy( oldname_lower, oldname );
2040 strlower_m( oldname_lower );
2041 fstrcpy( newname_lower, newname );
2042 strlower_m( newname_lower );
2043 rename_script = realloc_string_sub2(rename_script,
2044 "%unew",
2045 newname_lower,
2046 true,
2047 true);
2048 if (!rename_script) {
2049 return NT_STATUS_NO_MEMORY;
2051 rename_script = realloc_string_sub2(rename_script,
2052 "%uold",
2053 oldname_lower,
2054 true,
2055 true);
2056 rc = smbrun(rename_script, NULL);
2058 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2059 rename_script, rc));
2061 SAFE_FREE(rename_script);
2063 if (rc == 0) {
2064 smb_nscd_flush_user_cache();
2067 if (rc)
2068 return NT_STATUS_UNSUCCESSFUL;
2070 return NT_STATUS_OK;
2073 /**********************************************************************
2074 Helper function to determine for update_sam_account whether
2075 we need LDAP modification.
2076 *********************************************************************/
2078 static bool element_is_set_or_changed(const struct samu *sampass,
2079 enum pdb_elements element)
2081 return (IS_SAM_SET(sampass, element) ||
2082 IS_SAM_CHANGED(sampass, element));
2085 /**********************************************************************
2086 Add struct samu to LDAP.
2087 *********************************************************************/
2089 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2091 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2092 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2093 int rc;
2094 LDAPMessage *result = NULL;
2095 LDAPMessage *entry = NULL;
2096 LDAPMod **mods = NULL;
2097 int ldap_op = LDAP_MOD_REPLACE;
2098 uint32 num_result;
2099 const char **attr_list;
2100 char *escape_user = NULL;
2101 const char *username = pdb_get_username(newpwd);
2102 const DOM_SID *sid = pdb_get_user_sid(newpwd);
2103 char *filter = NULL;
2104 char *dn = NULL;
2105 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2106 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2108 if (!ctx) {
2109 return NT_STATUS_NO_MEMORY;
2112 if (!username || !*username) {
2113 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2114 status = NT_STATUS_INVALID_PARAMETER;
2115 goto fn_exit;
2118 /* free this list after the second search or in case we exit on failure */
2119 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2121 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2123 if (rc != LDAP_SUCCESS) {
2124 goto fn_exit;
2127 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2128 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2129 username));
2130 goto fn_exit;
2132 ldap_msgfree(result);
2133 result = NULL;
2135 if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
2136 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2137 sid, &result);
2138 if (rc == LDAP_SUCCESS) {
2139 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2140 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2141 "already in the base, with samba "
2142 "attributes\n", sid_string_dbg(sid)));
2143 goto fn_exit;
2145 ldap_msgfree(result);
2146 result = NULL;
2150 /* does the entry already exist but without a samba attributes?
2151 we need to return the samba attributes here */
2153 escape_user = escape_ldap_string(talloc_tos(), username);
2154 filter = talloc_strdup(attr_list, "(uid=%u)");
2155 if (!filter) {
2156 status = NT_STATUS_NO_MEMORY;
2157 goto fn_exit;
2159 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2160 TALLOC_FREE(escape_user);
2161 if (!filter) {
2162 status = NT_STATUS_NO_MEMORY;
2163 goto fn_exit;
2166 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2167 filter, attr_list, &result);
2168 if ( rc != LDAP_SUCCESS ) {
2169 goto fn_exit;
2172 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2174 if (num_result > 1) {
2175 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2176 goto fn_exit;
2179 /* Check if we need to update an existing entry */
2180 if (num_result == 1) {
2181 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2182 ldap_op = LDAP_MOD_REPLACE;
2183 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2184 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2185 if (!dn) {
2186 status = NT_STATUS_NO_MEMORY;
2187 goto fn_exit;
2190 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2192 /* There might be a SID for this account already - say an idmap entry */
2194 filter = talloc_asprintf(ctx,
2195 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2196 get_userattr_key2string(ldap_state->schema_ver,
2197 LDAP_ATTR_USER_SID),
2198 sid_string_talloc(ctx, sid),
2199 LDAP_OBJ_IDMAP_ENTRY,
2200 LDAP_OBJ_SID_ENTRY);
2201 if (!filter) {
2202 status = NT_STATUS_NO_MEMORY;
2203 goto fn_exit;
2206 /* free old result before doing a new search */
2207 if (result != NULL) {
2208 ldap_msgfree(result);
2209 result = NULL;
2211 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2212 filter, attr_list, &result);
2214 if ( rc != LDAP_SUCCESS ) {
2215 goto fn_exit;
2218 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2220 if (num_result > 1) {
2221 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2222 goto fn_exit;
2225 /* Check if we need to update an existing entry */
2226 if (num_result == 1) {
2228 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2229 ldap_op = LDAP_MOD_REPLACE;
2230 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2231 dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2232 if (!dn) {
2233 status = NT_STATUS_NO_MEMORY;
2234 goto fn_exit;
2239 if (num_result == 0) {
2240 char *escape_username;
2241 /* Check if we need to add an entry */
2242 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2243 ldap_op = LDAP_MOD_ADD;
2245 escape_username = escape_rdn_val_string_alloc(username);
2246 if (!escape_username) {
2247 status = NT_STATUS_NO_MEMORY;
2248 goto fn_exit;
2251 if (username[strlen(username)-1] == '$') {
2252 dn = talloc_asprintf(ctx,
2253 "uid=%s,%s",
2254 escape_username,
2255 lp_ldap_machine_suffix());
2256 } else {
2257 dn = talloc_asprintf(ctx,
2258 "uid=%s,%s",
2259 escape_username,
2260 lp_ldap_user_suffix());
2263 SAFE_FREE(escape_username);
2264 if (!dn) {
2265 status = NT_STATUS_NO_MEMORY;
2266 goto fn_exit;
2270 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2271 element_is_set_or_changed)) {
2272 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2273 if (mods != NULL) {
2274 ldap_mods_free(mods, true);
2276 goto fn_exit;
2279 if (mods == NULL) {
2280 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2281 goto fn_exit;
2283 switch ( ldap_state->schema_ver ) {
2284 case SCHEMAVER_SAMBAACCOUNT:
2285 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2286 break;
2287 case SCHEMAVER_SAMBASAMACCOUNT:
2288 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2289 break;
2290 default:
2291 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2292 break;
2295 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2296 if (!NT_STATUS_IS_OK(ret)) {
2297 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2298 pdb_get_username(newpwd),dn));
2299 ldap_mods_free(mods, true);
2300 goto fn_exit;
2303 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2304 ldap_mods_free(mods, true);
2306 status = NT_STATUS_OK;
2308 fn_exit:
2310 TALLOC_FREE(ctx);
2311 if (result) {
2312 ldap_msgfree(result);
2314 return status;
2317 /**********************************************************************
2318 *********************************************************************/
2320 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2321 const char *filter,
2322 LDAPMessage ** result)
2324 int scope = LDAP_SCOPE_SUBTREE;
2325 int rc;
2326 const char **attr_list;
2328 attr_list = get_attr_list(NULL, groupmap_attr_list);
2329 rc = smbldap_search(ldap_state->smbldap_state,
2330 lp_ldap_suffix (), scope,
2331 filter, attr_list, 0, result);
2332 TALLOC_FREE(attr_list);
2334 return rc;
2337 /**********************************************************************
2338 *********************************************************************/
2340 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2341 GROUP_MAP *map, LDAPMessage *entry)
2343 char *temp = NULL;
2344 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2346 if (ldap_state == NULL || map == NULL || entry == NULL ||
2347 ldap_state->smbldap_state->ldap_struct == NULL) {
2348 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2349 TALLOC_FREE(ctx);
2350 return false;
2353 temp = smbldap_talloc_single_attribute(
2354 ldap_state->smbldap_state->ldap_struct,
2355 entry,
2356 get_attr_key2string(groupmap_attr_list,
2357 LDAP_ATTR_GIDNUMBER),
2358 ctx);
2359 if (!temp) {
2360 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2361 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2362 TALLOC_FREE(ctx);
2363 return false;
2365 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2367 map->gid = (gid_t)atol(temp);
2369 TALLOC_FREE(temp);
2370 temp = smbldap_talloc_single_attribute(
2371 ldap_state->smbldap_state->ldap_struct,
2372 entry,
2373 get_attr_key2string(groupmap_attr_list,
2374 LDAP_ATTR_GROUP_SID),
2375 ctx);
2376 if (!temp) {
2377 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2378 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2379 TALLOC_FREE(ctx);
2380 return false;
2383 if (!string_to_sid(&map->sid, temp)) {
2384 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2385 TALLOC_FREE(ctx);
2386 return false;
2389 TALLOC_FREE(temp);
2390 temp = smbldap_talloc_single_attribute(
2391 ldap_state->smbldap_state->ldap_struct,
2392 entry,
2393 get_attr_key2string(groupmap_attr_list,
2394 LDAP_ATTR_GROUP_TYPE),
2395 ctx);
2396 if (!temp) {
2397 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2398 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2399 TALLOC_FREE(ctx);
2400 return false;
2402 map->sid_name_use = (enum lsa_SidType)atol(temp);
2404 if ((map->sid_name_use < SID_NAME_USER) ||
2405 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2406 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2407 TALLOC_FREE(ctx);
2408 return false;
2411 TALLOC_FREE(temp);
2412 temp = smbldap_talloc_single_attribute(
2413 ldap_state->smbldap_state->ldap_struct,
2414 entry,
2415 get_attr_key2string(groupmap_attr_list,
2416 LDAP_ATTR_DISPLAY_NAME),
2417 ctx);
2418 if (!temp) {
2419 temp = smbldap_talloc_single_attribute(
2420 ldap_state->smbldap_state->ldap_struct,
2421 entry,
2422 get_attr_key2string(groupmap_attr_list,
2423 LDAP_ATTR_CN),
2424 ctx);
2425 if (!temp) {
2426 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2427 for gidNumber(%lu)\n",(unsigned long)map->gid));
2428 TALLOC_FREE(ctx);
2429 return false;
2432 fstrcpy(map->nt_name, temp);
2434 TALLOC_FREE(temp);
2435 temp = smbldap_talloc_single_attribute(
2436 ldap_state->smbldap_state->ldap_struct,
2437 entry,
2438 get_attr_key2string(groupmap_attr_list,
2439 LDAP_ATTR_DESC),
2440 ctx);
2441 if (!temp) {
2442 temp = talloc_strdup(ctx, "");
2443 if (!temp) {
2444 TALLOC_FREE(ctx);
2445 return false;
2448 fstrcpy(map->comment, temp);
2450 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2451 store_gid_sid_cache(&map->sid, map->gid);
2454 TALLOC_FREE(ctx);
2455 return true;
2458 /**********************************************************************
2459 *********************************************************************/
2461 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2462 const char *filter,
2463 GROUP_MAP *map)
2465 struct ldapsam_privates *ldap_state =
2466 (struct ldapsam_privates *)methods->private_data;
2467 LDAPMessage *result = NULL;
2468 LDAPMessage *entry = NULL;
2469 int count;
2471 if (ldapsam_search_one_group(ldap_state, filter, &result)
2472 != LDAP_SUCCESS) {
2473 return NT_STATUS_NO_SUCH_GROUP;
2476 count = ldap_count_entries(priv2ld(ldap_state), result);
2478 if (count < 1) {
2479 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2480 "%s\n", filter));
2481 ldap_msgfree(result);
2482 return NT_STATUS_NO_SUCH_GROUP;
2485 if (count > 1) {
2486 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2487 "count=%d\n", filter, count));
2488 ldap_msgfree(result);
2489 return NT_STATUS_NO_SUCH_GROUP;
2492 entry = ldap_first_entry(priv2ld(ldap_state), result);
2494 if (!entry) {
2495 ldap_msgfree(result);
2496 return NT_STATUS_UNSUCCESSFUL;
2499 if (!init_group_from_ldap(ldap_state, map, entry)) {
2500 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2501 "group filter %s\n", filter));
2502 ldap_msgfree(result);
2503 return NT_STATUS_NO_SUCH_GROUP;
2506 ldap_msgfree(result);
2507 return NT_STATUS_OK;
2510 /**********************************************************************
2511 *********************************************************************/
2513 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2514 DOM_SID sid)
2516 char *filter = NULL;
2517 NTSTATUS status;
2518 fstring tmp;
2520 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2521 LDAP_OBJ_GROUPMAP,
2522 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2523 sid_to_fstring(tmp, &sid)) < 0) {
2524 return NT_STATUS_NO_MEMORY;
2527 status = ldapsam_getgroup(methods, filter, map);
2528 SAFE_FREE(filter);
2529 return status;
2532 /**********************************************************************
2533 *********************************************************************/
2535 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2536 gid_t gid)
2538 char *filter = NULL;
2539 NTSTATUS status;
2541 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2542 LDAP_OBJ_GROUPMAP,
2543 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2544 (unsigned long)gid) < 0) {
2545 return NT_STATUS_NO_MEMORY;
2548 status = ldapsam_getgroup(methods, filter, map);
2549 SAFE_FREE(filter);
2550 return status;
2553 /**********************************************************************
2554 *********************************************************************/
2556 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2557 const char *name)
2559 char *filter = NULL;
2560 char *escape_name = escape_ldap_string(talloc_tos(), name);
2561 NTSTATUS status;
2563 if (!escape_name) {
2564 return NT_STATUS_NO_MEMORY;
2567 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2568 LDAP_OBJ_GROUPMAP,
2569 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2570 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2571 escape_name) < 0) {
2572 TALLOC_FREE(escape_name);
2573 return NT_STATUS_NO_MEMORY;
2576 TALLOC_FREE(escape_name);
2577 status = ldapsam_getgroup(methods, filter, map);
2578 SAFE_FREE(filter);
2579 return status;
2582 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2583 LDAPMessage *entry,
2584 const DOM_SID *domain_sid,
2585 uint32 *rid)
2587 fstring str;
2588 DOM_SID sid;
2590 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2591 str, sizeof(str)-1)) {
2592 DEBUG(10, ("Could not find sambaSID attribute\n"));
2593 return False;
2596 if (!string_to_sid(&sid, str)) {
2597 DEBUG(10, ("Could not convert string %s to sid\n", str));
2598 return False;
2601 if (sid_compare_domain(&sid, domain_sid) != 0) {
2602 DEBUG(10, ("SID %s is not in expected domain %s\n",
2603 str, sid_string_dbg(domain_sid)));
2604 return False;
2607 if (!sid_peek_rid(&sid, rid)) {
2608 DEBUG(10, ("Could not peek into RID\n"));
2609 return False;
2612 return True;
2615 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2616 TALLOC_CTX *mem_ctx,
2617 const DOM_SID *group,
2618 uint32 **pp_member_rids,
2619 size_t *p_num_members)
2621 struct ldapsam_privates *ldap_state =
2622 (struct ldapsam_privates *)methods->private_data;
2623 struct smbldap_state *conn = ldap_state->smbldap_state;
2624 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2625 const char *sid_attrs[] = { "sambaSID", NULL };
2626 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2627 LDAPMessage *result = NULL;
2628 LDAPMessage *entry;
2629 char *filter;
2630 char **values = NULL;
2631 char **memberuid;
2632 char *gidstr;
2633 int rc, count;
2635 *pp_member_rids = NULL;
2636 *p_num_members = 0;
2638 filter = talloc_asprintf(mem_ctx,
2639 "(&(objectClass=%s)"
2640 "(objectClass=%s)"
2641 "(sambaSID=%s))",
2642 LDAP_OBJ_POSIXGROUP,
2643 LDAP_OBJ_GROUPMAP,
2644 sid_string_talloc(mem_ctx, group));
2645 if (filter == NULL) {
2646 ret = NT_STATUS_NO_MEMORY;
2647 goto done;
2650 rc = smbldap_search(conn, lp_ldap_suffix(),
2651 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2652 &result);
2654 if (rc != LDAP_SUCCESS)
2655 goto done;
2657 talloc_autofree_ldapmsg(mem_ctx, result);
2659 count = ldap_count_entries(conn->ldap_struct, result);
2661 if (count > 1) {
2662 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2663 sid_string_dbg(group)));
2664 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2665 goto done;
2668 if (count == 0) {
2669 ret = NT_STATUS_NO_SUCH_GROUP;
2670 goto done;
2673 entry = ldap_first_entry(conn->ldap_struct, result);
2674 if (entry == NULL)
2675 goto done;
2677 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2678 if (!gidstr) {
2679 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2680 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2681 goto done;
2684 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2686 if ((values != NULL) && (values[0] != NULL)) {
2688 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2689 if (filter == NULL) {
2690 ret = NT_STATUS_NO_MEMORY;
2691 goto done;
2694 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2695 char *escape_memberuid;
2697 escape_memberuid = escape_ldap_string(talloc_tos(),
2698 *memberuid);
2699 if (escape_memberuid == NULL) {
2700 ret = NT_STATUS_NO_MEMORY;
2701 goto done;
2704 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2705 TALLOC_FREE(escape_memberuid);
2706 if (filter == NULL) {
2707 ret = NT_STATUS_NO_MEMORY;
2708 goto done;
2712 filter = talloc_asprintf_append_buffer(filter, "))");
2713 if (filter == NULL) {
2714 ret = NT_STATUS_NO_MEMORY;
2715 goto done;
2718 rc = smbldap_search(conn, lp_ldap_suffix(),
2719 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2720 &result);
2722 if (rc != LDAP_SUCCESS)
2723 goto done;
2725 count = ldap_count_entries(conn->ldap_struct, result);
2726 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2728 talloc_autofree_ldapmsg(mem_ctx, result);
2730 for (entry = ldap_first_entry(conn->ldap_struct, result);
2731 entry != NULL;
2732 entry = ldap_next_entry(conn->ldap_struct, entry))
2734 char *sidstr;
2735 DOM_SID sid;
2736 uint32 rid;
2738 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2739 entry, "sambaSID",
2740 mem_ctx);
2741 if (!sidstr) {
2742 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2743 "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2744 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2745 goto done;
2748 if (!string_to_sid(&sid, sidstr))
2749 goto done;
2751 if (!sid_check_is_in_our_domain(&sid)) {
2752 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2753 "in our domain\n"));
2754 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2755 goto done;
2758 sid_peek_rid(&sid, &rid);
2760 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2761 p_num_members)) {
2762 ret = NT_STATUS_NO_MEMORY;
2763 goto done;
2768 filter = talloc_asprintf(mem_ctx,
2769 "(&(objectClass=%s)"
2770 "(gidNumber=%s))",
2771 LDAP_OBJ_SAMBASAMACCOUNT,
2772 gidstr);
2774 rc = smbldap_search(conn, lp_ldap_suffix(),
2775 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2776 &result);
2778 if (rc != LDAP_SUCCESS)
2779 goto done;
2781 talloc_autofree_ldapmsg(mem_ctx, result);
2783 for (entry = ldap_first_entry(conn->ldap_struct, result);
2784 entry != NULL;
2785 entry = ldap_next_entry(conn->ldap_struct, entry))
2787 uint32 rid;
2789 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2790 entry,
2791 get_global_sam_sid(),
2792 &rid)) {
2793 DEBUG(0, ("Severe DB error, %s can't miss the samba SID" "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2794 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2795 goto done;
2798 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2799 p_num_members)) {
2800 ret = NT_STATUS_NO_MEMORY;
2801 goto done;
2805 ret = NT_STATUS_OK;
2807 done:
2809 if (values)
2810 ldap_value_free(values);
2812 return ret;
2815 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2816 TALLOC_CTX *mem_ctx,
2817 struct samu *user,
2818 DOM_SID **pp_sids,
2819 gid_t **pp_gids,
2820 size_t *p_num_groups)
2822 struct ldapsam_privates *ldap_state =
2823 (struct ldapsam_privates *)methods->private_data;
2824 struct smbldap_state *conn = ldap_state->smbldap_state;
2825 char *filter;
2826 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2827 char *escape_name;
2828 int rc, count;
2829 LDAPMessage *result = NULL;
2830 LDAPMessage *entry;
2831 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2832 size_t num_sids, num_gids;
2833 char *gidstr;
2834 gid_t primary_gid = -1;
2836 *pp_sids = NULL;
2837 num_sids = 0;
2839 if (pdb_get_username(user) == NULL) {
2840 return NT_STATUS_INVALID_PARAMETER;
2843 escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2844 if (escape_name == NULL)
2845 return NT_STATUS_NO_MEMORY;
2847 /* retrieve the users primary gid */
2848 filter = talloc_asprintf(mem_ctx,
2849 "(&(objectClass=%s)(uid=%s))",
2850 LDAP_OBJ_SAMBASAMACCOUNT,
2851 escape_name);
2852 if (filter == NULL) {
2853 ret = NT_STATUS_NO_MEMORY;
2854 goto done;
2857 rc = smbldap_search(conn, lp_ldap_suffix(),
2858 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2860 if (rc != LDAP_SUCCESS)
2861 goto done;
2863 talloc_autofree_ldapmsg(mem_ctx, result);
2865 count = ldap_count_entries(priv2ld(ldap_state), result);
2867 switch (count) {
2868 case 0:
2869 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2870 ret = NT_STATUS_NO_SUCH_USER;
2871 goto done;
2872 case 1:
2873 entry = ldap_first_entry(priv2ld(ldap_state), result);
2875 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2876 if (!gidstr) {
2877 DEBUG (1, ("Unable to find the member's gid!\n"));
2878 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2879 goto done;
2881 primary_gid = strtoul(gidstr, NULL, 10);
2882 break;
2883 default:
2884 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2885 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2886 goto done;
2889 filter = talloc_asprintf(mem_ctx,
2890 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2891 LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2892 if (filter == NULL) {
2893 ret = NT_STATUS_NO_MEMORY;
2894 goto done;
2897 rc = smbldap_search(conn, lp_ldap_suffix(),
2898 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2900 if (rc != LDAP_SUCCESS)
2901 goto done;
2903 talloc_autofree_ldapmsg(mem_ctx, result);
2905 num_gids = 0;
2906 *pp_gids = NULL;
2908 num_sids = 0;
2909 *pp_sids = NULL;
2911 /* We need to add the primary group as the first gid/sid */
2913 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2914 ret = NT_STATUS_NO_MEMORY;
2915 goto done;
2918 /* This sid will be replaced later */
2920 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2921 &num_sids);
2922 if (!NT_STATUS_IS_OK(ret)) {
2923 goto done;
2926 for (entry = ldap_first_entry(conn->ldap_struct, result);
2927 entry != NULL;
2928 entry = ldap_next_entry(conn->ldap_struct, entry))
2930 fstring str;
2931 DOM_SID sid;
2932 gid_t gid;
2933 char *end;
2935 if (!smbldap_get_single_attribute(conn->ldap_struct,
2936 entry, "sambaSID",
2937 str, sizeof(str)-1))
2938 continue;
2940 if (!string_to_sid(&sid, str))
2941 goto done;
2943 if (!smbldap_get_single_attribute(conn->ldap_struct,
2944 entry, "gidNumber",
2945 str, sizeof(str)-1))
2946 continue;
2948 gid = strtoul(str, &end, 10);
2950 if (PTR_DIFF(end, str) != strlen(str))
2951 goto done;
2953 if (gid == primary_gid) {
2954 sid_copy(&(*pp_sids)[0], &sid);
2955 } else {
2956 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2957 &num_gids)) {
2958 ret = NT_STATUS_NO_MEMORY;
2959 goto done;
2961 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2962 &num_sids);
2963 if (!NT_STATUS_IS_OK(ret)) {
2964 goto done;
2969 if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2970 DEBUG(3, ("primary group of [%s] not found\n",
2971 pdb_get_username(user)));
2972 goto done;
2975 *p_num_groups = num_sids;
2977 ret = NT_STATUS_OK;
2979 done:
2981 TALLOC_FREE(escape_name);
2982 return ret;
2985 /**********************************************************************
2986 * Augment a posixGroup object with a sambaGroupMapping domgroup
2987 *********************************************************************/
2989 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2990 struct ldapsam_privates *ldap_state,
2991 GROUP_MAP *map)
2993 const char *filter, *dn;
2994 LDAPMessage *msg, *entry;
2995 LDAPMod **mods;
2996 int rc;
2998 filter = talloc_asprintf(mem_ctx,
2999 "(&(objectClass=%s)(gidNumber=%u))",
3000 LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
3001 if (filter == NULL) {
3002 return NT_STATUS_NO_MEMORY;
3005 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3006 get_attr_list(mem_ctx, groupmap_attr_list),
3007 &msg);
3008 talloc_autofree_ldapmsg(mem_ctx, msg);
3010 if ((rc != LDAP_SUCCESS) ||
3011 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3012 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3013 return NT_STATUS_NO_SUCH_GROUP;
3016 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3017 if (dn == NULL) {
3018 return NT_STATUS_NO_MEMORY;
3021 mods = NULL;
3022 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3023 LDAP_OBJ_GROUPMAP);
3024 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3025 sid_string_talloc(mem_ctx, &map->sid));
3026 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3027 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3028 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3029 map->nt_name);
3030 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3031 map->comment);
3032 talloc_autofree_ldapmod(mem_ctx, mods);
3034 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3035 if (rc != LDAP_SUCCESS) {
3036 return NT_STATUS_ACCESS_DENIED;
3039 return NT_STATUS_OK;
3042 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3043 GROUP_MAP *map)
3045 struct ldapsam_privates *ldap_state =
3046 (struct ldapsam_privates *)methods->private_data;
3047 LDAPMessage *msg = NULL;
3048 LDAPMod **mods = NULL;
3049 const char *attrs[] = { NULL };
3050 char *filter;
3052 char *dn;
3053 TALLOC_CTX *mem_ctx;
3054 NTSTATUS result;
3056 DOM_SID sid;
3058 int rc;
3060 mem_ctx = talloc_new(NULL);
3061 if (mem_ctx == NULL) {
3062 DEBUG(0, ("talloc_new failed\n"));
3063 return NT_STATUS_NO_MEMORY;
3066 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3067 sid_string_talloc(mem_ctx, &map->sid));
3068 if (filter == NULL) {
3069 result = NT_STATUS_NO_MEMORY;
3070 goto done;
3073 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3074 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3075 talloc_autofree_ldapmsg(mem_ctx, msg);
3077 if ((rc == LDAP_SUCCESS) &&
3078 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3080 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3081 "group mapping entry\n", sid_string_dbg(&map->sid)));
3082 result = NT_STATUS_GROUP_EXISTS;
3083 goto done;
3086 switch (map->sid_name_use) {
3088 case SID_NAME_DOM_GRP:
3089 /* To map a domain group we need to have a posix group
3090 to attach to. */
3091 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3092 goto done;
3093 break;
3095 case SID_NAME_ALIAS:
3096 if (!sid_check_is_in_our_domain(&map->sid)
3097 && !sid_check_is_in_builtin(&map->sid) )
3099 DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3100 sid_string_dbg(&map->sid)));
3101 result = NT_STATUS_INVALID_PARAMETER;
3102 goto done;
3104 break;
3106 default:
3107 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3108 sid_type_lookup(map->sid_name_use)));
3109 result = NT_STATUS_INVALID_PARAMETER;
3110 goto done;
3113 /* Domain groups have been mapped in a separate routine, we have to
3114 * create an alias now */
3116 if (map->gid == -1) {
3117 DEBUG(10, ("Refusing to map gid==-1\n"));
3118 result = NT_STATUS_INVALID_PARAMETER;
3119 goto done;
3122 if (pdb_gid_to_sid(map->gid, &sid)) {
3123 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3124 "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3125 result = NT_STATUS_GROUP_EXISTS;
3126 goto done;
3129 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3130 * the best we can get out of LDAP. */
3132 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3133 sid_string_talloc(mem_ctx, &map->sid),
3134 lp_ldap_group_suffix());
3135 if (dn == NULL) {
3136 result = NT_STATUS_NO_MEMORY;
3137 goto done;
3140 mods = NULL;
3142 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3143 LDAP_OBJ_SID_ENTRY);
3144 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3145 LDAP_OBJ_GROUPMAP);
3146 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3147 sid_string_talloc(mem_ctx, &map->sid));
3148 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3149 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3150 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3151 map->nt_name);
3152 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3153 map->comment);
3154 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3155 talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3156 talloc_autofree_ldapmod(mem_ctx, mods);
3158 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3160 result = (rc == LDAP_SUCCESS) ?
3161 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3163 done:
3164 TALLOC_FREE(mem_ctx);
3165 return result;
3168 /**********************************************************************
3169 * Update a group mapping entry. We're quite strict about what can be changed:
3170 * Only the description and displayname may be changed. It simply does not
3171 * make any sense to change the SID, gid or the type in a mapping.
3172 *********************************************************************/
3174 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3175 GROUP_MAP *map)
3177 struct ldapsam_privates *ldap_state =
3178 (struct ldapsam_privates *)methods->private_data;
3179 int rc;
3180 const char *filter, *dn;
3181 LDAPMessage *msg = NULL;
3182 LDAPMessage *entry = NULL;
3183 LDAPMod **mods = NULL;
3184 TALLOC_CTX *mem_ctx;
3185 NTSTATUS result;
3187 mem_ctx = talloc_new(NULL);
3188 if (mem_ctx == NULL) {
3189 DEBUG(0, ("talloc_new failed\n"));
3190 return NT_STATUS_NO_MEMORY;
3193 /* Make 100% sure that sid, gid and type are not changed by looking up
3194 * exactly the values we're given in LDAP. */
3196 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3197 "(sambaSid=%s)(gidNumber=%u)"
3198 "(sambaGroupType=%d))",
3199 LDAP_OBJ_GROUPMAP,
3200 sid_string_talloc(mem_ctx, &map->sid),
3201 (unsigned int)map->gid, map->sid_name_use);
3202 if (filter == NULL) {
3203 result = NT_STATUS_NO_MEMORY;
3204 goto done;
3207 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3208 get_attr_list(mem_ctx, groupmap_attr_list),
3209 &msg);
3210 talloc_autofree_ldapmsg(mem_ctx, msg);
3212 if ((rc != LDAP_SUCCESS) ||
3213 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3214 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3215 result = NT_STATUS_NO_SUCH_GROUP;
3216 goto done;
3219 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3221 if (dn == NULL) {
3222 result = NT_STATUS_NO_MEMORY;
3223 goto done;
3226 mods = NULL;
3227 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3228 map->nt_name);
3229 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3230 map->comment);
3231 talloc_autofree_ldapmod(mem_ctx, mods);
3233 if (mods == NULL) {
3234 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3235 "nothing to do\n"));
3236 result = NT_STATUS_OK;
3237 goto done;
3240 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3242 if (rc != LDAP_SUCCESS) {
3243 result = NT_STATUS_ACCESS_DENIED;
3244 goto done;
3247 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3248 "group %lu in LDAP\n", (unsigned long)map->gid));
3250 result = NT_STATUS_OK;
3252 done:
3253 TALLOC_FREE(mem_ctx);
3254 return result;
3257 /**********************************************************************
3258 *********************************************************************/
3260 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3261 DOM_SID sid)
3263 struct ldapsam_privates *priv =
3264 (struct ldapsam_privates *)methods->private_data;
3265 LDAPMessage *msg, *entry;
3266 int rc;
3267 NTSTATUS result;
3268 TALLOC_CTX *mem_ctx;
3269 char *filter;
3271 mem_ctx = talloc_new(NULL);
3272 if (mem_ctx == NULL) {
3273 DEBUG(0, ("talloc_new failed\n"));
3274 return NT_STATUS_NO_MEMORY;
3277 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3278 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3279 sid_string_talloc(mem_ctx, &sid));
3280 if (filter == NULL) {
3281 result = NT_STATUS_NO_MEMORY;
3282 goto done;
3284 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3285 get_attr_list(mem_ctx, groupmap_attr_list),
3286 &msg);
3287 talloc_autofree_ldapmsg(mem_ctx, msg);
3289 if ((rc != LDAP_SUCCESS) ||
3290 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3291 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3292 result = NT_STATUS_NO_SUCH_GROUP;
3293 goto done;
3296 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3297 get_attr_list(mem_ctx,
3298 groupmap_attr_list_to_delete));
3300 if ((rc == LDAP_NAMING_VIOLATION) ||
3301 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3302 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3303 const char *attrs[] = { "sambaGroupType", "description",
3304 "displayName", "sambaSIDList",
3305 NULL };
3307 /* Second try. Don't delete the sambaSID attribute, this is
3308 for "old" entries that are tacked on a winbind
3309 sambaIdmapEntry. */
3311 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3312 LDAP_OBJ_GROUPMAP, attrs);
3315 if ((rc == LDAP_NAMING_VIOLATION) ||
3316 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3317 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3318 const char *attrs[] = { "sambaGroupType", "description",
3319 "displayName", "sambaSIDList",
3320 "gidNumber", NULL };
3322 /* Third try. This is a post-3.0.21 alias (containing only
3323 * sambaSidEntry and sambaGroupMapping classes), we also have
3324 * to delete the gidNumber attribute, only the sambaSidEntry
3325 * remains */
3327 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3328 LDAP_OBJ_GROUPMAP, attrs);
3331 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3333 done:
3334 TALLOC_FREE(mem_ctx);
3335 return result;
3338 /**********************************************************************
3339 *********************************************************************/
3341 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3342 bool update)
3344 struct ldapsam_privates *ldap_state =
3345 (struct ldapsam_privates *)my_methods->private_data;
3346 char *filter = NULL;
3347 int rc;
3348 const char **attr_list;
3350 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3351 if (!filter) {
3352 return NT_STATUS_NO_MEMORY;
3354 attr_list = get_attr_list( NULL, groupmap_attr_list );
3355 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3356 LDAP_SCOPE_SUBTREE, filter,
3357 attr_list, 0, &ldap_state->result);
3358 TALLOC_FREE(attr_list);
3360 if (rc != LDAP_SUCCESS) {
3361 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3362 ldap_err2string(rc)));
3363 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3364 lp_ldap_suffix(), filter));
3365 ldap_msgfree(ldap_state->result);
3366 ldap_state->result = NULL;
3367 TALLOC_FREE(filter);
3368 return NT_STATUS_UNSUCCESSFUL;
3371 TALLOC_FREE(filter);
3373 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3374 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3375 ldap_state->result)));
3377 ldap_state->entry =
3378 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3379 ldap_state->result);
3380 ldap_state->index = 0;
3382 return NT_STATUS_OK;
3385 /**********************************************************************
3386 *********************************************************************/
3388 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3390 ldapsam_endsampwent(my_methods);
3393 /**********************************************************************
3394 *********************************************************************/
3396 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3397 GROUP_MAP *map)
3399 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3400 struct ldapsam_privates *ldap_state =
3401 (struct ldapsam_privates *)my_methods->private_data;
3402 bool bret = False;
3404 while (!bret) {
3405 if (!ldap_state->entry)
3406 return ret;
3408 ldap_state->index++;
3409 bret = init_group_from_ldap(ldap_state, map,
3410 ldap_state->entry);
3412 ldap_state->entry =
3413 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3414 ldap_state->entry);
3417 return NT_STATUS_OK;
3420 /**********************************************************************
3421 *********************************************************************/
3423 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3424 const DOM_SID *domsid, enum lsa_SidType sid_name_use,
3425 GROUP_MAP **pp_rmap,
3426 size_t *p_num_entries,
3427 bool unix_only)
3429 GROUP_MAP map;
3430 size_t entries = 0;
3432 *p_num_entries = 0;
3433 *pp_rmap = NULL;
3435 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3436 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3437 "passdb\n"));
3438 return NT_STATUS_ACCESS_DENIED;
3441 while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3442 if (sid_name_use != SID_NAME_UNKNOWN &&
3443 sid_name_use != map.sid_name_use) {
3444 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3445 "not of the requested type\n", map.nt_name));
3446 continue;
3448 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3449 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3450 "non mapped\n", map.nt_name));
3451 continue;
3454 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3455 if (!(*pp_rmap)) {
3456 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3457 "enlarge group map!\n"));
3458 return NT_STATUS_UNSUCCESSFUL;
3461 (*pp_rmap)[entries] = map;
3463 entries += 1;
3466 ldapsam_endsamgrent(methods);
3468 *p_num_entries = entries;
3470 return NT_STATUS_OK;
3473 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3474 const DOM_SID *alias,
3475 const DOM_SID *member,
3476 int modop)
3478 struct ldapsam_privates *ldap_state =
3479 (struct ldapsam_privates *)methods->private_data;
3480 char *dn = NULL;
3481 LDAPMessage *result = NULL;
3482 LDAPMessage *entry = NULL;
3483 int count;
3484 LDAPMod **mods = NULL;
3485 int rc;
3486 enum lsa_SidType type = SID_NAME_USE_NONE;
3487 fstring tmp;
3489 char *filter = NULL;
3491 if (sid_check_is_in_builtin(alias)) {
3492 type = SID_NAME_ALIAS;
3495 if (sid_check_is_in_our_domain(alias)) {
3496 type = SID_NAME_ALIAS;
3499 if (type == SID_NAME_USE_NONE) {
3500 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3501 sid_string_dbg(alias)));
3502 return NT_STATUS_NO_SUCH_ALIAS;
3505 if (asprintf(&filter,
3506 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3507 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3508 type) < 0) {
3509 return NT_STATUS_NO_MEMORY;
3512 if (ldapsam_search_one_group(ldap_state, filter,
3513 &result) != LDAP_SUCCESS) {
3514 SAFE_FREE(filter);
3515 return NT_STATUS_NO_SUCH_ALIAS;
3518 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3519 result);
3521 if (count < 1) {
3522 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3523 ldap_msgfree(result);
3524 SAFE_FREE(filter);
3525 return NT_STATUS_NO_SUCH_ALIAS;
3528 if (count > 1) {
3529 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3530 "filter %s: count=%d\n", filter, count));
3531 ldap_msgfree(result);
3532 SAFE_FREE(filter);
3533 return NT_STATUS_NO_SUCH_ALIAS;
3536 SAFE_FREE(filter);
3538 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3539 result);
3541 if (!entry) {
3542 ldap_msgfree(result);
3543 return NT_STATUS_UNSUCCESSFUL;
3546 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3547 if (!dn) {
3548 ldap_msgfree(result);
3549 return NT_STATUS_UNSUCCESSFUL;
3552 smbldap_set_mod(&mods, modop,
3553 get_attr_key2string(groupmap_attr_list,
3554 LDAP_ATTR_SID_LIST),
3555 sid_to_fstring(tmp, member));
3557 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3559 ldap_mods_free(mods, True);
3560 ldap_msgfree(result);
3561 TALLOC_FREE(dn);
3563 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3564 return NT_STATUS_MEMBER_IN_ALIAS;
3567 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3568 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3571 if (rc != LDAP_SUCCESS) {
3572 return NT_STATUS_UNSUCCESSFUL;
3575 return NT_STATUS_OK;
3578 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3579 const DOM_SID *alias,
3580 const DOM_SID *member)
3582 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3585 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3586 const DOM_SID *alias,
3587 const DOM_SID *member)
3589 return ldapsam_modify_aliasmem(methods, alias, member,
3590 LDAP_MOD_DELETE);
3593 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3594 const DOM_SID *alias,
3595 TALLOC_CTX *mem_ctx,
3596 DOM_SID **pp_members,
3597 size_t *p_num_members)
3599 struct ldapsam_privates *ldap_state =
3600 (struct ldapsam_privates *)methods->private_data;
3601 LDAPMessage *result = NULL;
3602 LDAPMessage *entry = NULL;
3603 int count;
3604 char **values = NULL;
3605 int i;
3606 char *filter = NULL;
3607 size_t num_members = 0;
3608 enum lsa_SidType type = SID_NAME_USE_NONE;
3609 fstring tmp;
3611 *pp_members = NULL;
3612 *p_num_members = 0;
3614 if (sid_check_is_in_builtin(alias)) {
3615 type = SID_NAME_ALIAS;
3618 if (sid_check_is_in_our_domain(alias)) {
3619 type = SID_NAME_ALIAS;
3622 if (type == SID_NAME_USE_NONE) {
3623 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3624 sid_string_dbg(alias)));
3625 return NT_STATUS_NO_SUCH_ALIAS;
3628 if (asprintf(&filter,
3629 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3630 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3631 type) < 0) {
3632 return NT_STATUS_NO_MEMORY;
3635 if (ldapsam_search_one_group(ldap_state, filter,
3636 &result) != LDAP_SUCCESS) {
3637 SAFE_FREE(filter);
3638 return NT_STATUS_NO_SUCH_ALIAS;
3641 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3642 result);
3644 if (count < 1) {
3645 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3646 ldap_msgfree(result);
3647 SAFE_FREE(filter);
3648 return NT_STATUS_NO_SUCH_ALIAS;
3651 if (count > 1) {
3652 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3653 "filter %s: count=%d\n", filter, count));
3654 ldap_msgfree(result);
3655 SAFE_FREE(filter);
3656 return NT_STATUS_NO_SUCH_ALIAS;
3659 SAFE_FREE(filter);
3661 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3662 result);
3664 if (!entry) {
3665 ldap_msgfree(result);
3666 return NT_STATUS_UNSUCCESSFUL;
3669 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3670 entry,
3671 get_attr_key2string(groupmap_attr_list,
3672 LDAP_ATTR_SID_LIST));
3674 if (values == NULL) {
3675 ldap_msgfree(result);
3676 return NT_STATUS_OK;
3679 count = ldap_count_values(values);
3681 for (i=0; i<count; i++) {
3682 DOM_SID member;
3683 NTSTATUS status;
3685 if (!string_to_sid(&member, values[i]))
3686 continue;
3688 status = add_sid_to_array(mem_ctx, &member, pp_members,
3689 &num_members);
3690 if (!NT_STATUS_IS_OK(status)) {
3691 ldap_value_free(values);
3692 ldap_msgfree(result);
3693 return status;
3697 *p_num_members = num_members;
3698 ldap_value_free(values);
3699 ldap_msgfree(result);
3701 return NT_STATUS_OK;
3704 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3705 TALLOC_CTX *mem_ctx,
3706 const DOM_SID *domain_sid,
3707 const DOM_SID *members,
3708 size_t num_members,
3709 uint32 **pp_alias_rids,
3710 size_t *p_num_alias_rids)
3712 struct ldapsam_privates *ldap_state =
3713 (struct ldapsam_privates *)methods->private_data;
3714 LDAP *ldap_struct;
3716 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3718 LDAPMessage *result = NULL;
3719 LDAPMessage *entry = NULL;
3720 int i;
3721 int rc;
3722 char *filter;
3723 enum lsa_SidType type = SID_NAME_USE_NONE;
3725 *pp_alias_rids = NULL;
3726 *p_num_alias_rids = 0;
3728 if (sid_check_is_builtin(domain_sid)) {
3729 type = SID_NAME_ALIAS;
3732 if (sid_check_is_domain(domain_sid)) {
3733 type = SID_NAME_ALIAS;
3736 if (type == SID_NAME_USE_NONE) {
3737 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3738 sid_string_dbg(domain_sid)));
3739 return NT_STATUS_UNSUCCESSFUL;
3742 if (num_members == 0) {
3743 return NT_STATUS_OK;
3746 filter = talloc_asprintf(mem_ctx,
3747 "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3748 LDAP_OBJ_GROUPMAP, type);
3750 for (i=0; i<num_members; i++)
3751 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3752 filter,
3753 sid_string_talloc(mem_ctx,
3754 &members[i]));
3756 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3758 if (filter == NULL) {
3759 return NT_STATUS_NO_MEMORY;
3762 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3763 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3765 if (rc != LDAP_SUCCESS)
3766 return NT_STATUS_UNSUCCESSFUL;
3768 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3770 for (entry = ldap_first_entry(ldap_struct, result);
3771 entry != NULL;
3772 entry = ldap_next_entry(ldap_struct, entry))
3774 fstring sid_str;
3775 DOM_SID sid;
3776 uint32 rid;
3778 if (!smbldap_get_single_attribute(ldap_struct, entry,
3779 LDAP_ATTRIBUTE_SID,
3780 sid_str,
3781 sizeof(sid_str)-1))
3782 continue;
3784 if (!string_to_sid(&sid, sid_str))
3785 continue;
3787 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3788 continue;
3790 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3791 p_num_alias_rids)) {
3792 ldap_msgfree(result);
3793 return NT_STATUS_NO_MEMORY;
3797 ldap_msgfree(result);
3798 return NT_STATUS_OK;
3801 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3802 enum pdb_policy_type type,
3803 uint32 value)
3805 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3806 int rc;
3807 LDAPMod **mods = NULL;
3808 fstring value_string;
3809 const char *policy_attr = NULL;
3811 struct ldapsam_privates *ldap_state =
3812 (struct ldapsam_privates *)methods->private_data;
3814 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3816 if (!ldap_state->domain_dn) {
3817 return NT_STATUS_INVALID_PARAMETER;
3820 policy_attr = get_account_policy_attr(type);
3821 if (policy_attr == NULL) {
3822 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3823 "policy\n"));
3824 return ntstatus;
3827 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3829 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3831 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3832 mods);
3834 ldap_mods_free(mods, True);
3836 if (rc != LDAP_SUCCESS) {
3837 return ntstatus;
3840 if (!cache_account_policy_set(type, value)) {
3841 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3842 "update local tdb cache\n"));
3843 return ntstatus;
3846 return NT_STATUS_OK;
3849 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3850 enum pdb_policy_type type,
3851 uint32_t value)
3853 return ldapsam_set_account_policy_in_ldap(methods, type,
3854 value);
3857 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3858 enum pdb_policy_type type,
3859 uint32 *value)
3861 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3862 LDAPMessage *result = NULL;
3863 LDAPMessage *entry = NULL;
3864 int count;
3865 int rc;
3866 char **vals = NULL;
3867 char *filter;
3868 const char *policy_attr = NULL;
3870 struct ldapsam_privates *ldap_state =
3871 (struct ldapsam_privates *)methods->private_data;
3873 const char *attrs[2];
3875 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3877 if (!ldap_state->domain_dn) {
3878 return NT_STATUS_INVALID_PARAMETER;
3881 policy_attr = get_account_policy_attr(type);
3882 if (!policy_attr) {
3883 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3884 "policy index: %d\n", type));
3885 return ntstatus;
3888 attrs[0] = policy_attr;
3889 attrs[1] = NULL;
3891 filter = talloc_asprintf(NULL, "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3892 if (filter == NULL) {
3893 return NT_STATUS_NO_MEMORY;
3895 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3896 LDAP_SCOPE_BASE, filter, attrs, 0,
3897 &result);
3899 if (rc != LDAP_SUCCESS) {
3900 return ntstatus;
3903 count = ldap_count_entries(priv2ld(ldap_state), result);
3904 if (count < 1) {
3905 goto out;
3908 entry = ldap_first_entry(priv2ld(ldap_state), result);
3909 if (entry == NULL) {
3910 goto out;
3913 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3914 if (vals == NULL) {
3915 goto out;
3918 *value = (uint32)atol(vals[0]);
3920 ntstatus = NT_STATUS_OK;
3922 out:
3923 if (vals)
3924 ldap_value_free(vals);
3925 ldap_msgfree(result);
3927 return ntstatus;
3930 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3932 - if user hasn't decided to use account policies inside LDAP just reuse the
3933 old tdb values
3935 - if there is a valid cache entry, return that
3936 - if there is an LDAP entry, update cache and return
3937 - otherwise set to default, update cache and return
3939 Guenther
3941 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3942 enum pdb_policy_type type,
3943 uint32_t *value)
3945 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3947 if (cache_account_policy_get(type, value)) {
3948 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3949 "cache\n"));
3950 return NT_STATUS_OK;
3953 ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3954 value);
3955 if (NT_STATUS_IS_OK(ntstatus)) {
3956 goto update_cache;
3959 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3960 "ldap\n"));
3962 #if 0
3963 /* should we automagically migrate old tdb value here ? */
3964 if (account_policy_get(type, value))
3965 goto update_ldap;
3967 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3968 "default\n", type));
3969 #endif
3971 if (!account_policy_get_default(type, value)) {
3972 return ntstatus;
3975 /* update_ldap: */
3977 ntstatus = ldapsam_set_account_policy(methods, type, *value);
3978 if (!NT_STATUS_IS_OK(ntstatus)) {
3979 return ntstatus;
3982 update_cache:
3984 if (!cache_account_policy_set(type, *value)) {
3985 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3986 "tdb as a cache\n"));
3987 return NT_STATUS_UNSUCCESSFUL;
3990 return NT_STATUS_OK;
3993 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3994 const DOM_SID *domain_sid,
3995 int num_rids,
3996 uint32 *rids,
3997 const char **names,
3998 enum lsa_SidType *attrs)
4000 struct ldapsam_privates *ldap_state =
4001 (struct ldapsam_privates *)methods->private_data;
4002 LDAPMessage *msg = NULL;
4003 LDAPMessage *entry;
4004 char *allsids = NULL;
4005 int i, rc, num_mapped;
4006 NTSTATUS result = NT_STATUS_NO_MEMORY;
4007 TALLOC_CTX *mem_ctx;
4008 LDAP *ld;
4009 bool is_builtin;
4011 mem_ctx = talloc_new(NULL);
4012 if (mem_ctx == NULL) {
4013 DEBUG(0, ("talloc_new failed\n"));
4014 goto done;
4017 if (!sid_check_is_builtin(domain_sid) &&
4018 !sid_check_is_domain(domain_sid)) {
4019 result = NT_STATUS_INVALID_PARAMETER;
4020 goto done;
4023 if (num_rids == 0) {
4024 result = NT_STATUS_NONE_MAPPED;
4025 goto done;
4028 for (i=0; i<num_rids; i++)
4029 attrs[i] = SID_NAME_UNKNOWN;
4031 allsids = talloc_strdup(mem_ctx, "");
4032 if (allsids == NULL) {
4033 goto done;
4036 for (i=0; i<num_rids; i++) {
4037 DOM_SID sid;
4038 sid_compose(&sid, domain_sid, rids[i]);
4039 allsids = talloc_asprintf_append_buffer(
4040 allsids, "(sambaSid=%s)",
4041 sid_string_talloc(mem_ctx, &sid));
4042 if (allsids == NULL) {
4043 goto done;
4047 /* First look for users */
4050 char *filter;
4051 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4053 filter = talloc_asprintf(
4054 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4055 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4057 if (filter == NULL) {
4058 goto done;
4061 rc = smbldap_search(ldap_state->smbldap_state,
4062 lp_ldap_user_suffix(),
4063 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4064 &msg);
4065 talloc_autofree_ldapmsg(mem_ctx, msg);
4068 if (rc != LDAP_SUCCESS)
4069 goto done;
4071 ld = ldap_state->smbldap_state->ldap_struct;
4072 num_mapped = 0;
4074 for (entry = ldap_first_entry(ld, msg);
4075 entry != NULL;
4076 entry = ldap_next_entry(ld, entry)) {
4077 uint32 rid;
4078 int rid_index;
4079 const char *name;
4081 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4082 &rid)) {
4083 DEBUG(2, ("Could not find sid from ldap entry\n"));
4084 continue;
4087 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4088 names);
4089 if (name == NULL) {
4090 DEBUG(2, ("Could not retrieve uid attribute\n"));
4091 continue;
4094 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4095 if (rid == rids[rid_index])
4096 break;
4099 if (rid_index == num_rids) {
4100 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4101 continue;
4104 attrs[rid_index] = SID_NAME_USER;
4105 names[rid_index] = name;
4106 num_mapped += 1;
4109 if (num_mapped == num_rids) {
4110 /* No need to look for groups anymore -- we're done */
4111 result = NT_STATUS_OK;
4112 goto done;
4115 /* Same game for groups */
4118 char *filter;
4119 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4120 "sambaGroupType", NULL };
4122 filter = talloc_asprintf(
4123 mem_ctx, "(&(objectClass=%s)(|%s))",
4124 LDAP_OBJ_GROUPMAP, allsids);
4125 if (filter == NULL) {
4126 goto done;
4129 rc = smbldap_search(ldap_state->smbldap_state,
4130 lp_ldap_suffix(),
4131 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4132 &msg);
4133 talloc_autofree_ldapmsg(mem_ctx, msg);
4136 if (rc != LDAP_SUCCESS)
4137 goto done;
4139 /* ldap_struct might have changed due to a reconnect */
4141 ld = ldap_state->smbldap_state->ldap_struct;
4143 /* For consistency checks, we already checked we're only domain or builtin */
4145 is_builtin = sid_check_is_builtin(domain_sid);
4147 for (entry = ldap_first_entry(ld, msg);
4148 entry != NULL;
4149 entry = ldap_next_entry(ld, entry))
4151 uint32 rid;
4152 int rid_index;
4153 const char *attr;
4154 enum lsa_SidType type;
4155 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4157 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4158 mem_ctx);
4159 if (attr == NULL) {
4160 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4161 dn));
4162 continue;
4165 type = (enum lsa_SidType)atol(attr);
4167 /* Consistency checks */
4168 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4169 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4170 (type != SID_NAME_DOM_GRP)))) {
4171 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4174 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4175 &rid)) {
4176 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4177 continue;
4180 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4182 if (attr == NULL) {
4183 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4184 dn));
4185 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4188 if (attr == NULL) {
4189 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4190 dn));
4191 continue;
4194 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4195 if (rid == rids[rid_index])
4196 break;
4199 if (rid_index == num_rids) {
4200 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4201 continue;
4204 attrs[rid_index] = type;
4205 names[rid_index] = attr;
4206 num_mapped += 1;
4209 result = NT_STATUS_NONE_MAPPED;
4211 if (num_mapped > 0)
4212 result = (num_mapped == num_rids) ?
4213 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4214 done:
4215 TALLOC_FREE(mem_ctx);
4216 return result;
4219 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4221 char *filter = NULL;
4222 char *escaped = NULL;
4223 char *result = NULL;
4225 if (asprintf(&filter, "(&%s(objectclass=%s))",
4226 "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4227 goto done;
4230 escaped = escape_ldap_string(talloc_tos(), username);
4231 if (escaped == NULL) goto done;
4233 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4235 done:
4236 SAFE_FREE(filter);
4237 TALLOC_FREE(escaped);
4239 return result;
4242 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4244 int i, num = 0;
4245 va_list ap;
4246 const char **result;
4248 va_start(ap, mem_ctx);
4249 while (va_arg(ap, const char *) != NULL)
4250 num += 1;
4251 va_end(ap);
4253 if ((result = TALLOC_ARRAY(mem_ctx, const char *, num+1)) == NULL) {
4254 return NULL;
4257 va_start(ap, mem_ctx);
4258 for (i=0; i<num; i++) {
4259 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4260 if (result[i] == NULL) {
4261 talloc_free(result);
4262 va_end(ap);
4263 return NULL;
4266 va_end(ap);
4268 result[num] = NULL;
4269 return result;
4272 struct ldap_search_state {
4273 struct smbldap_state *connection;
4275 uint32 acct_flags;
4276 uint16 group_type;
4278 const char *base;
4279 int scope;
4280 const char *filter;
4281 const char **attrs;
4282 int attrsonly;
4283 void *pagedresults_cookie;
4285 LDAPMessage *entries, *current_entry;
4286 bool (*ldap2displayentry)(struct ldap_search_state *state,
4287 TALLOC_CTX *mem_ctx,
4288 LDAP *ld, LDAPMessage *entry,
4289 struct samr_displayentry *result);
4292 static bool ldapsam_search_firstpage(struct pdb_search *search)
4294 struct ldap_search_state *state =
4295 (struct ldap_search_state *)search->private_data;
4296 LDAP *ld;
4297 int rc = LDAP_OPERATIONS_ERROR;
4299 state->entries = NULL;
4301 if (state->connection->paged_results) {
4302 rc = smbldap_search_paged(state->connection, state->base,
4303 state->scope, state->filter,
4304 state->attrs, state->attrsonly,
4305 lp_ldap_page_size(), &state->entries,
4306 &state->pagedresults_cookie);
4309 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4311 if (state->entries != NULL) {
4312 /* Left over from unsuccessful paged attempt */
4313 ldap_msgfree(state->entries);
4314 state->entries = NULL;
4317 rc = smbldap_search(state->connection, state->base,
4318 state->scope, state->filter, state->attrs,
4319 state->attrsonly, &state->entries);
4321 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4322 return False;
4324 /* Ok, the server was lying. It told us it could do paged
4325 * searches when it could not. */
4326 state->connection->paged_results = False;
4329 ld = state->connection->ldap_struct;
4330 if ( ld == NULL) {
4331 DEBUG(5, ("Don't have an LDAP connection right after a "
4332 "search\n"));
4333 return False;
4335 state->current_entry = ldap_first_entry(ld, state->entries);
4337 if (state->current_entry == NULL) {
4338 ldap_msgfree(state->entries);
4339 state->entries = NULL;
4342 return True;
4345 static bool ldapsam_search_nextpage(struct pdb_search *search)
4347 struct ldap_search_state *state =
4348 (struct ldap_search_state *)search->private_data;
4349 int rc;
4351 if (!state->connection->paged_results) {
4352 /* There is no next page when there are no paged results */
4353 return False;
4356 rc = smbldap_search_paged(state->connection, state->base,
4357 state->scope, state->filter, state->attrs,
4358 state->attrsonly, lp_ldap_page_size(),
4359 &state->entries,
4360 &state->pagedresults_cookie);
4362 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4363 return False;
4365 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4367 if (state->current_entry == NULL) {
4368 ldap_msgfree(state->entries);
4369 state->entries = NULL;
4372 return True;
4375 static bool ldapsam_search_next_entry(struct pdb_search *search,
4376 struct samr_displayentry *entry)
4378 struct ldap_search_state *state =
4379 (struct ldap_search_state *)search->private_data;
4380 bool result;
4382 retry:
4383 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4384 return False;
4386 if ((state->entries == NULL) &&
4387 !ldapsam_search_nextpage(search))
4388 return False;
4390 result = state->ldap2displayentry(state, search,
4391 state->connection->ldap_struct,
4392 state->current_entry, entry);
4394 if (!result) {
4395 char *dn;
4396 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4397 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4398 if (dn != NULL) ldap_memfree(dn);
4401 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4403 if (state->current_entry == NULL) {
4404 ldap_msgfree(state->entries);
4405 state->entries = NULL;
4408 if (!result) goto retry;
4410 return True;
4413 static void ldapsam_search_end(struct pdb_search *search)
4415 struct ldap_search_state *state =
4416 (struct ldap_search_state *)search->private_data;
4417 int rc;
4419 if (state->pagedresults_cookie == NULL)
4420 return;
4422 if (state->entries != NULL)
4423 ldap_msgfree(state->entries);
4425 state->entries = NULL;
4426 state->current_entry = NULL;
4428 if (!state->connection->paged_results)
4429 return;
4431 /* Tell the LDAP server we're not interested in the rest anymore. */
4433 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4434 state->filter, state->attrs,
4435 state->attrsonly, 0, &state->entries,
4436 &state->pagedresults_cookie);
4438 if (rc != LDAP_SUCCESS)
4439 DEBUG(5, ("Could not end search properly\n"));
4441 return;
4444 static bool ldapuser2displayentry(struct ldap_search_state *state,
4445 TALLOC_CTX *mem_ctx,
4446 LDAP *ld, LDAPMessage *entry,
4447 struct samr_displayentry *result)
4449 char **vals;
4450 size_t converted_size;
4451 DOM_SID sid;
4452 uint32 acct_flags;
4454 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4455 if ((vals == NULL) || (vals[0] == NULL)) {
4456 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4457 return False;
4459 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4460 ldap_value_free(vals);
4462 if ((state->acct_flags != 0) &&
4463 ((state->acct_flags & acct_flags) == 0))
4464 return False;
4466 result->acct_flags = acct_flags;
4467 result->account_name = "";
4468 result->fullname = "";
4469 result->description = "";
4471 vals = ldap_get_values(ld, entry, "uid");
4472 if ((vals == NULL) || (vals[0] == NULL)) {
4473 DEBUG(5, ("\"uid\" not found\n"));
4474 return False;
4476 if (!pull_utf8_talloc(mem_ctx,
4477 CONST_DISCARD(char **, &result->account_name),
4478 vals[0], &converted_size))
4480 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4481 strerror(errno)));
4484 ldap_value_free(vals);
4486 vals = ldap_get_values(ld, entry, "displayName");
4487 if ((vals == NULL) || (vals[0] == NULL))
4488 DEBUG(8, ("\"displayName\" not found\n"));
4489 else if (!pull_utf8_talloc(mem_ctx,
4490 CONST_DISCARD(char **, &result->fullname),
4491 vals[0], &converted_size))
4493 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4494 strerror(errno)));
4497 ldap_value_free(vals);
4499 vals = ldap_get_values(ld, entry, "description");
4500 if ((vals == NULL) || (vals[0] == NULL))
4501 DEBUG(8, ("\"description\" not found\n"));
4502 else if (!pull_utf8_talloc(mem_ctx,
4503 CONST_DISCARD(char **, &result->description),
4504 vals[0], &converted_size))
4506 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4507 strerror(errno)));
4510 ldap_value_free(vals);
4512 if ((result->account_name == NULL) ||
4513 (result->fullname == NULL) ||
4514 (result->description == NULL)) {
4515 DEBUG(0, ("talloc failed\n"));
4516 return False;
4519 vals = ldap_get_values(ld, entry, "sambaSid");
4520 if ((vals == NULL) || (vals[0] == NULL)) {
4521 DEBUG(0, ("\"objectSid\" not found\n"));
4522 return False;
4525 if (!string_to_sid(&sid, vals[0])) {
4526 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4527 ldap_value_free(vals);
4528 return False;
4530 ldap_value_free(vals);
4532 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4533 DEBUG(0, ("sid %s does not belong to our domain\n",
4534 sid_string_dbg(&sid)));
4535 return False;
4538 return True;
4542 static bool ldapsam_search_users(struct pdb_methods *methods,
4543 struct pdb_search *search,
4544 uint32 acct_flags)
4546 struct ldapsam_privates *ldap_state =
4547 (struct ldapsam_privates *)methods->private_data;
4548 struct ldap_search_state *state;
4550 state = talloc(search, struct ldap_search_state);
4551 if (state == NULL) {
4552 DEBUG(0, ("talloc failed\n"));
4553 return False;
4556 state->connection = ldap_state->smbldap_state;
4558 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4559 state->base = lp_ldap_user_suffix();
4560 else if ((acct_flags != 0) &&
4561 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4562 state->base = lp_ldap_machine_suffix();
4563 else
4564 state->base = lp_ldap_suffix();
4566 state->acct_flags = acct_flags;
4567 state->base = talloc_strdup(search, state->base);
4568 state->scope = LDAP_SCOPE_SUBTREE;
4569 state->filter = get_ldap_filter(search, "*");
4570 state->attrs = talloc_attrs(search, "uid", "sambaSid",
4571 "displayName", "description",
4572 "sambaAcctFlags", NULL);
4573 state->attrsonly = 0;
4574 state->pagedresults_cookie = NULL;
4575 state->entries = NULL;
4576 state->ldap2displayentry = ldapuser2displayentry;
4578 if ((state->filter == NULL) || (state->attrs == NULL)) {
4579 DEBUG(0, ("talloc failed\n"));
4580 return False;
4583 search->private_data = state;
4584 search->next_entry = ldapsam_search_next_entry;
4585 search->search_end = ldapsam_search_end;
4587 return ldapsam_search_firstpage(search);
4590 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4591 TALLOC_CTX *mem_ctx,
4592 LDAP *ld, LDAPMessage *entry,
4593 struct samr_displayentry *result)
4595 char **vals;
4596 size_t converted_size;
4597 DOM_SID sid;
4598 uint16 group_type;
4600 result->account_name = "";
4601 result->fullname = "";
4602 result->description = "";
4605 vals = ldap_get_values(ld, entry, "sambaGroupType");
4606 if ((vals == NULL) || (vals[0] == NULL)) {
4607 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4608 if (vals != NULL) {
4609 ldap_value_free(vals);
4611 return False;
4614 group_type = atoi(vals[0]);
4616 if ((state->group_type != 0) &&
4617 ((state->group_type != group_type))) {
4618 ldap_value_free(vals);
4619 return False;
4622 ldap_value_free(vals);
4624 /* display name is the NT group name */
4626 vals = ldap_get_values(ld, entry, "displayName");
4627 if ((vals == NULL) || (vals[0] == NULL)) {
4628 DEBUG(8, ("\"displayName\" not found\n"));
4630 /* fallback to the 'cn' attribute */
4631 vals = ldap_get_values(ld, entry, "cn");
4632 if ((vals == NULL) || (vals[0] == NULL)) {
4633 DEBUG(5, ("\"cn\" not found\n"));
4634 return False;
4636 if (!pull_utf8_talloc(mem_ctx,
4637 CONST_DISCARD(char **,
4638 &result->account_name),
4639 vals[0], &converted_size))
4641 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4642 "failed: %s", strerror(errno)));
4645 else if (!pull_utf8_talloc(mem_ctx,
4646 CONST_DISCARD(char **,
4647 &result->account_name),
4648 vals[0], &converted_size))
4650 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4651 strerror(errno)));
4654 ldap_value_free(vals);
4656 vals = ldap_get_values(ld, entry, "description");
4657 if ((vals == NULL) || (vals[0] == NULL))
4658 DEBUG(8, ("\"description\" not found\n"));
4659 else if (!pull_utf8_talloc(mem_ctx,
4660 CONST_DISCARD(char **, &result->description),
4661 vals[0], &converted_size))
4663 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4664 strerror(errno)));
4666 ldap_value_free(vals);
4668 if ((result->account_name == NULL) ||
4669 (result->fullname == NULL) ||
4670 (result->description == NULL)) {
4671 DEBUG(0, ("talloc failed\n"));
4672 return False;
4675 vals = ldap_get_values(ld, entry, "sambaSid");
4676 if ((vals == NULL) || (vals[0] == NULL)) {
4677 DEBUG(0, ("\"objectSid\" not found\n"));
4678 if (vals != NULL) {
4679 ldap_value_free(vals);
4681 return False;
4684 if (!string_to_sid(&sid, vals[0])) {
4685 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4686 return False;
4689 ldap_value_free(vals);
4691 switch (group_type) {
4692 case SID_NAME_DOM_GRP:
4693 case SID_NAME_ALIAS:
4695 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4696 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4698 DEBUG(0, ("%s is not in our domain\n",
4699 sid_string_dbg(&sid)));
4700 return False;
4702 break;
4704 default:
4705 DEBUG(0,("unkown group type: %d\n", group_type));
4706 return False;
4709 result->acct_flags = 0;
4711 return True;
4714 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4715 struct pdb_search *search,
4716 const DOM_SID *sid,
4717 enum lsa_SidType type)
4719 struct ldapsam_privates *ldap_state =
4720 (struct ldapsam_privates *)methods->private_data;
4721 struct ldap_search_state *state;
4722 fstring tmp;
4724 state = talloc(search, struct ldap_search_state);
4725 if (state == NULL) {
4726 DEBUG(0, ("talloc failed\n"));
4727 return False;
4730 state->connection = ldap_state->smbldap_state;
4732 state->base = talloc_strdup(search, lp_ldap_suffix());
4733 state->connection = ldap_state->smbldap_state;
4734 state->scope = LDAP_SCOPE_SUBTREE;
4735 state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4736 "(sambaGroupType=%d)(sambaSID=%s*))",
4737 LDAP_OBJ_GROUPMAP,
4738 type, sid_to_fstring(tmp, sid));
4739 state->attrs = talloc_attrs(search, "cn", "sambaSid",
4740 "displayName", "description",
4741 "sambaGroupType", NULL);
4742 state->attrsonly = 0;
4743 state->pagedresults_cookie = NULL;
4744 state->entries = NULL;
4745 state->group_type = type;
4746 state->ldap2displayentry = ldapgroup2displayentry;
4748 if ((state->filter == NULL) || (state->attrs == NULL)) {
4749 DEBUG(0, ("talloc failed\n"));
4750 return False;
4753 search->private_data = state;
4754 search->next_entry = ldapsam_search_next_entry;
4755 search->search_end = ldapsam_search_end;
4757 return ldapsam_search_firstpage(search);
4760 static bool ldapsam_search_groups(struct pdb_methods *methods,
4761 struct pdb_search *search)
4763 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4766 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4767 struct pdb_search *search,
4768 const DOM_SID *sid)
4770 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4773 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4775 return PDB_CAP_STORE_RIDS;
4778 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4779 uint32 *rid)
4781 struct smbldap_state *smbldap_state = priv->smbldap_state;
4783 LDAPMessage *result = NULL;
4784 LDAPMessage *entry = NULL;
4785 LDAPMod **mods = NULL;
4786 NTSTATUS status;
4787 char *value;
4788 int rc;
4789 uint32 nextRid = 0;
4790 const char *dn;
4792 TALLOC_CTX *mem_ctx;
4794 mem_ctx = talloc_new(NULL);
4795 if (mem_ctx == NULL) {
4796 DEBUG(0, ("talloc_new failed\n"));
4797 return NT_STATUS_NO_MEMORY;
4800 status = smbldap_search_domain_info(smbldap_state, &result,
4801 get_global_sam_name(), False);
4802 if (!NT_STATUS_IS_OK(status)) {
4803 DEBUG(3, ("Could not get domain info: %s\n",
4804 nt_errstr(status)));
4805 goto done;
4808 talloc_autofree_ldapmsg(mem_ctx, result);
4810 entry = ldap_first_entry(priv2ld(priv), result);
4811 if (entry == NULL) {
4812 DEBUG(0, ("Could not get domain info entry\n"));
4813 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4814 goto done;
4817 /* Find the largest of the three attributes "sambaNextRid",
4818 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4819 concept of differentiating between user and group rids, and will
4820 use only "sambaNextRid" in the future. But for compatibility
4821 reasons I look if others have chosen different strategies -- VL */
4823 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4824 "sambaNextRid", mem_ctx);
4825 if (value != NULL) {
4826 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4827 nextRid = MAX(nextRid, tmp);
4830 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4831 "sambaNextUserRid", mem_ctx);
4832 if (value != NULL) {
4833 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4834 nextRid = MAX(nextRid, tmp);
4837 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4838 "sambaNextGroupRid", mem_ctx);
4839 if (value != NULL) {
4840 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4841 nextRid = MAX(nextRid, tmp);
4844 if (nextRid == 0) {
4845 nextRid = BASE_RID-1;
4848 nextRid += 1;
4850 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4851 talloc_asprintf(mem_ctx, "%d", nextRid));
4852 talloc_autofree_ldapmod(mem_ctx, mods);
4854 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4855 status = NT_STATUS_NO_MEMORY;
4856 goto done;
4859 rc = smbldap_modify(smbldap_state, dn, mods);
4861 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4862 * please retry" */
4864 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4866 done:
4867 if (NT_STATUS_IS_OK(status)) {
4868 *rid = nextRid;
4871 TALLOC_FREE(mem_ctx);
4872 return status;
4875 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32 *rid)
4877 int i;
4879 for (i=0; i<10; i++) {
4880 NTSTATUS result = ldapsam_get_new_rid(
4881 (struct ldapsam_privates *)methods->private_data, rid);
4882 if (NT_STATUS_IS_OK(result)) {
4883 return result;
4886 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4887 return result;
4890 /* The ldap update failed (maybe a race condition), retry */
4893 /* Tried 10 times, fail. */
4894 return NT_STATUS_ACCESS_DENIED;
4897 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4899 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4900 return NT_STATUS_IS_OK(result) ? True : False;
4903 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4904 const DOM_SID *sid,
4905 union unid_t *id, enum lsa_SidType *type)
4907 struct ldapsam_privates *priv =
4908 (struct ldapsam_privates *)methods->private_data;
4909 char *filter;
4910 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4911 NULL };
4912 LDAPMessage *result = NULL;
4913 LDAPMessage *entry = NULL;
4914 bool ret = False;
4915 char *value;
4916 int rc;
4918 TALLOC_CTX *mem_ctx;
4920 mem_ctx = talloc_new(NULL);
4921 if (mem_ctx == NULL) {
4922 DEBUG(0, ("talloc_new failed\n"));
4923 return False;
4926 filter = talloc_asprintf(mem_ctx,
4927 "(&(sambaSid=%s)"
4928 "(|(objectClass=%s)(objectClass=%s)))",
4929 sid_string_talloc(mem_ctx, sid),
4930 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4931 if (filter == NULL) {
4932 DEBUG(5, ("talloc_asprintf failed\n"));
4933 goto done;
4936 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4937 attrs, &result);
4938 if (rc != LDAP_SUCCESS) {
4939 goto done;
4941 talloc_autofree_ldapmsg(mem_ctx, result);
4943 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4944 DEBUG(10, ("Got %d entries, expected one\n",
4945 ldap_count_entries(priv2ld(priv), result)));
4946 goto done;
4949 entry = ldap_first_entry(priv2ld(priv), result);
4951 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4952 "sambaGroupType", mem_ctx);
4954 if (value != NULL) {
4955 const char *gid_str;
4956 /* It's a group */
4958 gid_str = smbldap_talloc_single_attribute(
4959 priv2ld(priv), entry, "gidNumber", mem_ctx);
4960 if (gid_str == NULL) {
4961 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4962 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4963 entry)));
4964 goto done;
4967 id->gid = strtoul(gid_str, NULL, 10);
4968 *type = (enum lsa_SidType)strtoul(value, NULL, 10);
4969 ret = True;
4970 goto done;
4973 /* It must be a user */
4975 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4976 "uidNumber", mem_ctx);
4977 if (value == NULL) {
4978 DEBUG(1, ("Could not find uidNumber in %s\n",
4979 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4980 goto done;
4983 id->uid = strtoul(value, NULL, 10);
4984 *type = SID_NAME_USER;
4986 ret = True;
4987 done:
4988 TALLOC_FREE(mem_ctx);
4989 return ret;
4993 * The following functions is called only if
4994 * ldapsam:trusted and ldapsam:editposix are
4995 * set to true
4999 * ldapsam_create_user creates a new
5000 * posixAccount and sambaSamAccount object
5001 * in the ldap users subtree
5003 * The uid is allocated by winbindd.
5006 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5007 TALLOC_CTX *tmp_ctx, const char *name,
5008 uint32 acb_info, uint32 *rid)
5010 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5011 LDAPMessage *entry = NULL;
5012 LDAPMessage *result = NULL;
5013 uint32 num_result;
5014 bool is_machine = False;
5015 bool add_posix = False;
5016 LDAPMod **mods = NULL;
5017 struct samu *user;
5018 char *filter;
5019 char *username;
5020 char *homedir;
5021 char *gidstr;
5022 char *uidstr;
5023 char *shell;
5024 const char *dn = NULL;
5025 DOM_SID group_sid;
5026 DOM_SID user_sid;
5027 gid_t gid = -1;
5028 uid_t uid = -1;
5029 NTSTATUS ret;
5030 int rc;
5032 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5033 acb_info & ACB_WSTRUST ||
5034 acb_info & ACB_SVRTRUST ||
5035 acb_info & ACB_DOMTRUST) {
5036 is_machine = True;
5039 username = escape_ldap_string(talloc_tos(), name);
5040 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5041 username, LDAP_OBJ_POSIXACCOUNT);
5042 TALLOC_FREE(username);
5044 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5045 if (rc != LDAP_SUCCESS) {
5046 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5047 return NT_STATUS_ACCESS_DENIED;
5049 talloc_autofree_ldapmsg(tmp_ctx, result);
5051 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5053 if (num_result > 1) {
5054 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5055 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5058 if (num_result == 1) {
5059 char *tmp;
5060 /* check if it is just a posix account.
5061 * or if there is a sid attached to this entry
5064 entry = ldap_first_entry(priv2ld(ldap_state), result);
5065 if (!entry) {
5066 return NT_STATUS_UNSUCCESSFUL;
5069 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5070 if (tmp) {
5071 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5072 return NT_STATUS_USER_EXISTS;
5075 /* it is just a posix account, retrieve the dn for later use */
5076 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5077 if (!dn) {
5078 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5079 return NT_STATUS_NO_MEMORY;
5083 if (num_result == 0) {
5084 add_posix = True;
5087 /* Create the basic samu structure and generate the mods for the ldap commit */
5088 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5089 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5090 return ret;
5093 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5095 user = samu_new(tmp_ctx);
5096 if (!user) {
5097 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5098 return NT_STATUS_NO_MEMORY;
5101 if (!pdb_set_username(user, name, PDB_SET)) {
5102 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5103 return NT_STATUS_UNSUCCESSFUL;
5105 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5106 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5107 return NT_STATUS_UNSUCCESSFUL;
5109 if (is_machine) {
5110 if (acb_info & ACB_NORMAL) {
5111 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5112 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5113 return NT_STATUS_UNSUCCESSFUL;
5115 } else {
5116 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5117 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5118 return NT_STATUS_UNSUCCESSFUL;
5121 } else {
5122 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5123 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5124 return NT_STATUS_UNSUCCESSFUL;
5128 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5129 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5130 return NT_STATUS_UNSUCCESSFUL;
5133 if (!init_ldap_from_sam(ldap_state, NULL, &mods, user, element_is_set_or_changed)) {
5134 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5135 return NT_STATUS_UNSUCCESSFUL;
5138 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5139 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5141 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5143 if (add_posix) {
5144 char *escape_name;
5146 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5148 /* retrieve the Domain Users group gid */
5149 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_GROUP_RID_USERS) ||
5150 !sid_to_gid(&group_sid, &gid)) {
5151 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5152 return NT_STATUS_INVALID_PRIMARY_GROUP;
5155 /* lets allocate a new userid for this user */
5156 if (!winbind_allocate_uid(&uid)) {
5157 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5158 return NT_STATUS_UNSUCCESSFUL;
5162 if (is_machine) {
5163 /* TODO: choose a more appropriate default for machines */
5164 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5165 shell = talloc_strdup(tmp_ctx, "/bin/false");
5166 } else {
5167 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5168 shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5170 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5171 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5173 escape_name = escape_rdn_val_string_alloc(name);
5174 if (!escape_name) {
5175 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5176 return NT_STATUS_NO_MEMORY;
5179 if (is_machine) {
5180 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
5181 } else {
5182 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
5185 SAFE_FREE(escape_name);
5187 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5188 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5189 return NT_STATUS_NO_MEMORY;
5192 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5193 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5194 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5195 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5196 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5197 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5198 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5201 talloc_autofree_ldapmod(tmp_ctx, mods);
5203 if (add_posix) {
5204 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5205 } else {
5206 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5209 if (rc != LDAP_SUCCESS) {
5210 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5211 return NT_STATUS_UNSUCCESSFUL;
5214 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5216 flush_pwnam_cache();
5218 return NT_STATUS_OK;
5221 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5223 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5224 LDAPMessage *result = NULL;
5225 LDAPMessage *entry = NULL;
5226 int num_result;
5227 const char *dn;
5228 char *filter;
5229 int rc;
5231 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5233 filter = talloc_asprintf(tmp_ctx,
5234 "(&(uid=%s)"
5235 "(objectClass=%s)"
5236 "(objectClass=%s))",
5237 pdb_get_username(sam_acct),
5238 LDAP_OBJ_POSIXACCOUNT,
5239 LDAP_OBJ_SAMBASAMACCOUNT);
5240 if (filter == NULL) {
5241 return NT_STATUS_NO_MEMORY;
5244 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5245 if (rc != LDAP_SUCCESS) {
5246 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5247 return NT_STATUS_UNSUCCESSFUL;
5249 talloc_autofree_ldapmsg(tmp_ctx, result);
5251 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5253 if (num_result == 0) {
5254 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5255 return NT_STATUS_NO_SUCH_USER;
5258 if (num_result > 1) {
5259 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5260 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5263 entry = ldap_first_entry(priv2ld(ldap_state), result);
5264 if (!entry) {
5265 return NT_STATUS_UNSUCCESSFUL;
5268 /* it is just a posix account, retrieve the dn for later use */
5269 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5270 if (!dn) {
5271 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5272 return NT_STATUS_NO_MEMORY;
5275 /* try to remove memberships first */
5277 NTSTATUS status;
5278 struct dom_sid *sids = NULL;
5279 gid_t *gids = NULL;
5280 size_t num_groups = 0;
5281 int i;
5282 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5284 status = ldapsam_enum_group_memberships(my_methods,
5285 tmp_ctx,
5286 sam_acct,
5287 &sids,
5288 &gids,
5289 &num_groups);
5290 if (!NT_STATUS_IS_OK(status)) {
5291 goto delete_dn;
5294 for (i=0; i < num_groups; i++) {
5296 uint32_t group_rid;
5298 sid_peek_rid(&sids[i], &group_rid);
5300 ldapsam_del_groupmem(my_methods,
5301 tmp_ctx,
5302 group_rid,
5303 user_rid);
5307 delete_dn:
5309 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5310 if (rc != LDAP_SUCCESS) {
5311 return NT_STATUS_UNSUCCESSFUL;
5314 flush_pwnam_cache();
5316 return NT_STATUS_OK;
5320 * ldapsam_create_group creates a new
5321 * posixGroup and sambaGroupMapping object
5322 * in the ldap groups subtree
5324 * The gid is allocated by winbindd.
5327 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5328 TALLOC_CTX *tmp_ctx,
5329 const char *name,
5330 uint32 *rid)
5332 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5333 NTSTATUS ret;
5334 LDAPMessage *entry = NULL;
5335 LDAPMessage *result = NULL;
5336 uint32 num_result;
5337 bool is_new_entry = False;
5338 LDAPMod **mods = NULL;
5339 char *filter;
5340 char *groupsidstr;
5341 char *groupname;
5342 char *grouptype;
5343 char *gidstr;
5344 const char *dn = NULL;
5345 DOM_SID group_sid;
5346 gid_t gid = -1;
5347 int rc;
5349 groupname = escape_ldap_string(talloc_tos(), name);
5350 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5351 groupname, LDAP_OBJ_POSIXGROUP);
5352 TALLOC_FREE(groupname);
5354 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5355 if (rc != LDAP_SUCCESS) {
5356 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5357 return NT_STATUS_UNSUCCESSFUL;
5359 talloc_autofree_ldapmsg(tmp_ctx, result);
5361 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5363 if (num_result > 1) {
5364 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5365 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5368 if (num_result == 1) {
5369 char *tmp;
5370 /* check if it is just a posix group.
5371 * or if there is a sid attached to this entry
5374 entry = ldap_first_entry(priv2ld(ldap_state), result);
5375 if (!entry) {
5376 return NT_STATUS_UNSUCCESSFUL;
5379 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5380 if (tmp) {
5381 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5382 return NT_STATUS_GROUP_EXISTS;
5385 /* it is just a posix group, retrieve the gid and the dn for later use */
5386 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5387 if (!tmp) {
5388 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5389 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5392 gid = strtoul(tmp, NULL, 10);
5394 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5395 if (!dn) {
5396 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5397 return NT_STATUS_NO_MEMORY;
5401 if (num_result == 0) {
5402 char *escape_name;
5404 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5406 is_new_entry = True;
5408 /* lets allocate a new groupid for this group */
5409 if (!winbind_allocate_gid(&gid)) {
5410 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5411 return NT_STATUS_UNSUCCESSFUL;
5414 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5416 escape_name = escape_rdn_val_string_alloc(name);
5417 if (!escape_name) {
5418 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5419 return NT_STATUS_NO_MEMORY;
5422 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
5424 SAFE_FREE(escape_name);
5426 if (!gidstr || !dn) {
5427 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5428 return NT_STATUS_NO_MEMORY;
5431 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5432 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5433 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5436 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5437 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5438 return ret;
5441 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5443 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5444 &group_sid));
5445 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5447 if (!groupsidstr || !grouptype) {
5448 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5449 return NT_STATUS_NO_MEMORY;
5452 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5453 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5454 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5455 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5456 talloc_autofree_ldapmod(tmp_ctx, mods);
5458 if (is_new_entry) {
5459 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5460 #if 0
5461 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5462 /* This call may fail with rfc2307bis schema */
5463 /* Retry adding a structural class */
5464 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5465 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5467 #endif
5468 } else {
5469 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5472 if (rc != LDAP_SUCCESS) {
5473 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5474 return NT_STATUS_UNSUCCESSFUL;
5477 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5479 return NT_STATUS_OK;
5482 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32 rid)
5484 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5485 LDAPMessage *result = NULL;
5486 LDAPMessage *entry = NULL;
5487 int num_result;
5488 const char *dn;
5489 char *gidstr;
5490 char *filter;
5491 DOM_SID group_sid;
5492 int rc;
5494 /* get the group sid */
5495 sid_compose(&group_sid, get_global_sam_sid(), rid);
5497 filter = talloc_asprintf(tmp_ctx,
5498 "(&(sambaSID=%s)"
5499 "(objectClass=%s)"
5500 "(objectClass=%s))",
5501 sid_string_talloc(tmp_ctx, &group_sid),
5502 LDAP_OBJ_POSIXGROUP,
5503 LDAP_OBJ_GROUPMAP);
5504 if (filter == NULL) {
5505 return NT_STATUS_NO_MEMORY;
5508 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5509 if (rc != LDAP_SUCCESS) {
5510 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5511 return NT_STATUS_UNSUCCESSFUL;
5513 talloc_autofree_ldapmsg(tmp_ctx, result);
5515 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5517 if (num_result == 0) {
5518 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5519 return NT_STATUS_NO_SUCH_GROUP;
5522 if (num_result > 1) {
5523 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5524 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5527 entry = ldap_first_entry(priv2ld(ldap_state), result);
5528 if (!entry) {
5529 return NT_STATUS_UNSUCCESSFUL;
5532 /* here it is, retrieve the dn for later use */
5533 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5534 if (!dn) {
5535 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5536 return NT_STATUS_NO_MEMORY;
5539 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5540 if (!gidstr) {
5541 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5542 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5545 /* check no user have this group marked as primary group */
5546 filter = talloc_asprintf(tmp_ctx,
5547 "(&(gidNumber=%s)"
5548 "(objectClass=%s)"
5549 "(objectClass=%s))",
5550 gidstr,
5551 LDAP_OBJ_POSIXACCOUNT,
5552 LDAP_OBJ_SAMBASAMACCOUNT);
5554 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5555 if (rc != LDAP_SUCCESS) {
5556 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5557 return NT_STATUS_UNSUCCESSFUL;
5559 talloc_autofree_ldapmsg(tmp_ctx, result);
5561 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5563 if (num_result != 0) {
5564 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5565 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5568 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5569 if (rc != LDAP_SUCCESS) {
5570 return NT_STATUS_UNSUCCESSFUL;
5573 return NT_STATUS_OK;
5576 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5577 TALLOC_CTX *tmp_ctx,
5578 uint32 group_rid,
5579 uint32 member_rid,
5580 int modop)
5582 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5583 LDAPMessage *entry = NULL;
5584 LDAPMessage *result = NULL;
5585 uint32 num_result;
5586 LDAPMod **mods = NULL;
5587 char *filter;
5588 char *uidstr;
5589 const char *dn = NULL;
5590 DOM_SID group_sid;
5591 DOM_SID member_sid;
5592 int rc;
5594 switch (modop) {
5595 case LDAP_MOD_ADD:
5596 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5597 break;
5598 case LDAP_MOD_DELETE:
5599 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5600 break;
5601 default:
5602 return NT_STATUS_UNSUCCESSFUL;
5605 /* get member sid */
5606 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5608 /* get the group sid */
5609 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5611 filter = talloc_asprintf(tmp_ctx,
5612 "(&(sambaSID=%s)"
5613 "(objectClass=%s)"
5614 "(objectClass=%s))",
5615 sid_string_talloc(tmp_ctx, &member_sid),
5616 LDAP_OBJ_POSIXACCOUNT,
5617 LDAP_OBJ_SAMBASAMACCOUNT);
5618 if (filter == NULL) {
5619 return NT_STATUS_NO_MEMORY;
5622 /* get the member uid */
5623 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5624 if (rc != LDAP_SUCCESS) {
5625 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5626 return NT_STATUS_UNSUCCESSFUL;
5628 talloc_autofree_ldapmsg(tmp_ctx, result);
5630 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5632 if (num_result == 0) {
5633 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5634 return NT_STATUS_NO_SUCH_MEMBER;
5637 if (num_result > 1) {
5638 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5639 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5642 entry = ldap_first_entry(priv2ld(ldap_state), result);
5643 if (!entry) {
5644 return NT_STATUS_UNSUCCESSFUL;
5647 if (modop == LDAP_MOD_DELETE) {
5648 /* check if we are trying to remove the member from his primary group */
5649 char *gidstr;
5650 gid_t user_gid, group_gid;
5652 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5653 if (!gidstr) {
5654 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5655 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5658 user_gid = strtoul(gidstr, NULL, 10);
5660 if (!sid_to_gid(&group_sid, &group_gid)) {
5661 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5662 return NT_STATUS_UNSUCCESSFUL;
5665 if (user_gid == group_gid) {
5666 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5667 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5671 /* here it is, retrieve the uid for later use */
5672 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5673 if (!uidstr) {
5674 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5675 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5678 filter = talloc_asprintf(tmp_ctx,
5679 "(&(sambaSID=%s)"
5680 "(objectClass=%s)"
5681 "(objectClass=%s))",
5682 sid_string_talloc(tmp_ctx, &group_sid),
5683 LDAP_OBJ_POSIXGROUP,
5684 LDAP_OBJ_GROUPMAP);
5686 /* get the group */
5687 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5688 if (rc != LDAP_SUCCESS) {
5689 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5690 return NT_STATUS_UNSUCCESSFUL;
5692 talloc_autofree_ldapmsg(tmp_ctx, result);
5694 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5696 if (num_result == 0) {
5697 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5698 return NT_STATUS_NO_SUCH_GROUP;
5701 if (num_result > 1) {
5702 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5703 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5706 entry = ldap_first_entry(priv2ld(ldap_state), result);
5707 if (!entry) {
5708 return NT_STATUS_UNSUCCESSFUL;
5711 /* here it is, retrieve the dn for later use */
5712 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5713 if (!dn) {
5714 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5715 return NT_STATUS_NO_MEMORY;
5718 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5720 talloc_autofree_ldapmod(tmp_ctx, mods);
5722 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5723 if (rc != LDAP_SUCCESS) {
5724 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5725 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5726 return NT_STATUS_MEMBER_IN_GROUP;
5728 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5729 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5730 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5732 return NT_STATUS_UNSUCCESSFUL;
5735 return NT_STATUS_OK;
5738 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5739 TALLOC_CTX *tmp_ctx,
5740 uint32 group_rid,
5741 uint32 member_rid)
5743 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5745 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5746 TALLOC_CTX *tmp_ctx,
5747 uint32 group_rid,
5748 uint32 member_rid)
5750 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5753 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5754 TALLOC_CTX *mem_ctx,
5755 struct samu *sampass)
5757 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5758 LDAPMessage *entry = NULL;
5759 LDAPMessage *result = NULL;
5760 uint32 num_result;
5761 LDAPMod **mods = NULL;
5762 char *filter;
5763 char *escape_username;
5764 char *gidstr;
5765 const char *dn = NULL;
5766 gid_t gid;
5767 int rc;
5769 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5771 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5772 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5773 return NT_STATUS_UNSUCCESSFUL;
5775 gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5776 if (!gidstr) {
5777 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5778 return NT_STATUS_NO_MEMORY;
5781 escape_username = escape_ldap_string(talloc_tos(),
5782 pdb_get_username(sampass));
5783 if (escape_username== NULL) {
5784 return NT_STATUS_NO_MEMORY;
5787 filter = talloc_asprintf(mem_ctx,
5788 "(&(uid=%s)"
5789 "(objectClass=%s)"
5790 "(objectClass=%s))",
5791 escape_username,
5792 LDAP_OBJ_POSIXACCOUNT,
5793 LDAP_OBJ_SAMBASAMACCOUNT);
5795 TALLOC_FREE(escape_username);
5797 if (filter == NULL) {
5798 return NT_STATUS_NO_MEMORY;
5801 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5802 if (rc != LDAP_SUCCESS) {
5803 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5804 return NT_STATUS_UNSUCCESSFUL;
5806 talloc_autofree_ldapmsg(mem_ctx, result);
5808 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5810 if (num_result == 0) {
5811 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5812 return NT_STATUS_NO_SUCH_USER;
5815 if (num_result > 1) {
5816 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5817 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5820 entry = ldap_first_entry(priv2ld(ldap_state), result);
5821 if (!entry) {
5822 return NT_STATUS_UNSUCCESSFUL;
5825 /* retrieve the dn for later use */
5826 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5827 if (!dn) {
5828 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5829 return NT_STATUS_NO_MEMORY;
5832 /* remove the old one, and add the new one, this way we do not risk races */
5833 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
5835 if (mods == NULL) {
5836 return NT_STATUS_OK;
5839 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5841 if (rc != LDAP_SUCCESS) {
5842 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
5843 pdb_get_username(sampass), gidstr));
5844 return NT_STATUS_UNSUCCESSFUL;
5847 flush_pwnam_cache();
5849 return NT_STATUS_OK;
5853 /**********************************************************************
5854 trusted domains functions
5855 *********************************************************************/
5857 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
5858 const char *domain)
5860 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
5861 ldap_state->domain_dn);
5864 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
5865 TALLOC_CTX *mem_ctx,
5866 const char *domain, LDAPMessage **entry)
5868 int rc;
5869 char *filter;
5870 int scope = LDAP_SCOPE_SUBTREE;
5871 const char **attrs = NULL; /* NULL: get all attrs */
5872 int attrsonly = 0; /* 0: return values too */
5873 LDAPMessage *result = NULL;
5874 char *trusted_dn;
5875 uint32 num_result;
5877 filter = talloc_asprintf(talloc_tos(),
5878 "(&(objectClass=%s)(sambaDomainName=%s))",
5879 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
5881 trusted_dn = trusteddom_dn(ldap_state, domain);
5882 if (trusted_dn == NULL) {
5883 return False;
5885 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
5886 filter, attrs, attrsonly, &result);
5888 if (result != NULL) {
5889 talloc_autofree_ldapmsg(mem_ctx, result);
5892 if (rc == LDAP_NO_SUCH_OBJECT) {
5893 *entry = NULL;
5894 return True;
5897 if (rc != LDAP_SUCCESS) {
5898 return False;
5901 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5903 if (num_result > 1) {
5904 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
5905 "%s object for domain '%s'?!\n",
5906 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
5907 return False;
5910 if (num_result == 0) {
5911 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
5912 "%s object for domain %s.\n",
5913 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
5914 *entry = NULL;
5915 } else {
5916 *entry = ldap_first_entry(priv2ld(ldap_state), result);
5919 return True;
5922 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
5923 const char *domain,
5924 char** pwd,
5925 DOM_SID *sid,
5926 time_t *pass_last_set_time)
5928 struct ldapsam_privates *ldap_state =
5929 (struct ldapsam_privates *)methods->private_data;
5930 LDAPMessage *entry = NULL;
5932 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
5934 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
5935 (entry == NULL))
5937 return False;
5940 /* password */
5941 if (pwd != NULL) {
5942 char *pwd_str;
5943 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5944 entry, "sambaClearTextPassword", talloc_tos());
5945 if (pwd_str == NULL) {
5946 return False;
5948 /* trusteddom_pw routines do not use talloc yet... */
5949 *pwd = SMB_STRDUP(pwd_str);
5950 if (*pwd == NULL) {
5951 return False;
5955 /* last change time */
5956 if (pass_last_set_time != NULL) {
5957 char *time_str;
5958 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5959 entry, "sambaPwdLastSet", talloc_tos());
5960 if (time_str == NULL) {
5961 return False;
5963 *pass_last_set_time = (time_t)atol(time_str);
5966 /* domain sid */
5967 if (sid != NULL) {
5968 char *sid_str;
5969 DOM_SID *dom_sid;
5970 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5971 entry, "sambaSID",
5972 talloc_tos());
5973 if (sid_str == NULL) {
5974 return False;
5976 dom_sid = string_sid_talloc(talloc_tos(), sid_str);
5977 if (dom_sid == NULL) {
5978 return False;
5980 sid_copy(sid, dom_sid);
5983 return True;
5986 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
5987 const char* domain,
5988 const char* pwd,
5989 const DOM_SID *sid)
5991 struct ldapsam_privates *ldap_state =
5992 (struct ldapsam_privates *)methods->private_data;
5993 LDAPMessage *entry = NULL;
5994 LDAPMod **mods = NULL;
5995 char *prev_pwd = NULL;
5996 char *trusted_dn = NULL;
5997 int rc;
5999 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6002 * get the current entry (if there is one) in order to put the
6003 * current password into the previous password attribute
6005 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6006 return False;
6009 mods = NULL;
6010 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6011 LDAP_OBJ_TRUSTDOM_PASSWORD);
6012 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6013 domain);
6014 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6015 sid_string_tos(sid));
6016 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6017 talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6018 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6019 "sambaClearTextPassword", pwd);
6021 if (entry != NULL) {
6022 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6023 entry, "sambaClearTextPassword", talloc_tos());
6024 if (prev_pwd != NULL) {
6025 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6026 "sambaPreviousClearTextPassword",
6027 prev_pwd);
6031 talloc_autofree_ldapmod(talloc_tos(), mods);
6033 trusted_dn = trusteddom_dn(ldap_state, domain);
6034 if (trusted_dn == NULL) {
6035 return False;
6037 if (entry == NULL) {
6038 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6039 } else {
6040 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6043 if (rc != LDAP_SUCCESS) {
6044 DEBUG(1, ("error writing trusted domain password!\n"));
6045 return False;
6048 return True;
6051 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6052 const char *domain)
6054 int rc;
6055 struct ldapsam_privates *ldap_state =
6056 (struct ldapsam_privates *)methods->private_data;
6057 LDAPMessage *entry = NULL;
6058 const char *trusted_dn;
6060 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6061 return False;
6064 if (entry == NULL) {
6065 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6066 "%s\n", domain));
6067 return True;
6070 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6071 entry);
6072 if (trusted_dn == NULL) {
6073 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6074 return False;
6077 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6078 if (rc != LDAP_SUCCESS) {
6079 return False;
6082 return True;
6085 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6086 TALLOC_CTX *mem_ctx,
6087 uint32 *num_domains,
6088 struct trustdom_info ***domains)
6090 int rc;
6091 struct ldapsam_privates *ldap_state =
6092 (struct ldapsam_privates *)methods->private_data;
6093 char *filter;
6094 int scope = LDAP_SCOPE_SUBTREE;
6095 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6096 int attrsonly = 0; /* 0: return values too */
6097 LDAPMessage *result = NULL;
6098 LDAPMessage *entry = NULL;
6100 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6101 LDAP_OBJ_TRUSTDOM_PASSWORD);
6103 rc = smbldap_search(ldap_state->smbldap_state,
6104 ldap_state->domain_dn,
6105 scope,
6106 filter,
6107 attrs,
6108 attrsonly,
6109 &result);
6111 if (result != NULL) {
6112 talloc_autofree_ldapmsg(mem_ctx, result);
6115 if (rc != LDAP_SUCCESS) {
6116 return NT_STATUS_UNSUCCESSFUL;
6119 *num_domains = 0;
6120 if (!(*domains = TALLOC_ARRAY(mem_ctx, struct trustdom_info *, 1))) {
6121 DEBUG(1, ("talloc failed\n"));
6122 return NT_STATUS_NO_MEMORY;
6125 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6126 entry != NULL;
6127 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6129 char *dom_name, *dom_sid_str;
6130 struct trustdom_info *dom_info;
6132 dom_info = TALLOC_P(*domains, struct trustdom_info);
6133 if (dom_info == NULL) {
6134 DEBUG(1, ("talloc failed\n"));
6135 return NT_STATUS_NO_MEMORY;
6138 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6139 entry,
6140 "sambaDomainName",
6141 talloc_tos());
6142 if (dom_name == NULL) {
6143 DEBUG(1, ("talloc failed\n"));
6144 return NT_STATUS_NO_MEMORY;
6146 dom_info->name = dom_name;
6148 dom_sid_str = smbldap_talloc_single_attribute(
6149 priv2ld(ldap_state), entry, "sambaSID",
6150 talloc_tos());
6151 if (dom_sid_str == NULL) {
6152 DEBUG(1, ("talloc failed\n"));
6153 return NT_STATUS_NO_MEMORY;
6155 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6156 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6157 dom_sid_str));
6158 return NT_STATUS_UNSUCCESSFUL;
6161 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6162 domains, num_domains);
6164 if (*domains == NULL) {
6165 DEBUG(1, ("talloc failed\n"));
6166 return NT_STATUS_NO_MEMORY;
6170 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6171 return NT_STATUS_OK;
6175 /**********************************************************************
6176 Housekeeping
6177 *********************************************************************/
6179 static void free_private_data(void **vp)
6181 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6183 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6185 if ((*ldap_state)->result != NULL) {
6186 ldap_msgfree((*ldap_state)->result);
6187 (*ldap_state)->result = NULL;
6189 if ((*ldap_state)->domain_dn != NULL) {
6190 SAFE_FREE((*ldap_state)->domain_dn);
6193 *ldap_state = NULL;
6195 /* No need to free any further, as it is talloc()ed */
6198 /*********************************************************************
6199 Intitalise the parts of the pdb_methods structure that are common to
6200 all pdb_ldap modes
6201 *********************************************************************/
6203 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6205 NTSTATUS nt_status;
6206 struct ldapsam_privates *ldap_state;
6208 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6209 return nt_status;
6212 (*pdb_method)->name = "ldapsam";
6214 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6215 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6216 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6217 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6218 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6219 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6221 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6222 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6223 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6224 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6225 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6226 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6227 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6229 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6230 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6232 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6234 (*pdb_method)->capabilities = ldapsam_capabilities;
6235 (*pdb_method)->new_rid = ldapsam_new_rid;
6237 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6238 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6239 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6240 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6242 /* TODO: Setup private data and free */
6244 if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
6245 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6246 return NT_STATUS_NO_MEMORY;
6249 nt_status = smbldap_init(*pdb_method, pdb_get_event_context(),
6250 location, &ldap_state->smbldap_state);
6252 if ( !NT_STATUS_IS_OK(nt_status) ) {
6253 return nt_status;
6256 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6257 return NT_STATUS_NO_MEMORY;
6260 (*pdb_method)->private_data = ldap_state;
6262 (*pdb_method)->free_private_data = free_private_data;
6264 return NT_STATUS_OK;
6267 /**********************************************************************
6268 Initialise the 'compat' mode for pdb_ldap
6269 *********************************************************************/
6271 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
6273 NTSTATUS nt_status;
6274 struct ldapsam_privates *ldap_state;
6275 char *uri = talloc_strdup( NULL, location );
6277 trim_char( uri, '\"', '\"' );
6278 nt_status = pdb_init_ldapsam_common( pdb_method, uri );
6279 if ( uri )
6280 TALLOC_FREE( uri );
6282 if ( !NT_STATUS_IS_OK(nt_status) ) {
6283 return nt_status;
6286 (*pdb_method)->name = "ldapsam_compat";
6288 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6289 ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
6291 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6293 return NT_STATUS_OK;
6296 /**********************************************************************
6297 Initialise the normal mode for pdb_ldap
6298 *********************************************************************/
6300 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
6302 NTSTATUS nt_status;
6303 struct ldapsam_privates *ldap_state = NULL;
6304 uint32 alg_rid_base;
6305 char *alg_rid_base_string = NULL;
6306 LDAPMessage *result = NULL;
6307 LDAPMessage *entry = NULL;
6308 DOM_SID ldap_domain_sid;
6309 DOM_SID secrets_domain_sid;
6310 char *domain_sid_string = NULL;
6311 char *dn = NULL;
6312 char *uri = talloc_strdup( NULL, location );
6314 trim_char( uri, '\"', '\"' );
6315 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6316 if (uri) {
6317 TALLOC_FREE(uri);
6320 if (!NT_STATUS_IS_OK(nt_status)) {
6321 return nt_status;
6324 (*pdb_method)->name = "ldapsam";
6326 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6327 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6328 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6329 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6330 (*pdb_method)->search_users = ldapsam_search_users;
6331 (*pdb_method)->search_groups = ldapsam_search_groups;
6332 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6334 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6335 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6336 (*pdb_method)->enum_group_memberships =
6337 ldapsam_enum_group_memberships;
6338 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6339 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6341 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6342 (*pdb_method)->create_user = ldapsam_create_user;
6343 (*pdb_method)->delete_user = ldapsam_delete_user;
6344 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6345 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6346 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6347 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6348 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6352 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6353 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6355 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6357 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6358 &result,
6359 ldap_state->domain_name, True);
6361 if ( !NT_STATUS_IS_OK(nt_status) ) {
6362 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
6363 "info, nor add one to the domain\n"));
6364 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
6365 "will be unable to allocate new users/groups, "
6366 "and will risk BDCs having inconsistant SIDs\n"));
6367 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6368 return NT_STATUS_OK;
6371 /* Given that the above might fail, everything below this must be
6372 * optional */
6374 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6375 result);
6376 if (!entry) {
6377 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6378 "entry\n"));
6379 ldap_msgfree(result);
6380 return NT_STATUS_UNSUCCESSFUL;
6383 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6384 if (!dn) {
6385 ldap_msgfree(result);
6386 return NT_STATUS_UNSUCCESSFUL;
6389 ldap_state->domain_dn = smb_xstrdup(dn);
6390 TALLOC_FREE(dn);
6392 domain_sid_string = smbldap_talloc_single_attribute(
6393 ldap_state->smbldap_state->ldap_struct,
6394 entry,
6395 get_userattr_key2string(ldap_state->schema_ver,
6396 LDAP_ATTR_USER_SID),
6397 talloc_tos());
6399 if (domain_sid_string) {
6400 bool found_sid;
6401 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6402 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6403 "read as a valid SID\n", domain_sid_string));
6404 ldap_msgfree(result);
6405 TALLOC_FREE(domain_sid_string);
6406 return NT_STATUS_INVALID_PARAMETER;
6408 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6409 &secrets_domain_sid);
6410 if (!found_sid || !sid_equal(&secrets_domain_sid,
6411 &ldap_domain_sid)) {
6412 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6413 "%s based on pdb_ldap results %s -> %s\n",
6414 ldap_state->domain_name,
6415 sid_string_dbg(&secrets_domain_sid),
6416 sid_string_dbg(&ldap_domain_sid)));
6418 /* reset secrets.tdb sid */
6419 secrets_store_domain_sid(ldap_state->domain_name,
6420 &ldap_domain_sid);
6421 DEBUG(1, ("New global sam SID: %s\n",
6422 sid_string_dbg(get_global_sam_sid())));
6424 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6425 TALLOC_FREE(domain_sid_string);
6428 alg_rid_base_string = smbldap_talloc_single_attribute(
6429 ldap_state->smbldap_state->ldap_struct,
6430 entry,
6431 get_attr_key2string( dominfo_attr_list,
6432 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6433 talloc_tos());
6434 if (alg_rid_base_string) {
6435 alg_rid_base = (uint32)atol(alg_rid_base_string);
6436 if (alg_rid_base != algorithmic_rid_base()) {
6437 DEBUG(0, ("The value of 'algorithmic RID base' has "
6438 "changed since the LDAP\n"
6439 "database was initialised. Aborting. \n"));
6440 ldap_msgfree(result);
6441 TALLOC_FREE(alg_rid_base_string);
6442 return NT_STATUS_UNSUCCESSFUL;
6444 TALLOC_FREE(alg_rid_base_string);
6446 ldap_msgfree(result);
6448 return NT_STATUS_OK;
6451 NTSTATUS pdb_ldap_init(void)
6453 NTSTATUS nt_status;
6454 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6455 return nt_status;
6457 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
6458 return nt_status;
6460 /* Let pdb_nds register backends */
6461 pdb_nds_init();
6463 return NT_STATUS_OK;