s4:librpc/rpc: add dcerpc_secondary_auth_connection()
[Samba.git] / source3 / passdb / pdb_ldap.c
blobc65fb0877a1bcfbdf7e48161b5196b8d27a9b819
1 /*
2 Unix SMB/CIFS implementation.
3 LDAP protocol helper functions for SAMBA
4 Copyright (C) Jean François Micouleau 1998
5 Copyright (C) Gerald Carter 2001-2003
6 Copyright (C) Shahms King 2001
7 Copyright (C) Andrew Bartlett 2002-2003
8 Copyright (C) Stefan (metze) Metzmacher 2002-2003
9 Copyright (C) Simo Sorce 2006
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 3 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 /* TODO:
27 * persistent connections: if using NSS LDAP, many connections are made
28 * however, using only one within Samba would be nice
30 * Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
32 * Other LDAP based login attributes: accountExpires, etc.
33 * (should be the domain of Samba proper, but the sam_password/struct samu
34 * structures don't have fields for some of these attributes)
36 * SSL is done, but can't get the certificate based authentication to work
37 * against on my test platform (Linux 2.4, OpenLDAP 2.x)
40 /* NOTE: this will NOT work against an Active Directory server
41 * due to the fact that the two password fields cannot be retrieved
42 * from a server; recommend using security = domain in this situation
43 * and/or winbind
46 #include "includes.h"
47 #include "passdb.h"
48 #include "../libcli/auth/libcli_auth.h"
49 #include "secrets.h"
50 #include "idmap_cache.h"
51 #include "../libcli/security/security.h"
52 #include "../lib/util/util_pw.h"
53 #include "lib/winbind_util.h"
54 #include "librpc/gen_ndr/idmap.h"
55 #include "lib/param/loadparm.h"
56 #include "lib/util_sid_passdb.h"
58 #undef DBGC_CLASS
59 #define DBGC_CLASS DBGC_PASSDB
61 #include <lber.h>
62 #include <ldap.h>
65 #include "smbldap.h"
66 #include "passdb/pdb_ldap.h"
67 #include "passdb/pdb_nds.h"
68 #include "passdb/pdb_ipa.h"
69 #include "passdb/pdb_ldap_util.h"
70 #include "passdb/pdb_ldap_schema.h"
72 /**********************************************************************
73 Simple helper function to make stuff better readable
74 **********************************************************************/
76 LDAP *priv2ld(struct ldapsam_privates *priv)
78 return priv->smbldap_state->ldap_struct;
81 /**********************************************************************
82 Get the attribute name given a user schame version.
83 **********************************************************************/
85 static const char* get_userattr_key2string( int schema_ver, int key )
87 switch ( schema_ver ) {
88 case SCHEMAVER_SAMBASAMACCOUNT:
89 return get_attr_key2string( attrib_map_v30, key );
91 default:
92 DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
93 break;
95 return NULL;
98 /**********************************************************************
99 Return the list of attribute names given a user schema version.
100 **********************************************************************/
102 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
104 switch ( schema_ver ) {
105 case SCHEMAVER_SAMBASAMACCOUNT:
106 return get_attr_list( mem_ctx, attrib_map_v30 );
107 default:
108 DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
109 break;
112 return NULL;
115 /**************************************************************************
116 Return the list of attribute names to delete given a user schema version.
117 **************************************************************************/
119 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
120 int schema_ver )
122 switch ( schema_ver ) {
123 case SCHEMAVER_SAMBASAMACCOUNT:
124 return get_attr_list( mem_ctx,
125 attrib_map_to_delete_v30 );
126 default:
127 DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
128 break;
131 return NULL;
135 /*******************************************************************
136 Generate the LDAP search filter for the objectclass based on the
137 version of the schema we are using.
138 ******************************************************************/
140 static const char* get_objclass_filter( int schema_ver )
142 fstring objclass_filter;
143 char *result;
145 switch( schema_ver ) {
146 case SCHEMAVER_SAMBASAMACCOUNT:
147 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
148 break;
149 default:
150 DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
151 objclass_filter[0] = '\0';
152 break;
155 result = talloc_strdup(talloc_tos(), objclass_filter);
156 SMB_ASSERT(result != NULL);
157 return result;
160 /*****************************************************************
161 Scan a sequence number off OpenLDAP's syncrepl contextCSN
162 ******************************************************************/
164 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
166 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
167 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
168 LDAPMessage *msg = NULL;
169 LDAPMessage *entry = NULL;
170 TALLOC_CTX *mem_ctx;
171 char **values = NULL;
172 int rc, num_result, num_values, rid;
173 char *suffix = NULL;
174 char *tok;
175 const char *p;
176 const char **attrs;
178 /* Unfortunatly there is no proper way to detect syncrepl-support in
179 * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
180 * but do not show up in the root-DSE yet. Neither we can query the
181 * subschema-context for the syncProviderSubentry or syncConsumerSubentry
182 * objectclass. Currently we require lp_ldap_suffix() to show up as
183 * namingContext. - Guenther
186 if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
187 return ntstatus;
190 if (!seq_num) {
191 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
192 return ntstatus;
195 if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix(talloc_tos()))) {
196 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
197 "as top-level namingContext\n", lp_ldap_suffix(talloc_tos())));
198 return ntstatus;
201 mem_ctx = talloc_init("ldapsam_get_seq_num");
203 if (mem_ctx == NULL)
204 return NT_STATUS_NO_MEMORY;
206 if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
207 ntstatus = NT_STATUS_NO_MEMORY;
208 goto done;
211 /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
212 rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
213 if (rid > 0) {
215 /* consumer syncreplCookie: */
216 /* csn=20050126161620Z#0000001#00#00000 */
217 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
218 attrs[1] = NULL;
219 suffix = talloc_asprintf(mem_ctx,
220 "cn=syncrepl%d,%s", rid, lp_ldap_suffix(talloc_tos()));
221 if (!suffix) {
222 ntstatus = NT_STATUS_NO_MEMORY;
223 goto done;
225 } else {
227 /* provider contextCSN */
228 /* 20050126161620Z#000009#00#000000 */
229 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
230 attrs[1] = NULL;
231 suffix = talloc_asprintf(mem_ctx,
232 "cn=ldapsync,%s", lp_ldap_suffix(talloc_tos()));
234 if (!suffix) {
235 ntstatus = NT_STATUS_NO_MEMORY;
236 goto done;
240 rc = smbldap_search(ldap_state->smbldap_state, suffix,
241 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
243 if (rc != LDAP_SUCCESS) {
244 goto done;
247 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
248 if (num_result != 1) {
249 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
250 goto done;
253 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
254 if (entry == NULL) {
255 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
256 goto done;
259 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
260 if (values == NULL) {
261 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
262 goto done;
265 num_values = ldap_count_values(values);
266 if (num_values == 0) {
267 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
268 goto done;
271 p = values[0];
272 if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
273 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
274 goto done;
277 p = tok;
278 if (!strncmp(p, "csn=", strlen("csn=")))
279 p += strlen("csn=");
281 DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
283 *seq_num = generalized_to_unix_time(p);
285 /* very basic sanity check */
286 if (*seq_num <= 0) {
287 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n",
288 (int)*seq_num));
289 goto done;
292 ntstatus = NT_STATUS_OK;
294 done:
295 if (values != NULL)
296 ldap_value_free(values);
297 if (msg != NULL)
298 ldap_msgfree(msg);
299 if (mem_ctx)
300 talloc_destroy(mem_ctx);
302 return ntstatus;
305 /*******************************************************************
306 Run the search by name.
307 ******************************************************************/
309 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
310 const char *user,
311 LDAPMessage ** result,
312 const char **attr)
314 char *filter = NULL;
315 char *escape_user = escape_ldap_string(talloc_tos(), user);
316 int ret = -1;
318 if (!escape_user) {
319 return LDAP_NO_MEMORY;
323 * in the filter expression, replace %u with the real name
324 * so in ldap filter, %u MUST exist :-)
326 filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
327 get_objclass_filter(ldap_state->schema_ver));
328 if (!filter) {
329 TALLOC_FREE(escape_user);
330 return LDAP_NO_MEMORY;
333 * have to use this here because $ is filtered out
334 * in string_sub
337 filter = talloc_all_string_sub(talloc_tos(),
338 filter, "%u", escape_user);
339 TALLOC_FREE(escape_user);
340 if (!filter) {
341 return LDAP_NO_MEMORY;
344 ret = smbldap_search_suffix(ldap_state->smbldap_state,
345 filter, attr, result);
346 TALLOC_FREE(filter);
347 return ret;
350 /*******************************************************************
351 Run the search by SID.
352 ******************************************************************/
354 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
355 const struct dom_sid *sid, LDAPMessage ** result,
356 const char **attr)
358 char *filter = NULL;
359 int rc;
360 fstring sid_string;
362 filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
363 get_userattr_key2string(ldap_state->schema_ver,
364 LDAP_ATTR_USER_SID),
365 sid_to_fstring(sid_string, sid),
366 get_objclass_filter(ldap_state->schema_ver));
367 if (!filter) {
368 return LDAP_NO_MEMORY;
371 rc = smbldap_search_suffix(ldap_state->smbldap_state,
372 filter, attr, result);
374 TALLOC_FREE(filter);
375 return rc;
378 /*******************************************************************
379 Delete complete object or objectclass and attrs from
380 object found in search_result depending on lp_ldap_delete_dn
381 ******************************************************************/
383 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
384 TALLOC_CTX *mem_ctx,
385 LDAPMessage *entry,
386 const char *objectclass,
387 const char **attrs)
389 LDAPMod **mods = NULL;
390 char *name;
391 const char *dn;
392 BerElement *ptr = NULL;
394 dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
395 if (dn == NULL) {
396 return LDAP_NO_MEMORY;
399 if (lp_ldap_delete_dn()) {
400 return smbldap_delete(priv->smbldap_state, dn);
403 /* Ok, delete only the SAM attributes */
405 for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
406 name != NULL;
407 name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
408 const char **attrib;
410 /* We are only allowed to delete the attributes that
411 really exist. */
413 for (attrib = attrs; *attrib != NULL; attrib++) {
414 if (strequal(*attrib, name)) {
415 DEBUG(10, ("ldapsam_delete_entry: deleting "
416 "attribute %s\n", name));
417 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
418 NULL);
421 ldap_memfree(name);
424 if (ptr != NULL) {
425 ber_free(ptr, 0);
428 smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
429 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
431 return smbldap_modify(priv->smbldap_state, dn, mods);
434 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
436 char *temp;
437 struct tm tm;
439 temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
440 get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
441 talloc_tos());
442 if (!temp) {
443 return (time_t) 0;
446 if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
447 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
448 (char*)temp));
449 TALLOC_FREE(temp);
450 return (time_t) 0;
452 TALLOC_FREE(temp);
453 tzset();
454 return timegm(&tm);
457 /**********************************************************************
458 Initialize struct samu from an LDAP query.
459 (Based on init_sam_from_buffer in pdb_tdb.c)
460 *********************************************************************/
462 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
463 struct samu * sampass,
464 LDAPMessage * entry)
466 time_t logon_time,
467 logoff_time,
468 kickoff_time,
469 pass_last_set_time,
470 pass_can_change_time,
471 ldap_entry_time,
472 bad_password_time;
473 char *username = NULL,
474 *domain = NULL,
475 *nt_username = NULL,
476 *fullname = NULL,
477 *homedir = NULL,
478 *dir_drive = NULL,
479 *logon_script = NULL,
480 *profile_path = NULL,
481 *acct_desc = NULL,
482 *workstations = NULL,
483 *munged_dial = NULL;
484 uint32_t user_rid;
485 uint8_t smblmpwd[LM_HASH_LEN],
486 smbntpwd[NT_HASH_LEN];
487 bool use_samba_attrs = True;
488 uint32_t acct_ctrl = 0;
489 uint16_t logon_divs;
490 uint16_t bad_password_count = 0,
491 logon_count = 0;
492 uint32_t hours_len;
493 uint8_t hours[MAX_HOURS_LEN];
494 char *temp = NULL;
495 struct login_cache cache_entry;
496 uint32_t pwHistLen;
497 bool expand_explicit = lp_passdb_expand_explicit();
498 bool ret = false;
499 TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
501 if (!ctx) {
502 return false;
504 if (sampass == NULL || ldap_state == NULL || entry == NULL) {
505 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
506 goto fn_exit;
509 if (priv2ld(ldap_state) == NULL) {
510 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
511 "ldap_struct is NULL!\n"));
512 goto fn_exit;
515 if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
516 entry,
517 "uid",
518 ctx))) {
519 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
520 "this user!\n"));
521 goto fn_exit;
524 DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
526 nt_username = talloc_strdup(ctx, username);
527 if (!nt_username) {
528 goto fn_exit;
531 domain = talloc_strdup(ctx, ldap_state->domain_name);
532 if (!domain) {
533 goto fn_exit;
536 pdb_set_username(sampass, username, PDB_SET);
538 pdb_set_domain(sampass, domain, PDB_DEFAULT);
539 pdb_set_nt_username(sampass, nt_username, PDB_SET);
541 /* deal with different attributes between the schema first */
543 if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
544 if ((temp = smbldap_talloc_single_attribute(
545 ldap_state->smbldap_state->ldap_struct,
546 entry,
547 get_userattr_key2string(ldap_state->schema_ver,
548 LDAP_ATTR_USER_SID),
549 ctx))!=NULL) {
550 pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
552 } else {
553 if ((temp = smbldap_talloc_single_attribute(
554 ldap_state->smbldap_state->ldap_struct,
555 entry,
556 get_userattr_key2string(ldap_state->schema_ver,
557 LDAP_ATTR_USER_RID),
558 ctx))!=NULL) {
559 user_rid = (uint32_t)atol(temp);
560 pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
564 if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
565 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n",
566 get_userattr_key2string(ldap_state->schema_ver,
567 LDAP_ATTR_USER_SID),
568 get_userattr_key2string(ldap_state->schema_ver,
569 LDAP_ATTR_USER_RID),
570 username));
571 return False;
574 temp = smbldap_talloc_single_attribute(
575 ldap_state->smbldap_state->ldap_struct,
576 entry,
577 get_userattr_key2string(ldap_state->schema_ver,
578 LDAP_ATTR_PWD_LAST_SET),
579 ctx);
580 if (temp) {
581 pass_last_set_time = (time_t) atol(temp);
582 pdb_set_pass_last_set_time(sampass,
583 pass_last_set_time, PDB_SET);
586 temp = smbldap_talloc_single_attribute(
587 ldap_state->smbldap_state->ldap_struct,
588 entry,
589 get_userattr_key2string(ldap_state->schema_ver,
590 LDAP_ATTR_LOGON_TIME),
591 ctx);
592 if (temp) {
593 logon_time = (time_t) atol(temp);
594 pdb_set_logon_time(sampass, logon_time, PDB_SET);
597 temp = smbldap_talloc_single_attribute(
598 ldap_state->smbldap_state->ldap_struct,
599 entry,
600 get_userattr_key2string(ldap_state->schema_ver,
601 LDAP_ATTR_LOGOFF_TIME),
602 ctx);
603 if (temp) {
604 logoff_time = (time_t) atol(temp);
605 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
608 temp = smbldap_talloc_single_attribute(
609 ldap_state->smbldap_state->ldap_struct,
610 entry,
611 get_userattr_key2string(ldap_state->schema_ver,
612 LDAP_ATTR_KICKOFF_TIME),
613 ctx);
614 if (temp) {
615 kickoff_time = (time_t) atol(temp);
616 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
619 temp = smbldap_talloc_single_attribute(
620 ldap_state->smbldap_state->ldap_struct,
621 entry,
622 get_userattr_key2string(ldap_state->schema_ver,
623 LDAP_ATTR_PWD_CAN_CHANGE),
624 ctx);
625 if (temp) {
626 pass_can_change_time = (time_t) atol(temp);
627 pdb_set_pass_can_change_time(sampass,
628 pass_can_change_time, PDB_SET);
631 /* recommend that 'gecos' and 'displayName' should refer to the same
632 * attribute OID. userFullName depreciated, only used by Samba
633 * primary rules of LDAP: don't make a new attribute when one is already defined
634 * that fits your needs; using cn then displayName rather than 'userFullName'
637 fullname = smbldap_talloc_single_attribute(
638 ldap_state->smbldap_state->ldap_struct,
639 entry,
640 get_userattr_key2string(ldap_state->schema_ver,
641 LDAP_ATTR_DISPLAY_NAME),
642 ctx);
643 if (fullname) {
644 pdb_set_fullname(sampass, fullname, PDB_SET);
645 } else {
646 fullname = smbldap_talloc_single_attribute(
647 ldap_state->smbldap_state->ldap_struct,
648 entry,
649 get_userattr_key2string(ldap_state->schema_ver,
650 LDAP_ATTR_CN),
651 ctx);
652 if (fullname) {
653 pdb_set_fullname(sampass, fullname, PDB_SET);
657 dir_drive = smbldap_talloc_single_attribute(
658 ldap_state->smbldap_state->ldap_struct,
659 entry,
660 get_userattr_key2string(ldap_state->schema_ver,
661 LDAP_ATTR_HOME_DRIVE),
662 ctx);
663 if (dir_drive) {
664 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
665 } else {
666 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
669 homedir = smbldap_talloc_single_attribute(
670 ldap_state->smbldap_state->ldap_struct,
671 entry,
672 get_userattr_key2string(ldap_state->schema_ver,
673 LDAP_ATTR_HOME_PATH),
674 ctx);
675 if (homedir) {
676 if (expand_explicit) {
677 homedir = talloc_sub_basic(ctx,
678 username,
679 domain,
680 homedir);
681 if (!homedir) {
682 goto fn_exit;
685 pdb_set_homedir(sampass, homedir, PDB_SET);
686 } else {
687 pdb_set_homedir(sampass,
688 talloc_sub_basic(ctx, username, domain,
689 lp_logon_home()),
690 PDB_DEFAULT);
693 logon_script = smbldap_talloc_single_attribute(
694 ldap_state->smbldap_state->ldap_struct,
695 entry,
696 get_userattr_key2string(ldap_state->schema_ver,
697 LDAP_ATTR_LOGON_SCRIPT),
698 ctx);
699 if (logon_script) {
700 if (expand_explicit) {
701 logon_script = talloc_sub_basic(ctx,
702 username,
703 domain,
704 logon_script);
705 if (!logon_script) {
706 goto fn_exit;
709 pdb_set_logon_script(sampass, logon_script, PDB_SET);
710 } else {
711 pdb_set_logon_script(sampass,
712 talloc_sub_basic(ctx, username, domain,
713 lp_logon_script()),
714 PDB_DEFAULT );
717 profile_path = smbldap_talloc_single_attribute(
718 ldap_state->smbldap_state->ldap_struct,
719 entry,
720 get_userattr_key2string(ldap_state->schema_ver,
721 LDAP_ATTR_PROFILE_PATH),
722 ctx);
723 if (profile_path) {
724 if (expand_explicit) {
725 profile_path = talloc_sub_basic(ctx,
726 username,
727 domain,
728 profile_path);
729 if (!profile_path) {
730 goto fn_exit;
733 pdb_set_profile_path(sampass, profile_path, PDB_SET);
734 } else {
735 pdb_set_profile_path(sampass,
736 talloc_sub_basic(ctx, username, domain,
737 lp_logon_path()),
738 PDB_DEFAULT );
741 acct_desc = smbldap_talloc_single_attribute(
742 ldap_state->smbldap_state->ldap_struct,
743 entry,
744 get_userattr_key2string(ldap_state->schema_ver,
745 LDAP_ATTR_DESC),
746 ctx);
747 if (acct_desc) {
748 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
751 workstations = smbldap_talloc_single_attribute(
752 ldap_state->smbldap_state->ldap_struct,
753 entry,
754 get_userattr_key2string(ldap_state->schema_ver,
755 LDAP_ATTR_USER_WKS),
756 ctx);
757 if (workstations) {
758 pdb_set_workstations(sampass, workstations, PDB_SET);
761 munged_dial = smbldap_talloc_single_attribute(
762 ldap_state->smbldap_state->ldap_struct,
763 entry,
764 get_userattr_key2string(ldap_state->schema_ver,
765 LDAP_ATTR_MUNGED_DIAL),
766 ctx);
767 if (munged_dial) {
768 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
771 /* FIXME: hours stuff should be cleaner */
773 logon_divs = 168;
774 hours_len = 21;
775 memset(hours, 0xff, hours_len);
777 if (ldap_state->is_nds_ldap) {
778 char *user_dn;
779 size_t pwd_len;
780 char clear_text_pw[512];
782 /* Make call to Novell eDirectory ldap extension to get clear text password.
783 NOTE: This will only work if we have an SSL connection to eDirectory. */
784 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
785 if (user_dn != NULL) {
786 DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
788 pwd_len = sizeof(clear_text_pw);
789 if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
790 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
791 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
792 TALLOC_FREE(user_dn);
793 return False;
795 ZERO_STRUCT(smblmpwd);
796 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
797 TALLOC_FREE(user_dn);
798 return False;
800 ZERO_STRUCT(smbntpwd);
801 use_samba_attrs = False;
804 TALLOC_FREE(user_dn);
806 } else {
807 DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
811 if (use_samba_attrs) {
812 temp = smbldap_talloc_single_attribute(
813 ldap_state->smbldap_state->ldap_struct,
814 entry,
815 get_userattr_key2string(ldap_state->schema_ver,
816 LDAP_ATTR_LMPW),
817 ctx);
818 if (temp) {
819 pdb_gethexpwd(temp, smblmpwd);
820 memset((char *)temp, '\0', strlen(temp)+1);
821 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
822 goto fn_exit;
824 ZERO_STRUCT(smblmpwd);
827 temp = smbldap_talloc_single_attribute(
828 ldap_state->smbldap_state->ldap_struct,
829 entry,
830 get_userattr_key2string(ldap_state->schema_ver,
831 LDAP_ATTR_NTPW),
832 ctx);
833 if (temp) {
834 pdb_gethexpwd(temp, smbntpwd);
835 memset((char *)temp, '\0', strlen(temp)+1);
836 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
837 goto fn_exit;
839 ZERO_STRUCT(smbntpwd);
843 pwHistLen = 0;
845 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
846 if (pwHistLen > 0){
847 uint8_t *pwhist = NULL;
848 int i;
849 char *history_string = talloc_array(ctx, char,
850 MAX_PW_HISTORY_LEN*64);
852 if (!history_string) {
853 goto fn_exit;
856 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
858 pwhist = talloc_zero_array(ctx, uint8_t,
859 pwHistLen * PW_HISTORY_ENTRY_LEN);
860 if (pwhist == NULL) {
861 DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
862 goto fn_exit;
865 if (smbldap_get_single_attribute(
866 ldap_state->smbldap_state->ldap_struct,
867 entry,
868 get_userattr_key2string(ldap_state->schema_ver,
869 LDAP_ATTR_PWD_HISTORY),
870 history_string,
871 MAX_PW_HISTORY_LEN*64)) {
872 bool hex_failed = false;
873 for (i = 0; i < pwHistLen; i++){
874 /* Get the 16 byte salt. */
875 if (!pdb_gethexpwd(&history_string[i*64],
876 &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
877 hex_failed = true;
878 break;
880 /* Get the 16 byte MD5 hash of salt+passwd. */
881 if (!pdb_gethexpwd(&history_string[(i*64)+32],
882 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
883 PW_HISTORY_SALT_LEN])) {
884 hex_failed = True;
885 break;
888 if (hex_failed) {
889 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
890 username));
891 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
894 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
895 goto fn_exit;
899 temp = smbldap_talloc_single_attribute(
900 ldap_state->smbldap_state->ldap_struct,
901 entry,
902 get_userattr_key2string(ldap_state->schema_ver,
903 LDAP_ATTR_ACB_INFO),
904 ctx);
905 if (temp) {
906 acct_ctrl = pdb_decode_acct_ctrl(temp);
908 if (acct_ctrl == 0) {
909 acct_ctrl |= ACB_NORMAL;
912 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
913 } else {
914 acct_ctrl |= ACB_NORMAL;
917 pdb_set_hours_len(sampass, hours_len, PDB_SET);
918 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
920 temp = smbldap_talloc_single_attribute(
921 ldap_state->smbldap_state->ldap_struct,
922 entry,
923 get_userattr_key2string(ldap_state->schema_ver,
924 LDAP_ATTR_BAD_PASSWORD_COUNT),
925 ctx);
926 if (temp) {
927 bad_password_count = (uint32_t) atol(temp);
928 pdb_set_bad_password_count(sampass,
929 bad_password_count, PDB_SET);
932 temp = smbldap_talloc_single_attribute(
933 ldap_state->smbldap_state->ldap_struct,
934 entry,
935 get_userattr_key2string(ldap_state->schema_ver,
936 LDAP_ATTR_BAD_PASSWORD_TIME),
937 ctx);
938 if (temp) {
939 bad_password_time = (time_t) atol(temp);
940 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
944 temp = smbldap_talloc_single_attribute(
945 ldap_state->smbldap_state->ldap_struct,
946 entry,
947 get_userattr_key2string(ldap_state->schema_ver,
948 LDAP_ATTR_LOGON_COUNT),
949 ctx);
950 if (temp) {
951 logon_count = (uint32_t) atol(temp);
952 pdb_set_logon_count(sampass, logon_count, PDB_SET);
955 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
957 temp = smbldap_talloc_single_attribute(
958 ldap_state->smbldap_state->ldap_struct,
959 entry,
960 get_userattr_key2string(ldap_state->schema_ver,
961 LDAP_ATTR_LOGON_HOURS),
962 ctx);
963 if (temp) {
964 pdb_gethexhours(temp, hours);
965 memset((char *)temp, '\0', strlen(temp) +1);
966 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
967 ZERO_STRUCT(hours);
970 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
971 struct passwd unix_pw;
972 bool have_uid = false;
973 bool have_gid = false;
974 struct dom_sid mapped_gsid;
975 const struct dom_sid *primary_gsid;
976 struct unixid id;
978 ZERO_STRUCT(unix_pw);
980 unix_pw.pw_name = username;
981 unix_pw.pw_passwd = discard_const_p(char, "x");
983 temp = smbldap_talloc_single_attribute(
984 priv2ld(ldap_state),
985 entry,
986 "uidNumber",
987 ctx);
988 if (temp) {
989 /* We've got a uid, feed the cache */
990 unix_pw.pw_uid = strtoul(temp, NULL, 10);
991 have_uid = true;
993 temp = smbldap_talloc_single_attribute(
994 priv2ld(ldap_state),
995 entry,
996 "gidNumber",
997 ctx);
998 if (temp) {
999 /* We've got a uid, feed the cache */
1000 unix_pw.pw_gid = strtoul(temp, NULL, 10);
1001 have_gid = true;
1003 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1004 priv2ld(ldap_state),
1005 entry,
1006 "gecos",
1007 ctx);
1008 if (unix_pw.pw_gecos) {
1009 unix_pw.pw_gecos = fullname;
1011 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1012 priv2ld(ldap_state),
1013 entry,
1014 "homeDirectory",
1015 ctx);
1016 if (unix_pw.pw_dir) {
1017 unix_pw.pw_dir = discard_const_p(char, "");
1019 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1020 priv2ld(ldap_state),
1021 entry,
1022 "loginShell",
1023 ctx);
1024 if (unix_pw.pw_shell) {
1025 unix_pw.pw_shell = discard_const_p(char, "");
1028 if (have_uid && have_gid) {
1029 sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1030 } else {
1031 sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1034 if (sampass->unix_pw == NULL) {
1035 DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1036 pdb_get_username(sampass)));
1037 goto fn_exit;
1040 id.id = sampass->unix_pw->pw_uid;
1041 id.type = ID_TYPE_UID;
1043 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1045 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1046 primary_gsid = pdb_get_group_sid(sampass);
1047 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1048 id.id = sampass->unix_pw->pw_gid;
1049 id.type = ID_TYPE_GID;
1051 idmap_cache_set_sid2unixid(primary_gsid, &id);
1055 /* check the timestamp of the cache vs ldap entry */
1056 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1057 entry))) {
1058 ret = true;
1059 goto fn_exit;
1062 /* see if we have newer updates */
1063 if (!login_cache_read(sampass, &cache_entry)) {
1064 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1065 (unsigned int)pdb_get_bad_password_count(sampass),
1066 (unsigned int)pdb_get_bad_password_time(sampass)));
1067 ret = true;
1068 goto fn_exit;
1071 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1072 (unsigned int)ldap_entry_time,
1073 (unsigned int)cache_entry.entry_timestamp,
1074 (unsigned int)cache_entry.bad_password_time));
1076 if (ldap_entry_time > cache_entry.entry_timestamp) {
1077 /* cache is older than directory , so
1078 we need to delete the entry but allow the
1079 fields to be written out */
1080 login_cache_delentry(sampass);
1081 } else {
1082 /* read cache in */
1083 pdb_set_acct_ctrl(sampass,
1084 pdb_get_acct_ctrl(sampass) |
1085 (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1086 PDB_SET);
1087 pdb_set_bad_password_count(sampass,
1088 cache_entry.bad_password_count,
1089 PDB_SET);
1090 pdb_set_bad_password_time(sampass,
1091 cache_entry.bad_password_time,
1092 PDB_SET);
1095 ret = true;
1097 fn_exit:
1099 TALLOC_FREE(ctx);
1100 return ret;
1103 /**********************************************************************
1104 Initialize the ldap db from a struct samu. Called on update.
1105 (Based on init_buffer_from_sam in pdb_tdb.c)
1106 *********************************************************************/
1108 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1109 LDAPMessage *existing,
1110 LDAPMod *** mods, struct samu * sampass,
1111 bool (*need_update)(const struct samu *,
1112 enum pdb_elements))
1114 char *temp = NULL;
1116 if (mods == NULL || sampass == NULL) {
1117 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1118 return False;
1121 *mods = NULL;
1124 * took out adding "objectclass: sambaAccount"
1125 * do this on a per-mod basis
1127 if (need_update(sampass, PDB_USERNAME)) {
1128 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1129 "uid", pdb_get_username(sampass));
1130 if (ldap_state->is_nds_ldap) {
1131 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1132 "cn", pdb_get_username(sampass));
1133 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1134 "sn", pdb_get_username(sampass));
1138 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1140 /* only update the RID if we actually need to */
1141 if (need_update(sampass, PDB_USERSID)) {
1142 fstring sid_string;
1143 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1145 switch ( ldap_state->schema_ver ) {
1146 case SCHEMAVER_SAMBASAMACCOUNT:
1147 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1148 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1149 sid_to_fstring(sid_string, user_sid));
1150 break;
1152 default:
1153 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1154 break;
1158 /* we don't need to store the primary group RID - so leaving it
1159 'free' to hang off the unix primary group makes life easier */
1161 if (need_update(sampass, PDB_GROUPSID)) {
1162 fstring sid_string;
1163 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1165 switch ( ldap_state->schema_ver ) {
1166 case SCHEMAVER_SAMBASAMACCOUNT:
1167 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1168 get_userattr_key2string(ldap_state->schema_ver,
1169 LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1170 break;
1172 default:
1173 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1174 break;
1179 /* displayName, cn, and gecos should all be the same
1180 * most easily accomplished by giving them the same OID
1181 * gecos isn't set here b/c it should be handled by the
1182 * add-user script
1183 * We change displayName only and fall back to cn if
1184 * it does not exist.
1187 if (need_update(sampass, PDB_FULLNAME))
1188 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1189 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME),
1190 pdb_get_fullname(sampass));
1192 if (need_update(sampass, PDB_ACCTDESC))
1193 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1194 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC),
1195 pdb_get_acct_desc(sampass));
1197 if (need_update(sampass, PDB_WORKSTATIONS))
1198 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1199 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS),
1200 pdb_get_workstations(sampass));
1202 if (need_update(sampass, PDB_MUNGEDDIAL))
1203 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1204 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL),
1205 pdb_get_munged_dial(sampass));
1207 if (need_update(sampass, PDB_SMBHOME))
1208 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1209 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH),
1210 pdb_get_homedir(sampass));
1212 if (need_update(sampass, PDB_DRIVE))
1213 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1214 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE),
1215 pdb_get_dir_drive(sampass));
1217 if (need_update(sampass, PDB_LOGONSCRIPT))
1218 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1219 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT),
1220 pdb_get_logon_script(sampass));
1222 if (need_update(sampass, PDB_PROFILE))
1223 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1224 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH),
1225 pdb_get_profile_path(sampass));
1227 if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1228 return false;
1230 if (need_update(sampass, PDB_LOGONTIME))
1231 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1232 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1233 SAFE_FREE(temp);
1235 if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1236 return false;
1238 if (need_update(sampass, PDB_LOGOFFTIME))
1239 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1240 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1241 SAFE_FREE(temp);
1243 if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1244 return false;
1246 if (need_update(sampass, PDB_KICKOFFTIME))
1247 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1248 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1249 SAFE_FREE(temp);
1251 if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1252 return false;
1254 if (need_update(sampass, PDB_CANCHANGETIME))
1255 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1256 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1257 SAFE_FREE(temp);
1259 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1260 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1262 if (need_update(sampass, PDB_LMPASSWD)) {
1263 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1264 if (lm_pw) {
1265 char pwstr[34];
1266 pdb_sethexpwd(pwstr, lm_pw,
1267 pdb_get_acct_ctrl(sampass));
1268 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1269 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1270 pwstr);
1271 } else {
1272 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1273 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1274 NULL);
1277 if (need_update(sampass, PDB_NTPASSWD)) {
1278 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1279 if (nt_pw) {
1280 char pwstr[34];
1281 pdb_sethexpwd(pwstr, nt_pw,
1282 pdb_get_acct_ctrl(sampass));
1283 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1284 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1285 pwstr);
1286 } else {
1287 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1288 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1289 NULL);
1293 if (need_update(sampass, PDB_PWHISTORY)) {
1294 char *pwstr = NULL;
1295 uint32_t pwHistLen = 0;
1296 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1298 pwstr = SMB_MALLOC_ARRAY(char, 1024);
1299 if (!pwstr) {
1300 return false;
1302 if (pwHistLen == 0) {
1303 /* Remove any password history from the LDAP store. */
1304 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1305 pwstr[64] = '\0';
1306 } else {
1307 int i;
1308 uint32_t currHistLen = 0;
1309 const uint8_t *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1310 if (pwhist != NULL) {
1311 /* We can only store (1024-1/64 password history entries. */
1312 pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1313 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1314 /* Store the salt. */
1315 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1316 /* Followed by the md5 hash of salt + md4 hash */
1317 pdb_sethexpwd(&pwstr[(i*64)+32],
1318 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1319 DEBUG(100, ("pwstr=%s\n", pwstr));
1323 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1324 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1325 pwstr);
1326 SAFE_FREE(pwstr);
1329 if (need_update(sampass, PDB_PASSLASTSET)) {
1330 if (asprintf(&temp, "%li",
1331 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1332 return false;
1334 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1335 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1336 temp);
1337 SAFE_FREE(temp);
1341 if (need_update(sampass, PDB_HOURS)) {
1342 const uint8_t *hours = pdb_get_hours(sampass);
1343 if (hours) {
1344 char hourstr[44];
1345 pdb_sethexhours(hourstr, hours);
1346 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1347 existing,
1348 mods,
1349 get_userattr_key2string(ldap_state->schema_ver,
1350 LDAP_ATTR_LOGON_HOURS),
1351 hourstr);
1355 if (need_update(sampass, PDB_ACCTCTRL))
1356 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1357 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1358 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1360 /* password lockout cache:
1361 - If we are now autolocking or clearing, we write to ldap
1362 - If we are clearing, we delete the cache entry
1363 - If the count is > 0, we update the cache
1365 This even means when autolocking, we cache, just in case the
1366 update doesn't work, and we have to cache the autolock flag */
1368 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1369 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1370 uint16_t badcount = pdb_get_bad_password_count(sampass);
1371 time_t badtime = pdb_get_bad_password_time(sampass);
1372 uint32_t pol;
1373 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1375 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1376 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1378 if ((badcount >= pol) || (badcount == 0)) {
1379 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1380 (unsigned int)badcount, (unsigned int)badtime));
1381 if (asprintf(&temp, "%li", (long)badcount) < 0) {
1382 return false;
1384 smbldap_make_mod(
1385 ldap_state->smbldap_state->ldap_struct,
1386 existing, mods,
1387 get_userattr_key2string(
1388 ldap_state->schema_ver,
1389 LDAP_ATTR_BAD_PASSWORD_COUNT),
1390 temp);
1391 SAFE_FREE(temp);
1393 if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1394 return false;
1396 smbldap_make_mod(
1397 ldap_state->smbldap_state->ldap_struct,
1398 existing, mods,
1399 get_userattr_key2string(
1400 ldap_state->schema_ver,
1401 LDAP_ATTR_BAD_PASSWORD_TIME),
1402 temp);
1403 SAFE_FREE(temp);
1405 if (badcount == 0) {
1406 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1407 login_cache_delentry(sampass);
1408 } else {
1409 struct login_cache cache_entry;
1411 cache_entry.entry_timestamp = time(NULL);
1412 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1413 cache_entry.bad_password_count = badcount;
1414 cache_entry.bad_password_time = badtime;
1416 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1417 login_cache_write(sampass, &cache_entry);
1421 return True;
1424 /**********************************************************************
1425 End enumeration of the LDAP password list.
1426 *********************************************************************/
1428 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1430 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1431 if (ldap_state->result) {
1432 ldap_msgfree(ldap_state->result);
1433 ldap_state->result = NULL;
1437 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1438 const char *new_attr)
1440 int i;
1442 if (new_attr == NULL) {
1443 return;
1446 for (i=0; (*attr_list)[i] != NULL; i++) {
1450 (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1451 const char *, i+2);
1452 SMB_ASSERT((*attr_list) != NULL);
1453 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1454 (*attr_list)[i+1] = NULL;
1457 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1458 const char ***attr_list)
1460 append_attr(mem_ctx, attr_list, "uidNumber");
1461 append_attr(mem_ctx, attr_list, "gidNumber");
1462 append_attr(mem_ctx, attr_list, "homeDirectory");
1463 append_attr(mem_ctx, attr_list, "loginShell");
1464 append_attr(mem_ctx, attr_list, "gecos");
1467 /**********************************************************************
1468 Get struct samu entry from LDAP by username.
1469 *********************************************************************/
1471 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1473 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1474 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1475 LDAPMessage *result = NULL;
1476 LDAPMessage *entry = NULL;
1477 int count;
1478 const char ** attr_list;
1479 int rc;
1481 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1482 append_attr(user, &attr_list,
1483 get_userattr_key2string(ldap_state->schema_ver,
1484 LDAP_ATTR_MOD_TIMESTAMP));
1485 ldapsam_add_unix_attributes(user, &attr_list);
1486 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1487 attr_list);
1488 TALLOC_FREE( attr_list );
1490 if ( rc != LDAP_SUCCESS )
1491 return NT_STATUS_NO_SUCH_USER;
1493 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1495 if (count < 1) {
1496 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1497 ldap_msgfree(result);
1498 return NT_STATUS_NO_SUCH_USER;
1499 } else if (count > 1) {
1500 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1501 ldap_msgfree(result);
1502 return NT_STATUS_NO_SUCH_USER;
1505 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1506 if (entry) {
1507 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1508 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1509 ldap_msgfree(result);
1510 return NT_STATUS_NO_SUCH_USER;
1512 pdb_set_backend_private_data(user, result, NULL,
1513 my_methods, PDB_CHANGED);
1514 smbldap_talloc_autofree_ldapmsg(user, result);
1515 ret = NT_STATUS_OK;
1516 } else {
1517 ldap_msgfree(result);
1519 return ret;
1522 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1523 const struct dom_sid *sid, LDAPMessage **result)
1525 int rc = -1;
1526 const char ** attr_list;
1528 switch ( ldap_state->schema_ver ) {
1529 case SCHEMAVER_SAMBASAMACCOUNT: {
1530 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1531 if (tmp_ctx == NULL) {
1532 return LDAP_NO_MEMORY;
1535 attr_list = get_userattr_list(tmp_ctx,
1536 ldap_state->schema_ver);
1537 append_attr(tmp_ctx, &attr_list,
1538 get_userattr_key2string(
1539 ldap_state->schema_ver,
1540 LDAP_ATTR_MOD_TIMESTAMP));
1541 ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1542 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1543 result, attr_list);
1544 TALLOC_FREE(tmp_ctx);
1546 if ( rc != LDAP_SUCCESS )
1547 return rc;
1548 break;
1551 default:
1552 DEBUG(0,("Invalid schema version specified\n"));
1553 break;
1555 return rc;
1558 /**********************************************************************
1559 Get struct samu entry from LDAP by SID.
1560 *********************************************************************/
1562 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1564 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1565 LDAPMessage *result = NULL;
1566 LDAPMessage *entry = NULL;
1567 int count;
1568 int rc;
1570 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1571 sid, &result);
1572 if (rc != LDAP_SUCCESS)
1573 return NT_STATUS_NO_SUCH_USER;
1575 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1577 if (count < 1) {
1578 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1579 "count=%d\n", sid_string_dbg(sid), count));
1580 ldap_msgfree(result);
1581 return NT_STATUS_NO_SUCH_USER;
1582 } else if (count > 1) {
1583 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1584 "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1585 count));
1586 ldap_msgfree(result);
1587 return NT_STATUS_NO_SUCH_USER;
1590 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1591 if (!entry) {
1592 ldap_msgfree(result);
1593 return NT_STATUS_NO_SUCH_USER;
1596 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1597 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1598 ldap_msgfree(result);
1599 return NT_STATUS_NO_SUCH_USER;
1602 pdb_set_backend_private_data(user, result, NULL,
1603 my_methods, PDB_CHANGED);
1604 smbldap_talloc_autofree_ldapmsg(user, result);
1605 return NT_STATUS_OK;
1608 /********************************************************************
1609 Do the actual modification - also change a plaintext passord if
1610 it it set.
1611 **********************************************************************/
1613 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1614 struct samu *newpwd, char *dn,
1615 LDAPMod **mods, int ldap_op,
1616 bool (*need_update)(const struct samu *, enum pdb_elements))
1618 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1619 int rc;
1621 if (!newpwd || !dn) {
1622 return NT_STATUS_INVALID_PARAMETER;
1625 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1626 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1627 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1628 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1629 BerElement *ber;
1630 struct berval *bv;
1631 char *retoid = NULL;
1632 struct berval *retdata = NULL;
1633 char *utf8_password;
1634 char *utf8_dn;
1635 size_t converted_size;
1636 int ret;
1638 if (!ldap_state->is_nds_ldap) {
1640 if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct,
1641 LDAP_EXOP_MODIFY_PASSWD)) {
1642 DEBUG(2, ("ldap password change requested, but LDAP "
1643 "server does not support it -- ignoring\n"));
1644 return NT_STATUS_OK;
1648 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1649 pdb_get_plaintext_passwd(newpwd),
1650 &converted_size))
1652 return NT_STATUS_NO_MEMORY;
1655 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1656 TALLOC_FREE(utf8_password);
1657 return NT_STATUS_NO_MEMORY;
1660 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1661 DEBUG(0,("ber_alloc_t returns NULL\n"));
1662 TALLOC_FREE(utf8_password);
1663 TALLOC_FREE(utf8_dn);
1664 return NT_STATUS_UNSUCCESSFUL;
1667 if ((ber_printf (ber, "{") < 0) ||
1668 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1669 utf8_dn) < 0)) {
1670 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1671 "value <0\n"));
1672 ber_free(ber,1);
1673 TALLOC_FREE(utf8_dn);
1674 TALLOC_FREE(utf8_password);
1675 return NT_STATUS_UNSUCCESSFUL;
1678 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1679 ret = ber_printf(ber, "ts}",
1680 LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1681 utf8_password);
1682 } else {
1683 ret = ber_printf(ber, "}");
1686 if (ret < 0) {
1687 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1688 "value <0\n"));
1689 ber_free(ber,1);
1690 TALLOC_FREE(utf8_dn);
1691 TALLOC_FREE(utf8_password);
1692 return NT_STATUS_UNSUCCESSFUL;
1695 if ((rc = ber_flatten (ber, &bv))<0) {
1696 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1697 ber_free(ber,1);
1698 TALLOC_FREE(utf8_dn);
1699 TALLOC_FREE(utf8_password);
1700 return NT_STATUS_UNSUCCESSFUL;
1703 TALLOC_FREE(utf8_dn);
1704 TALLOC_FREE(utf8_password);
1705 ber_free(ber, 1);
1707 if (!ldap_state->is_nds_ldap) {
1708 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1709 LDAP_EXOP_MODIFY_PASSWD,
1710 bv, NULL, NULL, &retoid,
1711 &retdata);
1712 } else {
1713 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1714 pdb_get_plaintext_passwd(newpwd));
1716 if (rc != LDAP_SUCCESS) {
1717 char *ld_error = NULL;
1719 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1720 DEBUG(3, ("Could not set userPassword "
1721 "attribute due to an objectClass "
1722 "violation -- ignoring\n"));
1723 ber_bvfree(bv);
1724 return NT_STATUS_OK;
1727 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1728 &ld_error);
1729 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1730 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1731 SAFE_FREE(ld_error);
1732 ber_bvfree(bv);
1733 #if defined(LDAP_CONSTRAINT_VIOLATION)
1734 if (rc == LDAP_CONSTRAINT_VIOLATION)
1735 return NT_STATUS_PASSWORD_RESTRICTION;
1736 #endif
1737 return NT_STATUS_UNSUCCESSFUL;
1738 } else {
1739 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1740 #ifdef DEBUG_PASSWORD
1741 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1742 #endif
1743 if (retdata)
1744 ber_bvfree(retdata);
1745 if (retoid)
1746 ldap_memfree(retoid);
1748 ber_bvfree(bv);
1751 if (!mods) {
1752 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1753 /* may be password change below however */
1754 } else {
1755 switch(ldap_op) {
1756 case LDAP_MOD_ADD:
1757 if (ldap_state->is_nds_ldap) {
1758 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1759 "objectclass",
1760 "inetOrgPerson");
1761 } else {
1762 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1763 "objectclass",
1764 LDAP_OBJ_ACCOUNT);
1766 rc = smbldap_add(ldap_state->smbldap_state,
1767 dn, mods);
1768 break;
1769 case LDAP_MOD_REPLACE:
1770 rc = smbldap_modify(ldap_state->smbldap_state,
1771 dn ,mods);
1772 break;
1773 default:
1774 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1775 ldap_op));
1776 return NT_STATUS_INVALID_PARAMETER;
1779 if (rc!=LDAP_SUCCESS) {
1780 return NT_STATUS_UNSUCCESSFUL;
1784 return NT_STATUS_OK;
1787 /**********************************************************************
1788 Delete entry from LDAP for username.
1789 *********************************************************************/
1791 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1792 struct samu * sam_acct)
1794 struct ldapsam_privates *priv =
1795 (struct ldapsam_privates *)my_methods->private_data;
1796 const char *sname;
1797 int rc;
1798 LDAPMessage *msg, *entry;
1799 NTSTATUS result = NT_STATUS_NO_MEMORY;
1800 const char **attr_list;
1801 TALLOC_CTX *mem_ctx;
1803 if (!sam_acct) {
1804 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1805 return NT_STATUS_INVALID_PARAMETER;
1808 sname = pdb_get_username(sam_acct);
1810 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1811 "LDAP.\n", sname));
1813 mem_ctx = talloc_new(NULL);
1814 if (mem_ctx == NULL) {
1815 DEBUG(0, ("talloc_new failed\n"));
1816 goto done;
1819 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1820 if (attr_list == NULL) {
1821 goto done;
1824 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1826 if ((rc != LDAP_SUCCESS) ||
1827 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1828 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1829 DEBUG(5, ("Could not find user %s\n", sname));
1830 result = NT_STATUS_NO_SUCH_USER;
1831 goto done;
1834 rc = ldapsam_delete_entry(
1835 priv, mem_ctx, entry,
1836 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1837 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1838 attr_list);
1840 result = (rc == LDAP_SUCCESS) ?
1841 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1843 done:
1844 TALLOC_FREE(mem_ctx);
1845 return result;
1848 /**********************************************************************
1849 Update struct samu.
1850 *********************************************************************/
1852 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1854 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1855 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1856 int rc = 0;
1857 char *dn;
1858 LDAPMessage *result = NULL;
1859 LDAPMessage *entry = NULL;
1860 LDAPMod **mods = NULL;
1861 const char **attr_list;
1863 result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1864 if (!result) {
1865 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1866 if (pdb_get_username(newpwd) == NULL) {
1867 return NT_STATUS_INVALID_PARAMETER;
1869 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1870 TALLOC_FREE( attr_list );
1871 if (rc != LDAP_SUCCESS) {
1872 return NT_STATUS_UNSUCCESSFUL;
1874 pdb_set_backend_private_data(newpwd, result, NULL,
1875 my_methods, PDB_CHANGED);
1876 smbldap_talloc_autofree_ldapmsg(newpwd, result);
1879 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1880 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1881 return NT_STATUS_UNSUCCESSFUL;
1884 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1885 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1886 if (!dn) {
1887 return NT_STATUS_UNSUCCESSFUL;
1890 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1892 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1893 pdb_element_is_changed)) {
1894 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1895 TALLOC_FREE(dn);
1896 if (mods != NULL)
1897 ldap_mods_free(mods,True);
1898 return NT_STATUS_UNSUCCESSFUL;
1901 if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1902 && (mods == NULL)) {
1903 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1904 pdb_get_username(newpwd)));
1905 TALLOC_FREE(dn);
1906 return NT_STATUS_OK;
1909 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1911 if (mods != NULL) {
1912 ldap_mods_free(mods,True);
1915 TALLOC_FREE(dn);
1918 * We need to set the backend private data to NULL here. For example
1919 * setuserinfo level 25 does a pdb_update_sam_account twice on the
1920 * same one, and with the explicit delete / add logic for attribute
1921 * values the second time we would use the wrong "old" value which
1922 * does not exist in LDAP anymore. Thus the LDAP server would refuse
1923 * the update.
1924 * The existing LDAPMessage is still being auto-freed by the
1925 * destructor.
1927 pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1928 PDB_CHANGED);
1930 if (!NT_STATUS_IS_OK(ret)) {
1931 return ret;
1934 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1935 pdb_get_username(newpwd)));
1936 return NT_STATUS_OK;
1939 /***************************************************************************
1940 Renames a struct samu
1941 - The "rename user script" has full responsibility for changing everything
1942 ***************************************************************************/
1944 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1945 TALLOC_CTX *tmp_ctx,
1946 uint32_t group_rid,
1947 uint32_t member_rid);
1949 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1950 TALLOC_CTX *mem_ctx,
1951 struct samu *user,
1952 struct dom_sid **pp_sids,
1953 gid_t **pp_gids,
1954 uint32_t *p_num_groups);
1956 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1957 struct samu *old_acct,
1958 const char *newname)
1960 const char *oldname;
1961 int rc;
1962 char *rename_script = NULL;
1963 fstring oldname_lower, newname_lower;
1965 if (!old_acct) {
1966 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1967 return NT_STATUS_INVALID_PARAMETER;
1969 if (!newname) {
1970 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1971 return NT_STATUS_INVALID_PARAMETER;
1974 oldname = pdb_get_username(old_acct);
1976 /* rename the posix user */
1977 rename_script = lp_rename_user_script(talloc_tos());
1978 if (rename_script == NULL) {
1979 return NT_STATUS_NO_MEMORY;
1982 if (!(*rename_script)) {
1983 TALLOC_FREE(rename_script);
1984 return NT_STATUS_ACCESS_DENIED;
1987 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
1988 oldname, newname));
1990 /* We have to allow the account name to end with a '$'.
1991 Also, follow the semantics in _samr_create_user() and lower case the
1992 posix name but preserve the case in passdb */
1994 fstrcpy( oldname_lower, oldname );
1995 if (!strlower_m( oldname_lower )) {
1996 return NT_STATUS_INVALID_PARAMETER;
1998 fstrcpy( newname_lower, newname );
1999 if (!strlower_m( newname_lower )) {
2000 return NT_STATUS_INVALID_PARAMETER;
2003 rename_script = realloc_string_sub2(rename_script,
2004 "%unew",
2005 newname_lower,
2006 true,
2007 true);
2008 if (!rename_script) {
2009 return NT_STATUS_NO_MEMORY;
2011 rename_script = realloc_string_sub2(rename_script,
2012 "%uold",
2013 oldname_lower,
2014 true,
2015 true);
2016 rc = smbrun(rename_script, NULL);
2018 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2019 rename_script, rc));
2021 TALLOC_FREE(rename_script);
2023 if (rc == 0) {
2024 smb_nscd_flush_user_cache();
2027 if (rc)
2028 return NT_STATUS_UNSUCCESSFUL;
2030 return NT_STATUS_OK;
2033 /**********************************************************************
2034 Add struct samu to LDAP.
2035 *********************************************************************/
2037 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2039 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2040 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2041 int rc;
2042 LDAPMessage *result = NULL;
2043 LDAPMessage *entry = NULL;
2044 LDAPMod **mods = NULL;
2045 int ldap_op = LDAP_MOD_REPLACE;
2046 uint32_t num_result;
2047 const char **attr_list;
2048 char *escape_user = NULL;
2049 const char *username = pdb_get_username(newpwd);
2050 const struct dom_sid *sid = pdb_get_user_sid(newpwd);
2051 char *filter = NULL;
2052 char *dn = NULL;
2053 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2054 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2056 if (!ctx) {
2057 return NT_STATUS_NO_MEMORY;
2060 if (!username || !*username) {
2061 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2062 status = NT_STATUS_INVALID_PARAMETER;
2063 goto fn_exit;
2066 /* free this list after the second search or in case we exit on failure */
2067 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2069 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2071 if (rc != LDAP_SUCCESS) {
2072 goto fn_exit;
2075 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2076 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2077 username));
2078 goto fn_exit;
2080 ldap_msgfree(result);
2081 result = NULL;
2083 if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2084 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2085 sid, &result);
2086 if (rc == LDAP_SUCCESS) {
2087 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2088 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2089 "already in the base, with samba "
2090 "attributes\n", sid_string_dbg(sid)));
2091 goto fn_exit;
2093 ldap_msgfree(result);
2094 result = NULL;
2098 /* does the entry already exist but without a samba attributes?
2099 we need to return the samba attributes here */
2101 escape_user = escape_ldap_string(talloc_tos(), username);
2102 filter = talloc_strdup(attr_list, "(uid=%u)");
2103 if (!filter) {
2104 status = NT_STATUS_NO_MEMORY;
2105 goto fn_exit;
2107 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2108 TALLOC_FREE(escape_user);
2109 if (!filter) {
2110 status = NT_STATUS_NO_MEMORY;
2111 goto fn_exit;
2114 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2115 filter, attr_list, &result);
2116 if ( rc != LDAP_SUCCESS ) {
2117 goto fn_exit;
2120 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2122 if (num_result > 1) {
2123 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2124 goto fn_exit;
2127 /* Check if we need to update an existing entry */
2128 if (num_result == 1) {
2129 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2130 ldap_op = LDAP_MOD_REPLACE;
2131 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2132 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2133 if (!dn) {
2134 status = NT_STATUS_NO_MEMORY;
2135 goto fn_exit;
2138 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2140 /* There might be a SID for this account already - say an idmap entry */
2142 filter = talloc_asprintf(ctx,
2143 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2144 get_userattr_key2string(ldap_state->schema_ver,
2145 LDAP_ATTR_USER_SID),
2146 sid_string_talloc(ctx, sid),
2147 LDAP_OBJ_IDMAP_ENTRY,
2148 LDAP_OBJ_SID_ENTRY);
2149 if (!filter) {
2150 status = NT_STATUS_NO_MEMORY;
2151 goto fn_exit;
2154 /* free old result before doing a new search */
2155 if (result != NULL) {
2156 ldap_msgfree(result);
2157 result = NULL;
2159 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2160 filter, attr_list, &result);
2162 if ( rc != LDAP_SUCCESS ) {
2163 goto fn_exit;
2166 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2168 if (num_result > 1) {
2169 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2170 goto fn_exit;
2173 /* Check if we need to update an existing entry */
2174 if (num_result == 1) {
2176 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2177 ldap_op = LDAP_MOD_REPLACE;
2178 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2179 dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2180 if (!dn) {
2181 status = NT_STATUS_NO_MEMORY;
2182 goto fn_exit;
2187 if (num_result == 0) {
2188 char *escape_username;
2189 /* Check if we need to add an entry */
2190 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2191 ldap_op = LDAP_MOD_ADD;
2193 escape_username = escape_rdn_val_string_alloc(username);
2194 if (!escape_username) {
2195 status = NT_STATUS_NO_MEMORY;
2196 goto fn_exit;
2199 if (username[strlen(username)-1] == '$') {
2200 dn = talloc_asprintf(ctx,
2201 "uid=%s,%s",
2202 escape_username,
2203 lp_ldap_machine_suffix(talloc_tos()));
2204 } else {
2205 dn = talloc_asprintf(ctx,
2206 "uid=%s,%s",
2207 escape_username,
2208 lp_ldap_user_suffix(talloc_tos()));
2211 SAFE_FREE(escape_username);
2212 if (!dn) {
2213 status = NT_STATUS_NO_MEMORY;
2214 goto fn_exit;
2218 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2219 pdb_element_is_set_or_changed)) {
2220 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2221 if (mods != NULL) {
2222 ldap_mods_free(mods, true);
2224 goto fn_exit;
2227 if (mods == NULL) {
2228 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2229 goto fn_exit;
2231 switch ( ldap_state->schema_ver ) {
2232 case SCHEMAVER_SAMBASAMACCOUNT:
2233 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2234 break;
2235 default:
2236 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2237 break;
2240 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2241 if (!NT_STATUS_IS_OK(ret)) {
2242 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2243 pdb_get_username(newpwd),dn));
2244 ldap_mods_free(mods, true);
2245 goto fn_exit;
2248 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2249 ldap_mods_free(mods, true);
2251 status = NT_STATUS_OK;
2253 fn_exit:
2255 TALLOC_FREE(ctx);
2256 if (result) {
2257 ldap_msgfree(result);
2259 return status;
2262 /**********************************************************************
2263 *********************************************************************/
2265 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2266 const char *filter,
2267 LDAPMessage ** result)
2269 int scope = LDAP_SCOPE_SUBTREE;
2270 int rc;
2271 const char **attr_list;
2273 attr_list = get_attr_list(NULL, groupmap_attr_list);
2274 rc = smbldap_search(ldap_state->smbldap_state,
2275 lp_ldap_suffix (talloc_tos()), scope,
2276 filter, attr_list, 0, result);
2277 TALLOC_FREE(attr_list);
2279 return rc;
2282 /**********************************************************************
2283 *********************************************************************/
2285 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2286 GROUP_MAP *map, LDAPMessage *entry)
2288 char *temp = NULL;
2289 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2291 if (ldap_state == NULL || map == NULL || entry == NULL ||
2292 ldap_state->smbldap_state->ldap_struct == NULL) {
2293 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2294 TALLOC_FREE(ctx);
2295 return false;
2298 temp = smbldap_talloc_single_attribute(
2299 ldap_state->smbldap_state->ldap_struct,
2300 entry,
2301 get_attr_key2string(groupmap_attr_list,
2302 LDAP_ATTR_GIDNUMBER),
2303 ctx);
2304 if (!temp) {
2305 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2306 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2307 TALLOC_FREE(ctx);
2308 return false;
2310 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2312 map->gid = (gid_t)atol(temp);
2314 TALLOC_FREE(temp);
2315 temp = smbldap_talloc_single_attribute(
2316 ldap_state->smbldap_state->ldap_struct,
2317 entry,
2318 get_attr_key2string(groupmap_attr_list,
2319 LDAP_ATTR_GROUP_SID),
2320 ctx);
2321 if (!temp) {
2322 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2323 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2324 TALLOC_FREE(ctx);
2325 return false;
2328 if (!string_to_sid(&map->sid, temp)) {
2329 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2330 TALLOC_FREE(ctx);
2331 return false;
2334 TALLOC_FREE(temp);
2335 temp = smbldap_talloc_single_attribute(
2336 ldap_state->smbldap_state->ldap_struct,
2337 entry,
2338 get_attr_key2string(groupmap_attr_list,
2339 LDAP_ATTR_GROUP_TYPE),
2340 ctx);
2341 if (!temp) {
2342 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2343 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2344 TALLOC_FREE(ctx);
2345 return false;
2347 map->sid_name_use = (enum lsa_SidType)atol(temp);
2349 if ((map->sid_name_use < SID_NAME_USER) ||
2350 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2351 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2352 TALLOC_FREE(ctx);
2353 return false;
2356 TALLOC_FREE(temp);
2357 temp = smbldap_talloc_single_attribute(
2358 ldap_state->smbldap_state->ldap_struct,
2359 entry,
2360 get_attr_key2string(groupmap_attr_list,
2361 LDAP_ATTR_DISPLAY_NAME),
2362 ctx);
2363 if (!temp) {
2364 temp = smbldap_talloc_single_attribute(
2365 ldap_state->smbldap_state->ldap_struct,
2366 entry,
2367 get_attr_key2string(groupmap_attr_list,
2368 LDAP_ATTR_CN),
2369 ctx);
2370 if (!temp) {
2371 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2372 for gidNumber(%lu)\n",(unsigned long)map->gid));
2373 TALLOC_FREE(ctx);
2374 return false;
2377 map->nt_name = talloc_strdup(map, temp);
2378 if (!map->nt_name) {
2379 TALLOC_FREE(ctx);
2380 return false;
2383 TALLOC_FREE(temp);
2384 temp = smbldap_talloc_single_attribute(
2385 ldap_state->smbldap_state->ldap_struct,
2386 entry,
2387 get_attr_key2string(groupmap_attr_list,
2388 LDAP_ATTR_DESC),
2389 ctx);
2390 if (!temp) {
2391 temp = talloc_strdup(ctx, "");
2392 if (!temp) {
2393 TALLOC_FREE(ctx);
2394 return false;
2397 map->comment = talloc_strdup(map, temp);
2398 if (!map->comment) {
2399 TALLOC_FREE(ctx);
2400 return false;
2403 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2404 struct unixid id;
2405 id.id = map->gid;
2406 id.type = ID_TYPE_GID;
2408 idmap_cache_set_sid2unixid(&map->sid, &id);
2411 TALLOC_FREE(ctx);
2412 return true;
2415 /**********************************************************************
2416 *********************************************************************/
2418 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2419 const char *filter,
2420 GROUP_MAP *map)
2422 struct ldapsam_privates *ldap_state =
2423 (struct ldapsam_privates *)methods->private_data;
2424 LDAPMessage *result = NULL;
2425 LDAPMessage *entry = NULL;
2426 int count;
2428 if (ldapsam_search_one_group(ldap_state, filter, &result)
2429 != LDAP_SUCCESS) {
2430 return NT_STATUS_NO_SUCH_GROUP;
2433 count = ldap_count_entries(priv2ld(ldap_state), result);
2435 if (count < 1) {
2436 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2437 "%s\n", filter));
2438 ldap_msgfree(result);
2439 return NT_STATUS_NO_SUCH_GROUP;
2442 if (count > 1) {
2443 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2444 "count=%d\n", filter, count));
2445 ldap_msgfree(result);
2446 return NT_STATUS_NO_SUCH_GROUP;
2449 entry = ldap_first_entry(priv2ld(ldap_state), result);
2451 if (!entry) {
2452 ldap_msgfree(result);
2453 return NT_STATUS_UNSUCCESSFUL;
2456 if (!init_group_from_ldap(ldap_state, map, entry)) {
2457 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2458 "group filter %s\n", filter));
2459 ldap_msgfree(result);
2460 return NT_STATUS_NO_SUCH_GROUP;
2463 ldap_msgfree(result);
2464 return NT_STATUS_OK;
2467 /**********************************************************************
2468 *********************************************************************/
2470 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2471 struct dom_sid sid)
2473 char *filter = NULL;
2474 NTSTATUS status;
2475 fstring tmp;
2477 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2478 LDAP_OBJ_GROUPMAP,
2479 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2480 sid_to_fstring(tmp, &sid)) < 0) {
2481 return NT_STATUS_NO_MEMORY;
2484 status = ldapsam_getgroup(methods, filter, map);
2485 SAFE_FREE(filter);
2486 return status;
2489 /**********************************************************************
2490 *********************************************************************/
2492 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2493 gid_t gid)
2495 char *filter = NULL;
2496 NTSTATUS status;
2498 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2499 LDAP_OBJ_GROUPMAP,
2500 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2501 (unsigned long)gid) < 0) {
2502 return NT_STATUS_NO_MEMORY;
2505 status = ldapsam_getgroup(methods, filter, map);
2506 SAFE_FREE(filter);
2507 return status;
2510 /**********************************************************************
2511 *********************************************************************/
2513 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2514 const char *name)
2516 char *filter = NULL;
2517 char *escape_name = escape_ldap_string(talloc_tos(), name);
2518 NTSTATUS status;
2520 if (!escape_name) {
2521 return NT_STATUS_NO_MEMORY;
2524 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2525 LDAP_OBJ_GROUPMAP,
2526 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2527 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2528 escape_name) < 0) {
2529 TALLOC_FREE(escape_name);
2530 return NT_STATUS_NO_MEMORY;
2533 TALLOC_FREE(escape_name);
2534 status = ldapsam_getgroup(methods, filter, map);
2535 SAFE_FREE(filter);
2536 return status;
2539 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2540 LDAPMessage *entry,
2541 const struct dom_sid *domain_sid,
2542 uint32_t *rid)
2544 fstring str;
2545 struct dom_sid sid;
2547 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2548 str, sizeof(str)-1)) {
2549 DEBUG(10, ("Could not find sambaSID attribute\n"));
2550 return False;
2553 if (!string_to_sid(&sid, str)) {
2554 DEBUG(10, ("Could not convert string %s to sid\n", str));
2555 return False;
2558 if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2559 DEBUG(10, ("SID %s is not in expected domain %s\n",
2560 str, sid_string_dbg(domain_sid)));
2561 return False;
2564 if (!sid_peek_rid(&sid, rid)) {
2565 DEBUG(10, ("Could not peek into RID\n"));
2566 return False;
2569 return True;
2572 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2573 TALLOC_CTX *mem_ctx,
2574 const struct dom_sid *group,
2575 uint32_t **pp_member_rids,
2576 size_t *p_num_members)
2578 struct ldapsam_privates *ldap_state =
2579 (struct ldapsam_privates *)methods->private_data;
2580 struct smbldap_state *conn = ldap_state->smbldap_state;
2581 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2582 const char *sid_attrs[] = { "sambaSID", NULL };
2583 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2584 LDAPMessage *result = NULL;
2585 LDAPMessage *entry;
2586 char *filter;
2587 char **values = NULL;
2588 char **memberuid;
2589 char *gidstr;
2590 int rc, count;
2592 *pp_member_rids = NULL;
2593 *p_num_members = 0;
2595 filter = talloc_asprintf(mem_ctx,
2596 "(&(objectClass=%s)"
2597 "(objectClass=%s)"
2598 "(sambaSID=%s))",
2599 LDAP_OBJ_POSIXGROUP,
2600 LDAP_OBJ_GROUPMAP,
2601 sid_string_talloc(mem_ctx, group));
2602 if (filter == NULL) {
2603 ret = NT_STATUS_NO_MEMORY;
2604 goto done;
2607 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2608 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2609 &result);
2611 if (rc != LDAP_SUCCESS)
2612 goto done;
2614 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2616 count = ldap_count_entries(conn->ldap_struct, result);
2618 if (count > 1) {
2619 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2620 sid_string_dbg(group)));
2621 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2622 goto done;
2625 if (count == 0) {
2626 ret = NT_STATUS_NO_SUCH_GROUP;
2627 goto done;
2630 entry = ldap_first_entry(conn->ldap_struct, result);
2631 if (entry == NULL)
2632 goto done;
2634 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2635 if (!gidstr) {
2636 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2637 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2638 goto done;
2641 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2643 if ((values != NULL) && (values[0] != NULL)) {
2645 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2646 if (filter == NULL) {
2647 ret = NT_STATUS_NO_MEMORY;
2648 goto done;
2651 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2652 char *escape_memberuid;
2654 escape_memberuid = escape_ldap_string(talloc_tos(),
2655 *memberuid);
2656 if (escape_memberuid == NULL) {
2657 ret = NT_STATUS_NO_MEMORY;
2658 goto done;
2661 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2662 TALLOC_FREE(escape_memberuid);
2663 if (filter == NULL) {
2664 ret = NT_STATUS_NO_MEMORY;
2665 goto done;
2669 filter = talloc_asprintf_append_buffer(filter, "))");
2670 if (filter == NULL) {
2671 ret = NT_STATUS_NO_MEMORY;
2672 goto done;
2675 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2676 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2677 &result);
2679 if (rc != LDAP_SUCCESS)
2680 goto done;
2682 count = ldap_count_entries(conn->ldap_struct, result);
2683 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2685 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2687 for (entry = ldap_first_entry(conn->ldap_struct, result);
2688 entry != NULL;
2689 entry = ldap_next_entry(conn->ldap_struct, entry))
2691 char *sidstr;
2692 struct dom_sid sid;
2693 uint32_t rid;
2695 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2696 entry, "sambaSID",
2697 mem_ctx);
2698 if (!sidstr) {
2699 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2700 "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2701 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2702 goto done;
2705 if (!string_to_sid(&sid, sidstr))
2706 goto done;
2708 if (!sid_check_is_in_our_sam(&sid)) {
2709 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2710 "in our domain\n"));
2711 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2712 goto done;
2715 sid_peek_rid(&sid, &rid);
2717 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2718 p_num_members)) {
2719 ret = NT_STATUS_NO_MEMORY;
2720 goto done;
2725 filter = talloc_asprintf(mem_ctx,
2726 "(&(objectClass=%s)"
2727 "(gidNumber=%s))",
2728 LDAP_OBJ_SAMBASAMACCOUNT,
2729 gidstr);
2731 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2732 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2733 &result);
2735 if (rc != LDAP_SUCCESS)
2736 goto done;
2738 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2740 for (entry = ldap_first_entry(conn->ldap_struct, result);
2741 entry != NULL;
2742 entry = ldap_next_entry(conn->ldap_struct, entry))
2744 uint32_t rid;
2746 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2747 entry,
2748 get_global_sam_sid(),
2749 &rid)) {
2750 DEBUG(0, ("Severe DB error, %s can't miss the samba SID" "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2751 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2752 goto done;
2755 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2756 p_num_members)) {
2757 ret = NT_STATUS_NO_MEMORY;
2758 goto done;
2762 ret = NT_STATUS_OK;
2764 done:
2766 if (values)
2767 ldap_value_free(values);
2769 return ret;
2772 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2773 TALLOC_CTX *mem_ctx,
2774 struct samu *user,
2775 struct dom_sid **pp_sids,
2776 gid_t **pp_gids,
2777 uint32_t *p_num_groups)
2779 struct ldapsam_privates *ldap_state =
2780 (struct ldapsam_privates *)methods->private_data;
2781 struct smbldap_state *conn = ldap_state->smbldap_state;
2782 char *filter;
2783 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2784 char *escape_name;
2785 int rc, count;
2786 LDAPMessage *result = NULL;
2787 LDAPMessage *entry;
2788 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2789 uint32_t num_sids;
2790 uint32_t num_gids;
2791 char *gidstr;
2792 gid_t primary_gid = -1;
2794 *pp_sids = NULL;
2795 num_sids = 0;
2797 if (pdb_get_username(user) == NULL) {
2798 return NT_STATUS_INVALID_PARAMETER;
2801 escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2802 if (escape_name == NULL)
2803 return NT_STATUS_NO_MEMORY;
2805 if (user->unix_pw) {
2806 primary_gid = user->unix_pw->pw_gid;
2807 } else {
2808 /* retrieve the users primary gid */
2809 filter = talloc_asprintf(mem_ctx,
2810 "(&(objectClass=%s)(uid=%s))",
2811 LDAP_OBJ_SAMBASAMACCOUNT,
2812 escape_name);
2813 if (filter == NULL) {
2814 ret = NT_STATUS_NO_MEMORY;
2815 goto done;
2818 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2819 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2821 if (rc != LDAP_SUCCESS)
2822 goto done;
2824 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2826 count = ldap_count_entries(priv2ld(ldap_state), result);
2828 switch (count) {
2829 case 0:
2830 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2831 ret = NT_STATUS_NO_SUCH_USER;
2832 goto done;
2833 case 1:
2834 entry = ldap_first_entry(priv2ld(ldap_state), result);
2836 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2837 if (!gidstr) {
2838 DEBUG (1, ("Unable to find the member's gid!\n"));
2839 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2840 goto done;
2842 primary_gid = strtoul(gidstr, NULL, 10);
2843 break;
2844 default:
2845 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2846 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2847 goto done;
2851 filter = talloc_asprintf(mem_ctx,
2852 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2853 LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2854 if (filter == NULL) {
2855 ret = NT_STATUS_NO_MEMORY;
2856 goto done;
2859 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2860 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2862 if (rc != LDAP_SUCCESS)
2863 goto done;
2865 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2867 num_gids = 0;
2868 *pp_gids = NULL;
2870 num_sids = 0;
2871 *pp_sids = NULL;
2873 /* We need to add the primary group as the first gid/sid */
2875 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2876 ret = NT_STATUS_NO_MEMORY;
2877 goto done;
2880 /* This sid will be replaced later */
2882 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2883 &num_sids);
2884 if (!NT_STATUS_IS_OK(ret)) {
2885 goto done;
2888 for (entry = ldap_first_entry(conn->ldap_struct, result);
2889 entry != NULL;
2890 entry = ldap_next_entry(conn->ldap_struct, entry))
2892 fstring str;
2893 struct dom_sid sid;
2894 gid_t gid;
2895 char *end;
2897 if (!smbldap_get_single_attribute(conn->ldap_struct,
2898 entry, "sambaSID",
2899 str, sizeof(str)-1))
2900 continue;
2902 if (!string_to_sid(&sid, str))
2903 goto done;
2905 if (!smbldap_get_single_attribute(conn->ldap_struct,
2906 entry, "gidNumber",
2907 str, sizeof(str)-1))
2908 continue;
2910 gid = strtoul(str, &end, 10);
2912 if (PTR_DIFF(end, str) != strlen(str))
2913 goto done;
2915 if (gid == primary_gid) {
2916 sid_copy(&(*pp_sids)[0], &sid);
2917 } else {
2918 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2919 &num_gids)) {
2920 ret = NT_STATUS_NO_MEMORY;
2921 goto done;
2923 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2924 &num_sids);
2925 if (!NT_STATUS_IS_OK(ret)) {
2926 goto done;
2931 if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2932 DEBUG(3, ("primary group of [%s] not found\n",
2933 pdb_get_username(user)));
2934 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2935 goto done;
2938 *p_num_groups = num_sids;
2940 ret = NT_STATUS_OK;
2942 done:
2944 TALLOC_FREE(escape_name);
2945 return ret;
2948 /**********************************************************************
2949 * Augment a posixGroup object with a sambaGroupMapping domgroup
2950 *********************************************************************/
2952 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2953 struct ldapsam_privates *ldap_state,
2954 GROUP_MAP *map)
2956 const char *filter, *dn;
2957 LDAPMessage *msg, *entry;
2958 LDAPMod **mods;
2959 int rc;
2961 filter = talloc_asprintf(mem_ctx,
2962 "(&(objectClass=%s)(gidNumber=%u))",
2963 LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2964 if (filter == NULL) {
2965 return NT_STATUS_NO_MEMORY;
2968 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2969 get_attr_list(mem_ctx, groupmap_attr_list),
2970 &msg);
2971 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
2973 if ((rc != LDAP_SUCCESS) ||
2974 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2975 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2976 return NT_STATUS_NO_SUCH_GROUP;
2979 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2980 if (dn == NULL) {
2981 return NT_STATUS_NO_MEMORY;
2984 mods = NULL;
2985 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2986 LDAP_OBJ_GROUPMAP);
2987 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2988 sid_string_talloc(mem_ctx, &map->sid));
2989 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2990 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2991 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2992 map->nt_name);
2993 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2994 map->comment);
2995 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
2997 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2998 if (rc != LDAP_SUCCESS) {
2999 return NT_STATUS_ACCESS_DENIED;
3002 return NT_STATUS_OK;
3005 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3006 GROUP_MAP *map)
3008 struct ldapsam_privates *ldap_state =
3009 (struct ldapsam_privates *)methods->private_data;
3010 LDAPMessage *msg = NULL;
3011 LDAPMod **mods = NULL;
3012 const char *attrs[] = { NULL };
3013 char *filter;
3015 char *dn;
3016 TALLOC_CTX *mem_ctx;
3017 NTSTATUS result;
3019 struct dom_sid sid;
3020 struct unixid id;
3022 int rc;
3024 mem_ctx = talloc_new(NULL);
3025 if (mem_ctx == NULL) {
3026 DEBUG(0, ("talloc_new failed\n"));
3027 return NT_STATUS_NO_MEMORY;
3030 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3031 sid_string_talloc(mem_ctx, &map->sid));
3032 if (filter == NULL) {
3033 result = NT_STATUS_NO_MEMORY;
3034 goto done;
3037 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3038 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3039 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3041 if ((rc == LDAP_SUCCESS) &&
3042 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3044 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3045 "group mapping entry\n", sid_string_dbg(&map->sid)));
3046 result = NT_STATUS_GROUP_EXISTS;
3047 goto done;
3050 switch (map->sid_name_use) {
3052 case SID_NAME_DOM_GRP:
3053 /* To map a domain group we need to have a posix group
3054 to attach to. */
3055 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3056 goto done;
3057 break;
3059 case SID_NAME_ALIAS:
3060 if (!sid_check_is_in_our_sam(&map->sid)
3061 && !sid_check_is_in_builtin(&map->sid) )
3063 DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3064 sid_string_dbg(&map->sid)));
3065 result = NT_STATUS_INVALID_PARAMETER;
3066 goto done;
3068 break;
3070 default:
3071 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3072 sid_type_lookup(map->sid_name_use)));
3073 result = NT_STATUS_INVALID_PARAMETER;
3074 goto done;
3077 /* Domain groups have been mapped in a separate routine, we have to
3078 * create an alias now */
3080 if (map->gid == -1) {
3081 DEBUG(10, ("Refusing to map gid==-1\n"));
3082 result = NT_STATUS_INVALID_PARAMETER;
3083 goto done;
3086 id.id = map->gid;
3087 id.type = ID_TYPE_GID;
3089 if (pdb_id_to_sid(&id, &sid)) {
3090 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3091 "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3092 result = NT_STATUS_GROUP_EXISTS;
3093 goto done;
3096 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3097 * the best we can get out of LDAP. */
3099 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3100 sid_string_talloc(mem_ctx, &map->sid),
3101 lp_ldap_group_suffix(talloc_tos()));
3102 if (dn == NULL) {
3103 result = NT_STATUS_NO_MEMORY;
3104 goto done;
3107 mods = NULL;
3109 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3110 LDAP_OBJ_SID_ENTRY);
3111 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3112 LDAP_OBJ_GROUPMAP);
3113 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3114 sid_string_talloc(mem_ctx, &map->sid));
3115 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3116 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3117 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3118 map->nt_name);
3119 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3120 map->comment);
3121 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3122 talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3123 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3125 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3127 result = (rc == LDAP_SUCCESS) ?
3128 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3130 done:
3131 TALLOC_FREE(mem_ctx);
3132 return result;
3135 /**********************************************************************
3136 * Update a group mapping entry. We're quite strict about what can be changed:
3137 * Only the description and displayname may be changed. It simply does not
3138 * make any sense to change the SID, gid or the type in a mapping.
3139 *********************************************************************/
3141 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3142 GROUP_MAP *map)
3144 struct ldapsam_privates *ldap_state =
3145 (struct ldapsam_privates *)methods->private_data;
3146 int rc;
3147 const char *filter, *dn;
3148 LDAPMessage *msg = NULL;
3149 LDAPMessage *entry = NULL;
3150 LDAPMod **mods = NULL;
3151 TALLOC_CTX *mem_ctx;
3152 NTSTATUS result;
3154 mem_ctx = talloc_new(NULL);
3155 if (mem_ctx == NULL) {
3156 DEBUG(0, ("talloc_new failed\n"));
3157 return NT_STATUS_NO_MEMORY;
3160 /* Make 100% sure that sid, gid and type are not changed by looking up
3161 * exactly the values we're given in LDAP. */
3163 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3164 "(sambaSid=%s)(gidNumber=%u)"
3165 "(sambaGroupType=%d))",
3166 LDAP_OBJ_GROUPMAP,
3167 sid_string_talloc(mem_ctx, &map->sid),
3168 (unsigned int)map->gid, map->sid_name_use);
3169 if (filter == NULL) {
3170 result = NT_STATUS_NO_MEMORY;
3171 goto done;
3174 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3175 get_attr_list(mem_ctx, groupmap_attr_list),
3176 &msg);
3177 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3179 if ((rc != LDAP_SUCCESS) ||
3180 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3181 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3182 result = NT_STATUS_NO_SUCH_GROUP;
3183 goto done;
3186 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3188 if (dn == NULL) {
3189 result = NT_STATUS_NO_MEMORY;
3190 goto done;
3193 mods = NULL;
3194 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3195 map->nt_name);
3196 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3197 map->comment);
3198 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3200 if (mods == NULL) {
3201 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3202 "nothing to do\n"));
3203 result = NT_STATUS_OK;
3204 goto done;
3207 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3209 if (rc != LDAP_SUCCESS) {
3210 result = NT_STATUS_ACCESS_DENIED;
3211 goto done;
3214 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3215 "group %lu in LDAP\n", (unsigned long)map->gid));
3217 result = NT_STATUS_OK;
3219 done:
3220 TALLOC_FREE(mem_ctx);
3221 return result;
3224 /**********************************************************************
3225 *********************************************************************/
3227 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3228 struct dom_sid sid)
3230 struct ldapsam_privates *priv =
3231 (struct ldapsam_privates *)methods->private_data;
3232 LDAPMessage *msg, *entry;
3233 int rc;
3234 NTSTATUS result;
3235 TALLOC_CTX *mem_ctx;
3236 char *filter;
3238 mem_ctx = talloc_new(NULL);
3239 if (mem_ctx == NULL) {
3240 DEBUG(0, ("talloc_new failed\n"));
3241 return NT_STATUS_NO_MEMORY;
3244 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3245 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3246 sid_string_talloc(mem_ctx, &sid));
3247 if (filter == NULL) {
3248 result = NT_STATUS_NO_MEMORY;
3249 goto done;
3251 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3252 get_attr_list(mem_ctx, groupmap_attr_list),
3253 &msg);
3254 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3256 if ((rc != LDAP_SUCCESS) ||
3257 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3258 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3259 result = NT_STATUS_NO_SUCH_GROUP;
3260 goto done;
3263 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3264 get_attr_list(mem_ctx,
3265 groupmap_attr_list_to_delete));
3267 if ((rc == LDAP_NAMING_VIOLATION) ||
3268 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3269 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3270 const char *attrs[] = { "sambaGroupType", "description",
3271 "displayName", "sambaSIDList",
3272 NULL };
3274 /* Second try. Don't delete the sambaSID attribute, this is
3275 for "old" entries that are tacked on a winbind
3276 sambaIdmapEntry. */
3278 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3279 LDAP_OBJ_GROUPMAP, attrs);
3282 if ((rc == LDAP_NAMING_VIOLATION) ||
3283 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3284 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3285 const char *attrs[] = { "sambaGroupType", "description",
3286 "displayName", "sambaSIDList",
3287 "gidNumber", NULL };
3289 /* Third try. This is a post-3.0.21 alias (containing only
3290 * sambaSidEntry and sambaGroupMapping classes), we also have
3291 * to delete the gidNumber attribute, only the sambaSidEntry
3292 * remains */
3294 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3295 LDAP_OBJ_GROUPMAP, attrs);
3298 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3300 done:
3301 TALLOC_FREE(mem_ctx);
3302 return result;
3305 /**********************************************************************
3306 *********************************************************************/
3308 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3309 bool update)
3311 struct ldapsam_privates *ldap_state =
3312 (struct ldapsam_privates *)my_methods->private_data;
3313 char *filter = NULL;
3314 int rc;
3315 const char **attr_list;
3317 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3318 if (!filter) {
3319 return NT_STATUS_NO_MEMORY;
3321 attr_list = get_attr_list( NULL, groupmap_attr_list );
3322 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3323 LDAP_SCOPE_SUBTREE, filter,
3324 attr_list, 0, &ldap_state->result);
3325 TALLOC_FREE(attr_list);
3327 if (rc != LDAP_SUCCESS) {
3328 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3329 ldap_err2string(rc)));
3330 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3331 lp_ldap_suffix(talloc_tos()), filter));
3332 ldap_msgfree(ldap_state->result);
3333 ldap_state->result = NULL;
3334 TALLOC_FREE(filter);
3335 return NT_STATUS_UNSUCCESSFUL;
3338 TALLOC_FREE(filter);
3340 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3341 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3342 ldap_state->result)));
3344 ldap_state->entry =
3345 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3346 ldap_state->result);
3347 ldap_state->index = 0;
3349 return NT_STATUS_OK;
3352 /**********************************************************************
3353 *********************************************************************/
3355 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3357 ldapsam_endsampwent(my_methods);
3360 /**********************************************************************
3361 *********************************************************************/
3363 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3364 GROUP_MAP *map)
3366 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3367 struct ldapsam_privates *ldap_state =
3368 (struct ldapsam_privates *)my_methods->private_data;
3369 bool bret = False;
3371 while (!bret) {
3372 if (!ldap_state->entry)
3373 return ret;
3375 ldap_state->index++;
3376 bret = init_group_from_ldap(ldap_state, map,
3377 ldap_state->entry);
3379 ldap_state->entry =
3380 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3381 ldap_state->entry);
3384 return NT_STATUS_OK;
3387 /**********************************************************************
3388 *********************************************************************/
3390 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3391 const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3392 GROUP_MAP ***pp_rmap,
3393 size_t *p_num_entries,
3394 bool unix_only)
3396 GROUP_MAP *map = NULL;
3397 size_t entries = 0;
3399 *p_num_entries = 0;
3400 *pp_rmap = NULL;
3402 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3403 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3404 "passdb\n"));
3405 return NT_STATUS_ACCESS_DENIED;
3408 while (true) {
3410 map = talloc_zero(NULL, GROUP_MAP);
3411 if (!map) {
3412 return NT_STATUS_NO_MEMORY;
3415 if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
3416 TALLOC_FREE(map);
3417 break;
3420 if (sid_name_use != SID_NAME_UNKNOWN &&
3421 sid_name_use != map->sid_name_use) {
3422 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3423 "not of the requested type\n",
3424 map->nt_name));
3425 continue;
3427 if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
3428 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3429 "non mapped\n", map->nt_name));
3430 continue;
3433 *pp_rmap = talloc_realloc(NULL, *pp_rmap,
3434 GROUP_MAP *, entries + 1);
3435 if (!(*pp_rmap)) {
3436 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3437 "enlarge group map!\n"));
3438 return NT_STATUS_UNSUCCESSFUL;
3441 (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
3443 entries += 1;
3446 ldapsam_endsamgrent(methods);
3448 *p_num_entries = entries;
3450 return NT_STATUS_OK;
3453 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3454 const struct dom_sid *alias,
3455 const struct dom_sid *member,
3456 int modop)
3458 struct ldapsam_privates *ldap_state =
3459 (struct ldapsam_privates *)methods->private_data;
3460 char *dn = NULL;
3461 LDAPMessage *result = NULL;
3462 LDAPMessage *entry = NULL;
3463 int count;
3464 LDAPMod **mods = NULL;
3465 int rc;
3466 enum lsa_SidType type = SID_NAME_USE_NONE;
3467 fstring tmp;
3469 char *filter = NULL;
3471 if (sid_check_is_in_builtin(alias)) {
3472 type = SID_NAME_ALIAS;
3475 if (sid_check_is_in_our_sam(alias)) {
3476 type = SID_NAME_ALIAS;
3479 if (type == SID_NAME_USE_NONE) {
3480 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3481 sid_string_dbg(alias)));
3482 return NT_STATUS_NO_SUCH_ALIAS;
3485 if (asprintf(&filter,
3486 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3487 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3488 type) < 0) {
3489 return NT_STATUS_NO_MEMORY;
3492 if (ldapsam_search_one_group(ldap_state, filter,
3493 &result) != LDAP_SUCCESS) {
3494 SAFE_FREE(filter);
3495 return NT_STATUS_NO_SUCH_ALIAS;
3498 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3499 result);
3501 if (count < 1) {
3502 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3503 ldap_msgfree(result);
3504 SAFE_FREE(filter);
3505 return NT_STATUS_NO_SUCH_ALIAS;
3508 if (count > 1) {
3509 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3510 "filter %s: count=%d\n", filter, count));
3511 ldap_msgfree(result);
3512 SAFE_FREE(filter);
3513 return NT_STATUS_NO_SUCH_ALIAS;
3516 SAFE_FREE(filter);
3518 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3519 result);
3521 if (!entry) {
3522 ldap_msgfree(result);
3523 return NT_STATUS_UNSUCCESSFUL;
3526 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3527 if (!dn) {
3528 ldap_msgfree(result);
3529 return NT_STATUS_UNSUCCESSFUL;
3532 smbldap_set_mod(&mods, modop,
3533 get_attr_key2string(groupmap_attr_list,
3534 LDAP_ATTR_SID_LIST),
3535 sid_to_fstring(tmp, member));
3537 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3539 ldap_mods_free(mods, True);
3540 ldap_msgfree(result);
3541 TALLOC_FREE(dn);
3543 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3544 return NT_STATUS_MEMBER_IN_ALIAS;
3547 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3548 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3551 if (rc != LDAP_SUCCESS) {
3552 return NT_STATUS_UNSUCCESSFUL;
3555 return NT_STATUS_OK;
3558 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3559 const struct dom_sid *alias,
3560 const struct dom_sid *member)
3562 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3565 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3566 const struct dom_sid *alias,
3567 const struct dom_sid *member)
3569 return ldapsam_modify_aliasmem(methods, alias, member,
3570 LDAP_MOD_DELETE);
3573 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3574 const struct dom_sid *alias,
3575 TALLOC_CTX *mem_ctx,
3576 struct dom_sid **pp_members,
3577 size_t *p_num_members)
3579 struct ldapsam_privates *ldap_state =
3580 (struct ldapsam_privates *)methods->private_data;
3581 LDAPMessage *result = NULL;
3582 LDAPMessage *entry = NULL;
3583 int count;
3584 char **values = NULL;
3585 int i;
3586 char *filter = NULL;
3587 uint32_t num_members = 0;
3588 enum lsa_SidType type = SID_NAME_USE_NONE;
3589 fstring tmp;
3591 *pp_members = NULL;
3592 *p_num_members = 0;
3594 if (sid_check_is_in_builtin(alias)) {
3595 type = SID_NAME_ALIAS;
3598 if (sid_check_is_in_our_sam(alias)) {
3599 type = SID_NAME_ALIAS;
3602 if (type == SID_NAME_USE_NONE) {
3603 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3604 sid_string_dbg(alias)));
3605 return NT_STATUS_NO_SUCH_ALIAS;
3608 if (asprintf(&filter,
3609 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3610 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3611 type) < 0) {
3612 return NT_STATUS_NO_MEMORY;
3615 if (ldapsam_search_one_group(ldap_state, filter,
3616 &result) != LDAP_SUCCESS) {
3617 SAFE_FREE(filter);
3618 return NT_STATUS_NO_SUCH_ALIAS;
3621 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3622 result);
3624 if (count < 1) {
3625 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3626 ldap_msgfree(result);
3627 SAFE_FREE(filter);
3628 return NT_STATUS_NO_SUCH_ALIAS;
3631 if (count > 1) {
3632 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3633 "filter %s: count=%d\n", filter, count));
3634 ldap_msgfree(result);
3635 SAFE_FREE(filter);
3636 return NT_STATUS_NO_SUCH_ALIAS;
3639 SAFE_FREE(filter);
3641 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3642 result);
3644 if (!entry) {
3645 ldap_msgfree(result);
3646 return NT_STATUS_UNSUCCESSFUL;
3649 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3650 entry,
3651 get_attr_key2string(groupmap_attr_list,
3652 LDAP_ATTR_SID_LIST));
3654 if (values == NULL) {
3655 ldap_msgfree(result);
3656 return NT_STATUS_OK;
3659 count = ldap_count_values(values);
3661 for (i=0; i<count; i++) {
3662 struct dom_sid member;
3663 NTSTATUS status;
3665 if (!string_to_sid(&member, values[i]))
3666 continue;
3668 status = add_sid_to_array(mem_ctx, &member, pp_members,
3669 &num_members);
3670 if (!NT_STATUS_IS_OK(status)) {
3671 ldap_value_free(values);
3672 ldap_msgfree(result);
3673 return status;
3677 *p_num_members = num_members;
3678 ldap_value_free(values);
3679 ldap_msgfree(result);
3681 return NT_STATUS_OK;
3684 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3685 TALLOC_CTX *mem_ctx,
3686 const struct dom_sid *domain_sid,
3687 const struct dom_sid *members,
3688 size_t num_members,
3689 uint32_t **pp_alias_rids,
3690 size_t *p_num_alias_rids)
3692 struct ldapsam_privates *ldap_state =
3693 (struct ldapsam_privates *)methods->private_data;
3694 LDAP *ldap_struct;
3696 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3698 LDAPMessage *result = NULL;
3699 LDAPMessage *entry = NULL;
3700 int i;
3701 int rc;
3702 char *filter;
3703 enum lsa_SidType type = SID_NAME_USE_NONE;
3704 bool is_builtin = false;
3705 bool sid_added = false;
3707 *pp_alias_rids = NULL;
3708 *p_num_alias_rids = 0;
3710 if (sid_check_is_builtin(domain_sid)) {
3711 is_builtin = true;
3712 type = SID_NAME_ALIAS;
3715 if (sid_check_is_our_sam(domain_sid)) {
3716 type = SID_NAME_ALIAS;
3719 if (type == SID_NAME_USE_NONE) {
3720 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3721 sid_string_dbg(domain_sid)));
3722 return NT_STATUS_UNSUCCESSFUL;
3725 if (num_members == 0) {
3726 return NT_STATUS_OK;
3729 filter = talloc_asprintf(mem_ctx,
3730 "(&(objectclass=%s)(sambaGroupType=%d)(|",
3731 LDAP_OBJ_GROUPMAP, type);
3733 for (i=0; i<num_members; i++)
3734 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3735 filter,
3736 sid_string_talloc(mem_ctx,
3737 &members[i]));
3739 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3741 if (filter == NULL) {
3742 return NT_STATUS_NO_MEMORY;
3745 if (is_builtin &&
3746 ldap_state->search_cache.filter &&
3747 strcmp(ldap_state->search_cache.filter, filter) == 0) {
3748 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3749 result = ldap_state->search_cache.result;
3750 ldap_state->search_cache.result = NULL;
3751 } else {
3752 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3753 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3754 if (rc != LDAP_SUCCESS) {
3755 return NT_STATUS_UNSUCCESSFUL;
3757 smbldap_talloc_autofree_ldapmsg(filter, result);
3760 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3762 for (entry = ldap_first_entry(ldap_struct, result);
3763 entry != NULL;
3764 entry = ldap_next_entry(ldap_struct, entry))
3766 fstring sid_str;
3767 struct dom_sid sid;
3768 uint32_t rid;
3770 if (!smbldap_get_single_attribute(ldap_struct, entry,
3771 LDAP_ATTRIBUTE_SID,
3772 sid_str,
3773 sizeof(sid_str)-1))
3774 continue;
3776 if (!string_to_sid(&sid, sid_str))
3777 continue;
3779 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3780 continue;
3782 sid_added = true;
3784 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3785 p_num_alias_rids)) {
3786 return NT_STATUS_NO_MEMORY;
3790 if (!is_builtin && !sid_added) {
3791 TALLOC_FREE(ldap_state->search_cache.filter);
3793 * Note: result is a talloc child of filter because of the
3794 * smbldap_talloc_autofree_ldapmsg() usage
3796 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3797 ldap_state->search_cache.result = result;
3800 return NT_STATUS_OK;
3803 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3804 enum pdb_policy_type type,
3805 uint32_t value)
3807 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3808 int rc;
3809 LDAPMod **mods = NULL;
3810 fstring value_string;
3811 const char *policy_attr = NULL;
3813 struct ldapsam_privates *ldap_state =
3814 (struct ldapsam_privates *)methods->private_data;
3816 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3818 if (!ldap_state->domain_dn) {
3819 return NT_STATUS_INVALID_PARAMETER;
3822 policy_attr = get_account_policy_attr(type);
3823 if (policy_attr == NULL) {
3824 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3825 "policy\n"));
3826 return ntstatus;
3829 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3831 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3833 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3834 mods);
3836 ldap_mods_free(mods, True);
3838 if (rc != LDAP_SUCCESS) {
3839 return ntstatus;
3842 if (!cache_account_policy_set(type, value)) {
3843 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3844 "update local tdb cache\n"));
3845 return ntstatus;
3848 return NT_STATUS_OK;
3851 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3852 enum pdb_policy_type type,
3853 uint32_t value)
3855 return ldapsam_set_account_policy_in_ldap(methods, type,
3856 value);
3859 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3860 enum pdb_policy_type type,
3861 uint32_t *value)
3863 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3864 LDAPMessage *result = NULL;
3865 LDAPMessage *entry = NULL;
3866 int count;
3867 int rc;
3868 char **vals = NULL;
3869 char *filter;
3870 const char *policy_attr = NULL;
3872 struct ldapsam_privates *ldap_state =
3873 (struct ldapsam_privates *)methods->private_data;
3875 const char *attrs[2];
3877 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3879 if (!ldap_state->domain_dn) {
3880 return NT_STATUS_INVALID_PARAMETER;
3883 policy_attr = get_account_policy_attr(type);
3884 if (!policy_attr) {
3885 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3886 "policy index: %d\n", type));
3887 return ntstatus;
3890 attrs[0] = policy_attr;
3891 attrs[1] = NULL;
3893 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3894 if (filter == NULL) {
3895 return NT_STATUS_NO_MEMORY;
3897 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3898 LDAP_SCOPE_BASE, filter, attrs, 0,
3899 &result);
3900 TALLOC_FREE(filter);
3901 if (rc != LDAP_SUCCESS) {
3902 return ntstatus;
3905 count = ldap_count_entries(priv2ld(ldap_state), result);
3906 if (count < 1) {
3907 goto out;
3910 entry = ldap_first_entry(priv2ld(ldap_state), result);
3911 if (entry == NULL) {
3912 goto out;
3915 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3916 if (vals == NULL) {
3917 goto out;
3920 *value = (uint32_t)atol(vals[0]);
3922 ntstatus = NT_STATUS_OK;
3924 out:
3925 if (vals)
3926 ldap_value_free(vals);
3927 ldap_msgfree(result);
3929 return ntstatus;
3932 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3934 - if user hasn't decided to use account policies inside LDAP just reuse the
3935 old tdb values
3937 - if there is a valid cache entry, return that
3938 - if there is an LDAP entry, update cache and return
3939 - otherwise set to default, update cache and return
3941 Guenther
3943 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3944 enum pdb_policy_type type,
3945 uint32_t *value)
3947 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3949 if (cache_account_policy_get(type, value)) {
3950 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3951 "cache\n"));
3952 return NT_STATUS_OK;
3955 ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3956 value);
3957 if (NT_STATUS_IS_OK(ntstatus)) {
3958 goto update_cache;
3961 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3962 "ldap\n"));
3964 #if 0
3965 /* should we automagically migrate old tdb value here ? */
3966 if (account_policy_get(type, value))
3967 goto update_ldap;
3969 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3970 "default\n", type));
3971 #endif
3973 if (!account_policy_get_default(type, value)) {
3974 return ntstatus;
3977 /* update_ldap: */
3979 ntstatus = ldapsam_set_account_policy(methods, type, *value);
3980 if (!NT_STATUS_IS_OK(ntstatus)) {
3981 return ntstatus;
3984 update_cache:
3986 if (!cache_account_policy_set(type, *value)) {
3987 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3988 "tdb as a cache\n"));
3989 return NT_STATUS_UNSUCCESSFUL;
3992 return NT_STATUS_OK;
3995 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3996 const struct dom_sid *domain_sid,
3997 int num_rids,
3998 uint32_t *rids,
3999 const char **names,
4000 enum lsa_SidType *attrs)
4002 struct ldapsam_privates *ldap_state =
4003 (struct ldapsam_privates *)methods->private_data;
4004 LDAPMessage *msg = NULL;
4005 LDAPMessage *entry;
4006 char *allsids = NULL;
4007 int i, rc, num_mapped;
4008 NTSTATUS result = NT_STATUS_NO_MEMORY;
4009 TALLOC_CTX *mem_ctx;
4010 LDAP *ld;
4011 bool is_builtin;
4013 mem_ctx = talloc_new(NULL);
4014 if (mem_ctx == NULL) {
4015 DEBUG(0, ("talloc_new failed\n"));
4016 goto done;
4019 if (!sid_check_is_builtin(domain_sid) &&
4020 !sid_check_is_our_sam(domain_sid)) {
4021 result = NT_STATUS_INVALID_PARAMETER;
4022 goto done;
4025 if (num_rids == 0) {
4026 result = NT_STATUS_NONE_MAPPED;
4027 goto done;
4030 for (i=0; i<num_rids; i++)
4031 attrs[i] = SID_NAME_UNKNOWN;
4033 allsids = talloc_strdup(mem_ctx, "");
4034 if (allsids == NULL) {
4035 goto done;
4038 for (i=0; i<num_rids; i++) {
4039 struct dom_sid sid;
4040 sid_compose(&sid, domain_sid, rids[i]);
4041 allsids = talloc_asprintf_append_buffer(
4042 allsids, "(sambaSid=%s)",
4043 sid_string_talloc(mem_ctx, &sid));
4044 if (allsids == NULL) {
4045 goto done;
4049 /* First look for users */
4052 char *filter;
4053 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4055 filter = talloc_asprintf(
4056 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4057 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4059 if (filter == NULL) {
4060 goto done;
4063 rc = smbldap_search(ldap_state->smbldap_state,
4064 lp_ldap_user_suffix(talloc_tos()),
4065 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4066 &msg);
4067 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4070 if (rc != LDAP_SUCCESS)
4071 goto done;
4073 ld = ldap_state->smbldap_state->ldap_struct;
4074 num_mapped = 0;
4076 for (entry = ldap_first_entry(ld, msg);
4077 entry != NULL;
4078 entry = ldap_next_entry(ld, entry)) {
4079 uint32_t rid;
4080 int rid_index;
4081 const char *name;
4083 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4084 &rid)) {
4085 DEBUG(2, ("Could not find sid from ldap entry\n"));
4086 continue;
4089 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4090 names);
4091 if (name == NULL) {
4092 DEBUG(2, ("Could not retrieve uid attribute\n"));
4093 continue;
4096 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4097 if (rid == rids[rid_index])
4098 break;
4101 if (rid_index == num_rids) {
4102 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4103 continue;
4106 attrs[rid_index] = SID_NAME_USER;
4107 names[rid_index] = name;
4108 num_mapped += 1;
4111 if (num_mapped == num_rids) {
4112 /* No need to look for groups anymore -- we're done */
4113 result = NT_STATUS_OK;
4114 goto done;
4117 /* Same game for groups */
4120 char *filter;
4121 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4122 "sambaGroupType", NULL };
4124 filter = talloc_asprintf(
4125 mem_ctx, "(&(objectClass=%s)(|%s))",
4126 LDAP_OBJ_GROUPMAP, allsids);
4127 if (filter == NULL) {
4128 goto done;
4131 rc = smbldap_search(ldap_state->smbldap_state,
4132 lp_ldap_suffix(talloc_tos()),
4133 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4134 &msg);
4135 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4138 if (rc != LDAP_SUCCESS)
4139 goto done;
4141 /* ldap_struct might have changed due to a reconnect */
4143 ld = ldap_state->smbldap_state->ldap_struct;
4145 /* For consistency checks, we already checked we're only domain or builtin */
4147 is_builtin = sid_check_is_builtin(domain_sid);
4149 for (entry = ldap_first_entry(ld, msg);
4150 entry != NULL;
4151 entry = ldap_next_entry(ld, entry))
4153 uint32_t rid;
4154 int rid_index;
4155 const char *attr;
4156 enum lsa_SidType type;
4157 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4159 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4160 mem_ctx);
4161 if (attr == NULL) {
4162 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4163 dn));
4164 continue;
4167 type = (enum lsa_SidType)atol(attr);
4169 /* Consistency checks */
4170 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4171 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4172 (type != SID_NAME_DOM_GRP)))) {
4173 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4176 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4177 &rid)) {
4178 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4179 continue;
4182 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4184 if (attr == NULL) {
4185 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4186 dn));
4187 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4190 if (attr == NULL) {
4191 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4192 dn));
4193 continue;
4196 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4197 if (rid == rids[rid_index])
4198 break;
4201 if (rid_index == num_rids) {
4202 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4203 continue;
4206 attrs[rid_index] = type;
4207 names[rid_index] = attr;
4208 num_mapped += 1;
4211 result = NT_STATUS_NONE_MAPPED;
4213 if (num_mapped > 0)
4214 result = (num_mapped == num_rids) ?
4215 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4216 done:
4217 TALLOC_FREE(mem_ctx);
4218 return result;
4221 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4223 char *filter = NULL;
4224 char *escaped = NULL;
4225 char *result = NULL;
4227 if (asprintf(&filter, "(&%s(objectclass=%s))",
4228 "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4229 goto done;
4232 escaped = escape_ldap_string(talloc_tos(), username);
4233 if (escaped == NULL) goto done;
4235 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4237 done:
4238 SAFE_FREE(filter);
4239 TALLOC_FREE(escaped);
4241 return result;
4244 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4246 int i, num = 0;
4247 va_list ap;
4248 const char **result;
4250 va_start(ap, mem_ctx);
4251 while (va_arg(ap, const char *) != NULL)
4252 num += 1;
4253 va_end(ap);
4255 if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4256 return NULL;
4259 va_start(ap, mem_ctx);
4260 for (i=0; i<num; i++) {
4261 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4262 if (result[i] == NULL) {
4263 talloc_free(result);
4264 va_end(ap);
4265 return NULL;
4268 va_end(ap);
4270 result[num] = NULL;
4271 return result;
4274 struct ldap_search_state {
4275 struct smbldap_state *connection;
4277 uint32_t acct_flags;
4278 uint16_t group_type;
4280 const char *base;
4281 int scope;
4282 const char *filter;
4283 const char **attrs;
4284 int attrsonly;
4285 void *pagedresults_cookie;
4287 LDAPMessage *entries, *current_entry;
4288 bool (*ldap2displayentry)(struct ldap_search_state *state,
4289 TALLOC_CTX *mem_ctx,
4290 LDAP *ld, LDAPMessage *entry,
4291 struct samr_displayentry *result);
4294 static bool ldapsam_search_firstpage(struct pdb_search *search)
4296 struct ldap_search_state *state =
4297 (struct ldap_search_state *)search->private_data;
4298 LDAP *ld;
4299 int rc = LDAP_OPERATIONS_ERROR;
4301 state->entries = NULL;
4303 if (state->connection->paged_results) {
4304 rc = smbldap_search_paged(state->connection, state->base,
4305 state->scope, state->filter,
4306 state->attrs, state->attrsonly,
4307 lp_ldap_page_size(), &state->entries,
4308 &state->pagedresults_cookie);
4311 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4313 if (state->entries != NULL) {
4314 /* Left over from unsuccessful paged attempt */
4315 ldap_msgfree(state->entries);
4316 state->entries = NULL;
4319 rc = smbldap_search(state->connection, state->base,
4320 state->scope, state->filter, state->attrs,
4321 state->attrsonly, &state->entries);
4323 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4324 return False;
4326 /* Ok, the server was lying. It told us it could do paged
4327 * searches when it could not. */
4328 state->connection->paged_results = False;
4331 ld = state->connection->ldap_struct;
4332 if ( ld == NULL) {
4333 DEBUG(5, ("Don't have an LDAP connection right after a "
4334 "search\n"));
4335 return False;
4337 state->current_entry = ldap_first_entry(ld, state->entries);
4339 return True;
4342 static bool ldapsam_search_nextpage(struct pdb_search *search)
4344 struct ldap_search_state *state =
4345 (struct ldap_search_state *)search->private_data;
4346 int rc;
4348 if (!state->connection->paged_results) {
4349 /* There is no next page when there are no paged results */
4350 return False;
4353 rc = smbldap_search_paged(state->connection, state->base,
4354 state->scope, state->filter, state->attrs,
4355 state->attrsonly, lp_ldap_page_size(),
4356 &state->entries,
4357 &state->pagedresults_cookie);
4359 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4360 return False;
4362 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4364 if (state->current_entry == NULL) {
4365 ldap_msgfree(state->entries);
4366 state->entries = NULL;
4367 return false;
4370 return True;
4373 static bool ldapsam_search_next_entry(struct pdb_search *search,
4374 struct samr_displayentry *entry)
4376 struct ldap_search_state *state =
4377 (struct ldap_search_state *)search->private_data;
4378 bool result;
4380 retry:
4381 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4382 return False;
4384 if ((state->entries == NULL) &&
4385 !ldapsam_search_nextpage(search))
4386 return False;
4388 if (state->current_entry == NULL) {
4389 return false;
4392 result = state->ldap2displayentry(state, search,
4393 state->connection->ldap_struct,
4394 state->current_entry, entry);
4396 if (!result) {
4397 char *dn;
4398 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4399 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4400 if (dn != NULL) ldap_memfree(dn);
4403 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4405 if (state->current_entry == NULL) {
4406 ldap_msgfree(state->entries);
4407 state->entries = NULL;
4410 if (!result) goto retry;
4412 return True;
4415 static void ldapsam_search_end(struct pdb_search *search)
4417 struct ldap_search_state *state =
4418 (struct ldap_search_state *)search->private_data;
4419 int rc;
4421 if (state->pagedresults_cookie == NULL)
4422 return;
4424 if (state->entries != NULL)
4425 ldap_msgfree(state->entries);
4427 state->entries = NULL;
4428 state->current_entry = NULL;
4430 if (!state->connection->paged_results)
4431 return;
4433 /* Tell the LDAP server we're not interested in the rest anymore. */
4435 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4436 state->filter, state->attrs,
4437 state->attrsonly, 0, &state->entries,
4438 &state->pagedresults_cookie);
4440 if (rc != LDAP_SUCCESS)
4441 DEBUG(5, ("Could not end search properly\n"));
4443 return;
4446 static bool ldapuser2displayentry(struct ldap_search_state *state,
4447 TALLOC_CTX *mem_ctx,
4448 LDAP *ld, LDAPMessage *entry,
4449 struct samr_displayentry *result)
4451 char **vals;
4452 size_t converted_size;
4453 struct dom_sid sid;
4454 uint32_t acct_flags;
4456 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4457 if ((vals == NULL) || (vals[0] == NULL)) {
4458 acct_flags = ACB_NORMAL;
4459 } else {
4460 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4461 ldap_value_free(vals);
4464 if ((state->acct_flags != 0) &&
4465 ((state->acct_flags & acct_flags) == 0))
4466 return False;
4468 result->acct_flags = acct_flags;
4469 result->account_name = "";
4470 result->fullname = "";
4471 result->description = "";
4473 vals = ldap_get_values(ld, entry, "uid");
4474 if ((vals == NULL) || (vals[0] == NULL)) {
4475 DEBUG(5, ("\"uid\" not found\n"));
4476 return False;
4478 if (!pull_utf8_talloc(mem_ctx,
4479 discard_const_p(char *, &result->account_name),
4480 vals[0], &converted_size))
4482 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4483 strerror(errno)));
4486 ldap_value_free(vals);
4488 vals = ldap_get_values(ld, entry, "displayName");
4489 if ((vals == NULL) || (vals[0] == NULL))
4490 DEBUG(8, ("\"displayName\" not found\n"));
4491 else if (!pull_utf8_talloc(mem_ctx,
4492 discard_const_p(char *, &result->fullname),
4493 vals[0], &converted_size))
4495 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4496 strerror(errno)));
4499 ldap_value_free(vals);
4501 vals = ldap_get_values(ld, entry, "description");
4502 if ((vals == NULL) || (vals[0] == NULL))
4503 DEBUG(8, ("\"description\" not found\n"));
4504 else if (!pull_utf8_talloc(mem_ctx,
4505 discard_const_p(char *, &result->description),
4506 vals[0], &converted_size))
4508 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4509 strerror(errno)));
4512 ldap_value_free(vals);
4514 if ((result->account_name == NULL) ||
4515 (result->fullname == NULL) ||
4516 (result->description == NULL)) {
4517 DEBUG(0, ("talloc failed\n"));
4518 return False;
4521 vals = ldap_get_values(ld, entry, "sambaSid");
4522 if ((vals == NULL) || (vals[0] == NULL)) {
4523 DEBUG(0, ("\"objectSid\" not found\n"));
4524 return False;
4527 if (!string_to_sid(&sid, vals[0])) {
4528 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4529 ldap_value_free(vals);
4530 return False;
4532 ldap_value_free(vals);
4534 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4535 DEBUG(0, ("sid %s does not belong to our domain\n",
4536 sid_string_dbg(&sid)));
4537 return False;
4540 return True;
4544 static bool ldapsam_search_users(struct pdb_methods *methods,
4545 struct pdb_search *search,
4546 uint32_t acct_flags)
4548 struct ldapsam_privates *ldap_state =
4549 (struct ldapsam_privates *)methods->private_data;
4550 struct ldap_search_state *state;
4552 state = talloc(search, struct ldap_search_state);
4553 if (state == NULL) {
4554 DEBUG(0, ("talloc failed\n"));
4555 return False;
4558 state->connection = ldap_state->smbldap_state;
4560 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4561 state->base = lp_ldap_user_suffix(talloc_tos());
4562 else if ((acct_flags != 0) &&
4563 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4564 state->base = lp_ldap_machine_suffix(talloc_tos());
4565 else
4566 state->base = lp_ldap_suffix(talloc_tos());
4568 state->acct_flags = acct_flags;
4569 state->base = talloc_strdup(search, state->base);
4570 state->scope = LDAP_SCOPE_SUBTREE;
4571 state->filter = get_ldap_filter(search, "*");
4572 state->attrs = talloc_attrs(search, "uid", "sambaSid",
4573 "displayName", "description",
4574 "sambaAcctFlags", NULL);
4575 state->attrsonly = 0;
4576 state->pagedresults_cookie = NULL;
4577 state->entries = NULL;
4578 state->ldap2displayentry = ldapuser2displayentry;
4580 if ((state->filter == NULL) || (state->attrs == NULL)) {
4581 DEBUG(0, ("talloc failed\n"));
4582 return False;
4585 search->private_data = state;
4586 search->next_entry = ldapsam_search_next_entry;
4587 search->search_end = ldapsam_search_end;
4589 return ldapsam_search_firstpage(search);
4592 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4593 TALLOC_CTX *mem_ctx,
4594 LDAP *ld, LDAPMessage *entry,
4595 struct samr_displayentry *result)
4597 char **vals;
4598 size_t converted_size;
4599 struct dom_sid sid;
4600 uint16_t group_type;
4602 result->account_name = "";
4603 result->fullname = "";
4604 result->description = "";
4607 vals = ldap_get_values(ld, entry, "sambaGroupType");
4608 if ((vals == NULL) || (vals[0] == NULL)) {
4609 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4610 if (vals != NULL) {
4611 ldap_value_free(vals);
4613 return False;
4616 group_type = atoi(vals[0]);
4618 if ((state->group_type != 0) &&
4619 ((state->group_type != group_type))) {
4620 ldap_value_free(vals);
4621 return False;
4624 ldap_value_free(vals);
4626 /* display name is the NT group name */
4628 vals = ldap_get_values(ld, entry, "displayName");
4629 if ((vals == NULL) || (vals[0] == NULL)) {
4630 DEBUG(8, ("\"displayName\" not found\n"));
4632 /* fallback to the 'cn' attribute */
4633 vals = ldap_get_values(ld, entry, "cn");
4634 if ((vals == NULL) || (vals[0] == NULL)) {
4635 DEBUG(5, ("\"cn\" not found\n"));
4636 return False;
4638 if (!pull_utf8_talloc(mem_ctx,
4639 discard_const_p(char *,
4640 &result->account_name),
4641 vals[0], &converted_size))
4643 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4644 "failed: %s", strerror(errno)));
4647 else if (!pull_utf8_talloc(mem_ctx,
4648 discard_const_p(char *,
4649 &result->account_name),
4650 vals[0], &converted_size))
4652 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4653 strerror(errno)));
4656 ldap_value_free(vals);
4658 vals = ldap_get_values(ld, entry, "description");
4659 if ((vals == NULL) || (vals[0] == NULL))
4660 DEBUG(8, ("\"description\" not found\n"));
4661 else if (!pull_utf8_talloc(mem_ctx,
4662 discard_const_p(char *, &result->description),
4663 vals[0], &converted_size))
4665 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4666 strerror(errno)));
4668 ldap_value_free(vals);
4670 if ((result->account_name == NULL) ||
4671 (result->fullname == NULL) ||
4672 (result->description == NULL)) {
4673 DEBUG(0, ("talloc failed\n"));
4674 return False;
4677 vals = ldap_get_values(ld, entry, "sambaSid");
4678 if ((vals == NULL) || (vals[0] == NULL)) {
4679 DEBUG(0, ("\"objectSid\" not found\n"));
4680 if (vals != NULL) {
4681 ldap_value_free(vals);
4683 return False;
4686 if (!string_to_sid(&sid, vals[0])) {
4687 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4688 return False;
4691 ldap_value_free(vals);
4693 switch (group_type) {
4694 case SID_NAME_DOM_GRP:
4695 case SID_NAME_ALIAS:
4697 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4698 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4700 DEBUG(0, ("%s is not in our domain\n",
4701 sid_string_dbg(&sid)));
4702 return False;
4704 break;
4706 default:
4707 DEBUG(0,("unknown group type: %d\n", group_type));
4708 return False;
4711 result->acct_flags = 0;
4713 return True;
4716 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4717 struct pdb_search *search,
4718 const struct dom_sid *sid,
4719 enum lsa_SidType type)
4721 struct ldapsam_privates *ldap_state =
4722 (struct ldapsam_privates *)methods->private_data;
4723 struct ldap_search_state *state;
4724 fstring tmp;
4726 state = talloc(search, struct ldap_search_state);
4727 if (state == NULL) {
4728 DEBUG(0, ("talloc failed\n"));
4729 return False;
4732 state->connection = ldap_state->smbldap_state;
4734 state->base = lp_ldap_suffix(search);
4735 state->connection = ldap_state->smbldap_state;
4736 state->scope = LDAP_SCOPE_SUBTREE;
4737 state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4738 "(sambaGroupType=%d)(sambaSID=%s*))",
4739 LDAP_OBJ_GROUPMAP,
4740 type, sid_to_fstring(tmp, sid));
4741 state->attrs = talloc_attrs(search, "cn", "sambaSid",
4742 "displayName", "description",
4743 "sambaGroupType", NULL);
4744 state->attrsonly = 0;
4745 state->pagedresults_cookie = NULL;
4746 state->entries = NULL;
4747 state->group_type = type;
4748 state->ldap2displayentry = ldapgroup2displayentry;
4750 if ((state->filter == NULL) || (state->attrs == NULL)) {
4751 DEBUG(0, ("talloc failed\n"));
4752 return False;
4755 search->private_data = state;
4756 search->next_entry = ldapsam_search_next_entry;
4757 search->search_end = ldapsam_search_end;
4759 return ldapsam_search_firstpage(search);
4762 static bool ldapsam_search_groups(struct pdb_methods *methods,
4763 struct pdb_search *search)
4765 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4768 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4769 struct pdb_search *search,
4770 const struct dom_sid *sid)
4772 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4775 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4777 return PDB_CAP_STORE_RIDS;
4780 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4781 uint32_t *rid)
4783 struct smbldap_state *smbldap_state = priv->smbldap_state;
4785 LDAPMessage *result = NULL;
4786 LDAPMessage *entry = NULL;
4787 LDAPMod **mods = NULL;
4788 NTSTATUS status;
4789 char *value;
4790 int rc;
4791 uint32_t nextRid = 0;
4792 const char *dn;
4794 TALLOC_CTX *mem_ctx;
4796 mem_ctx = talloc_new(NULL);
4797 if (mem_ctx == NULL) {
4798 DEBUG(0, ("talloc_new failed\n"));
4799 return NT_STATUS_NO_MEMORY;
4802 status = smbldap_search_domain_info(smbldap_state, &result,
4803 get_global_sam_name(), False);
4804 if (!NT_STATUS_IS_OK(status)) {
4805 DEBUG(3, ("Could not get domain info: %s\n",
4806 nt_errstr(status)));
4807 goto done;
4810 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4812 entry = ldap_first_entry(priv2ld(priv), result);
4813 if (entry == NULL) {
4814 DEBUG(0, ("Could not get domain info entry\n"));
4815 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4816 goto done;
4819 /* Find the largest of the three attributes "sambaNextRid",
4820 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4821 concept of differentiating between user and group rids, and will
4822 use only "sambaNextRid" in the future. But for compatibility
4823 reasons I look if others have chosen different strategies -- VL */
4825 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4826 "sambaNextRid", mem_ctx);
4827 if (value != NULL) {
4828 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4829 nextRid = MAX(nextRid, tmp);
4832 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4833 "sambaNextUserRid", mem_ctx);
4834 if (value != NULL) {
4835 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4836 nextRid = MAX(nextRid, tmp);
4839 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4840 "sambaNextGroupRid", mem_ctx);
4841 if (value != NULL) {
4842 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4843 nextRid = MAX(nextRid, tmp);
4846 if (nextRid == 0) {
4847 nextRid = BASE_RID-1;
4850 nextRid += 1;
4852 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4853 talloc_asprintf(mem_ctx, "%d", nextRid));
4854 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
4856 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4857 status = NT_STATUS_NO_MEMORY;
4858 goto done;
4861 rc = smbldap_modify(smbldap_state, dn, mods);
4863 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4864 * please retry" */
4866 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4868 done:
4869 if (NT_STATUS_IS_OK(status)) {
4870 *rid = nextRid;
4873 TALLOC_FREE(mem_ctx);
4874 return status;
4877 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4879 int i;
4881 for (i=0; i<10; i++) {
4882 NTSTATUS result = ldapsam_get_new_rid(
4883 (struct ldapsam_privates *)methods->private_data, rid);
4884 if (NT_STATUS_IS_OK(result)) {
4885 return result;
4888 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4889 return result;
4892 /* The ldap update failed (maybe a race condition), retry */
4895 /* Tried 10 times, fail. */
4896 return NT_STATUS_ACCESS_DENIED;
4899 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4901 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4902 return NT_STATUS_IS_OK(result) ? True : False;
4905 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4906 const struct dom_sid *sid,
4907 struct unixid *id)
4909 struct ldapsam_privates *priv =
4910 (struct ldapsam_privates *)methods->private_data;
4911 char *filter;
4912 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4913 NULL };
4914 LDAPMessage *result = NULL;
4915 LDAPMessage *entry = NULL;
4916 bool ret = False;
4917 char *value;
4918 int rc;
4920 TALLOC_CTX *mem_ctx;
4922 ret = pdb_sid_to_id_unix_users_and_groups(sid, id);
4923 if (ret == true) {
4924 return true;
4927 mem_ctx = talloc_new(NULL);
4928 if (mem_ctx == NULL) {
4929 DEBUG(0, ("talloc_new failed\n"));
4930 return False;
4933 filter = talloc_asprintf(mem_ctx,
4934 "(&(sambaSid=%s)"
4935 "(|(objectClass=%s)(objectClass=%s)))",
4936 sid_string_talloc(mem_ctx, sid),
4937 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4938 if (filter == NULL) {
4939 DEBUG(5, ("talloc_asprintf failed\n"));
4940 goto done;
4943 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4944 attrs, &result);
4945 if (rc != LDAP_SUCCESS) {
4946 goto done;
4948 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4950 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4951 DEBUG(10, ("Got %d entries, expected one\n",
4952 ldap_count_entries(priv2ld(priv), result)));
4953 goto done;
4956 entry = ldap_first_entry(priv2ld(priv), result);
4958 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4959 "sambaGroupType", mem_ctx);
4961 if (value != NULL) {
4962 const char *gid_str;
4963 /* It's a group */
4965 gid_str = smbldap_talloc_single_attribute(
4966 priv2ld(priv), entry, "gidNumber", mem_ctx);
4967 if (gid_str == NULL) {
4968 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4969 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4970 entry)));
4971 goto done;
4974 id->id = strtoul(gid_str, NULL, 10);
4975 id->type = ID_TYPE_GID;
4976 ret = True;
4977 goto done;
4980 /* It must be a user */
4982 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4983 "uidNumber", mem_ctx);
4984 if (value == NULL) {
4985 DEBUG(1, ("Could not find uidNumber in %s\n",
4986 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4987 goto done;
4990 id->id = strtoul(value, NULL, 10);
4991 id->type = ID_TYPE_UID;
4993 ret = True;
4994 done:
4995 TALLOC_FREE(mem_ctx);
4996 return ret;
5000 * Find the SID for a uid.
5001 * This is shortcut is only used if ldapsam:trusted is set to true.
5003 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5004 struct dom_sid *sid)
5006 struct ldapsam_privates *priv =
5007 (struct ldapsam_privates *)methods->private_data;
5008 char *filter;
5009 const char *attrs[] = { "sambaSID", NULL };
5010 LDAPMessage *result = NULL;
5011 LDAPMessage *entry = NULL;
5012 bool ret = false;
5013 char *user_sid_string;
5014 struct dom_sid user_sid;
5015 int rc;
5016 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5018 filter = talloc_asprintf(tmp_ctx,
5019 "(&(uidNumber=%u)"
5020 "(objectClass=%s)"
5021 "(objectClass=%s))",
5022 (unsigned int)uid,
5023 LDAP_OBJ_POSIXACCOUNT,
5024 LDAP_OBJ_SAMBASAMACCOUNT);
5025 if (filter == NULL) {
5026 DEBUG(3, ("talloc_asprintf failed\n"));
5027 goto done;
5030 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5031 if (rc != LDAP_SUCCESS) {
5032 goto done;
5034 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5036 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5037 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5038 ldap_count_entries(priv2ld(priv), result),
5039 (unsigned int)uid));
5040 goto done;
5043 entry = ldap_first_entry(priv2ld(priv), result);
5045 user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5046 "sambaSID", tmp_ctx);
5047 if (user_sid_string == NULL) {
5048 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5049 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5050 goto done;
5053 if (!string_to_sid(&user_sid, user_sid_string)) {
5054 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5055 user_sid_string));
5056 goto done;
5059 sid_copy(sid, &user_sid);
5061 ret = true;
5063 done:
5064 TALLOC_FREE(tmp_ctx);
5065 return ret;
5069 * Find the SID for a gid.
5070 * This is shortcut is only used if ldapsam:trusted is set to true.
5072 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5073 struct dom_sid *sid)
5075 struct ldapsam_privates *priv =
5076 (struct ldapsam_privates *)methods->private_data;
5077 char *filter;
5078 const char *attrs[] = { "sambaSID", NULL };
5079 LDAPMessage *result = NULL;
5080 LDAPMessage *entry = NULL;
5081 bool ret = false;
5082 char *group_sid_string;
5083 struct dom_sid group_sid;
5084 int rc;
5085 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5087 filter = talloc_asprintf(tmp_ctx,
5088 "(&(gidNumber=%u)"
5089 "(objectClass=%s))",
5090 (unsigned int)gid,
5091 LDAP_OBJ_GROUPMAP);
5092 if (filter == NULL) {
5093 DEBUG(3, ("talloc_asprintf failed\n"));
5094 goto done;
5097 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5098 if (rc != LDAP_SUCCESS) {
5099 goto done;
5101 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5103 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5104 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5105 ldap_count_entries(priv2ld(priv), result),
5106 (unsigned int)gid));
5107 goto done;
5110 entry = ldap_first_entry(priv2ld(priv), result);
5112 group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5113 "sambaSID", tmp_ctx);
5114 if (group_sid_string == NULL) {
5115 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5116 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5117 goto done;
5120 if (!string_to_sid(&group_sid, group_sid_string)) {
5121 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5122 group_sid_string));
5123 goto done;
5126 sid_copy(sid, &group_sid);
5128 ret = true;
5130 done:
5131 TALLOC_FREE(tmp_ctx);
5132 return ret;
5135 static bool ldapsam_id_to_sid(struct pdb_methods *methods, struct unixid *id,
5136 struct dom_sid *sid)
5138 switch (id->type) {
5139 case ID_TYPE_UID:
5140 return ldapsam_uid_to_sid(methods, id->id, sid);
5142 case ID_TYPE_GID:
5143 return ldapsam_gid_to_sid(methods, id->id, sid);
5145 default:
5146 return false;
5152 * The following functions are called only if
5153 * ldapsam:trusted and ldapsam:editposix are
5154 * set to true
5158 * ldapsam_create_user creates a new
5159 * posixAccount and sambaSamAccount object
5160 * in the ldap users subtree
5162 * The uid is allocated by winbindd.
5165 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5166 TALLOC_CTX *tmp_ctx, const char *name,
5167 uint32_t acb_info, uint32_t *rid)
5169 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5170 LDAPMessage *entry = NULL;
5171 LDAPMessage *result = NULL;
5172 uint32_t num_result;
5173 bool is_machine = False;
5174 bool add_posix = False;
5175 bool init_okay = False;
5176 LDAPMod **mods = NULL;
5177 struct samu *user;
5178 char *filter;
5179 char *username;
5180 char *homedir;
5181 char *gidstr;
5182 char *uidstr;
5183 char *shell;
5184 const char *dn = NULL;
5185 struct dom_sid group_sid;
5186 struct dom_sid user_sid;
5187 gid_t gid = -1;
5188 uid_t uid = -1;
5189 NTSTATUS ret;
5190 int rc;
5192 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5193 acb_info & ACB_WSTRUST ||
5194 acb_info & ACB_SVRTRUST ||
5195 acb_info & ACB_DOMTRUST) {
5196 is_machine = True;
5199 username = escape_ldap_string(talloc_tos(), name);
5200 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5201 username, LDAP_OBJ_POSIXACCOUNT);
5202 TALLOC_FREE(username);
5204 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5205 if (rc != LDAP_SUCCESS) {
5206 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5207 return NT_STATUS_ACCESS_DENIED;
5209 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5211 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5213 if (num_result > 1) {
5214 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5215 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5218 if (num_result == 1) {
5219 char *tmp;
5220 /* check if it is just a posix account.
5221 * or if there is a sid attached to this entry
5224 entry = ldap_first_entry(priv2ld(ldap_state), result);
5225 if (!entry) {
5226 return NT_STATUS_UNSUCCESSFUL;
5229 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5230 if (tmp) {
5231 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5232 return NT_STATUS_USER_EXISTS;
5235 /* it is just a posix account, retrieve the dn for later use */
5236 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5237 if (!dn) {
5238 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5239 return NT_STATUS_NO_MEMORY;
5243 if (num_result == 0) {
5244 add_posix = True;
5247 /* Create the basic samu structure and generate the mods for the ldap commit */
5248 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5249 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5250 return ret;
5253 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5255 user = samu_new(tmp_ctx);
5256 if (!user) {
5257 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5258 return NT_STATUS_NO_MEMORY;
5261 if (!pdb_set_username(user, name, PDB_SET)) {
5262 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5263 return NT_STATUS_UNSUCCESSFUL;
5265 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5266 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5267 return NT_STATUS_UNSUCCESSFUL;
5269 if (is_machine) {
5270 if (acb_info & ACB_NORMAL) {
5271 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5272 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5273 return NT_STATUS_UNSUCCESSFUL;
5275 } else {
5276 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5277 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5278 return NT_STATUS_UNSUCCESSFUL;
5281 } else {
5282 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5283 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5284 return NT_STATUS_UNSUCCESSFUL;
5288 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5289 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5290 return NT_STATUS_UNSUCCESSFUL;
5293 init_okay = init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed);
5294 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5296 if (!init_okay) {
5297 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5298 return NT_STATUS_UNSUCCESSFUL;
5301 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5302 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5304 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5306 if (add_posix) {
5307 char *escape_name;
5309 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5311 /* retrieve the Domain Users group gid */
5312 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5313 !sid_to_gid(&group_sid, &gid)) {
5314 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5315 return NT_STATUS_INVALID_PRIMARY_GROUP;
5318 /* lets allocate a new userid for this user */
5319 if (!winbind_allocate_uid(&uid)) {
5320 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5321 return NT_STATUS_UNSUCCESSFUL;
5325 if (is_machine) {
5326 /* TODO: choose a more appropriate default for machines */
5327 homedir = talloc_sub_specified(tmp_ctx,
5328 lp_template_homedir(),
5329 "SMB_workstations_home",
5330 NULL,
5331 ldap_state->domain_name,
5332 uid,
5333 gid);
5334 shell = talloc_strdup(tmp_ctx, "/bin/false");
5335 } else {
5336 homedir = talloc_sub_specified(tmp_ctx,
5337 lp_template_homedir(),
5338 name,
5339 NULL,
5340 ldap_state->domain_name,
5341 uid,
5342 gid);
5343 shell = talloc_sub_specified(tmp_ctx,
5344 lp_template_shell(),
5345 name,
5346 NULL,
5347 ldap_state->domain_name,
5348 uid,
5349 gid);
5351 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5352 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5354 escape_name = escape_rdn_val_string_alloc(name);
5355 if (!escape_name) {
5356 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5357 return NT_STATUS_NO_MEMORY;
5360 if (is_machine) {
5361 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
5362 } else {
5363 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
5366 SAFE_FREE(escape_name);
5368 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5369 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5370 return NT_STATUS_NO_MEMORY;
5373 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5374 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5375 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5376 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5377 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5378 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5379 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5382 if (add_posix) {
5383 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5384 } else {
5385 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5388 if (rc != LDAP_SUCCESS) {
5389 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5390 return NT_STATUS_UNSUCCESSFUL;
5393 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5395 flush_pwnam_cache();
5397 return NT_STATUS_OK;
5400 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5402 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5403 LDAPMessage *result = NULL;
5404 LDAPMessage *entry = NULL;
5405 int num_result;
5406 const char *dn;
5407 char *filter;
5408 int rc;
5410 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5412 filter = talloc_asprintf(tmp_ctx,
5413 "(&(uid=%s)"
5414 "(objectClass=%s)"
5415 "(objectClass=%s))",
5416 pdb_get_username(sam_acct),
5417 LDAP_OBJ_POSIXACCOUNT,
5418 LDAP_OBJ_SAMBASAMACCOUNT);
5419 if (filter == NULL) {
5420 return NT_STATUS_NO_MEMORY;
5423 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5424 if (rc != LDAP_SUCCESS) {
5425 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5426 return NT_STATUS_UNSUCCESSFUL;
5428 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5430 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5432 if (num_result == 0) {
5433 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5434 return NT_STATUS_NO_SUCH_USER;
5437 if (num_result > 1) {
5438 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5439 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5442 entry = ldap_first_entry(priv2ld(ldap_state), result);
5443 if (!entry) {
5444 return NT_STATUS_UNSUCCESSFUL;
5447 /* it is just a posix account, retrieve the dn for later use */
5448 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5449 if (!dn) {
5450 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5451 return NT_STATUS_NO_MEMORY;
5454 /* try to remove memberships first */
5456 NTSTATUS status;
5457 struct dom_sid *sids = NULL;
5458 gid_t *gids = NULL;
5459 uint32_t num_groups = 0;
5460 int i;
5461 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5463 status = ldapsam_enum_group_memberships(my_methods,
5464 tmp_ctx,
5465 sam_acct,
5466 &sids,
5467 &gids,
5468 &num_groups);
5469 if (!NT_STATUS_IS_OK(status)) {
5470 goto delete_dn;
5473 for (i=0; i < num_groups; i++) {
5475 uint32_t group_rid;
5477 sid_peek_rid(&sids[i], &group_rid);
5479 ldapsam_del_groupmem(my_methods,
5480 tmp_ctx,
5481 group_rid,
5482 user_rid);
5486 delete_dn:
5488 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5489 if (rc != LDAP_SUCCESS) {
5490 return NT_STATUS_UNSUCCESSFUL;
5493 flush_pwnam_cache();
5495 return NT_STATUS_OK;
5499 * ldapsam_create_group creates a new
5500 * posixGroup and sambaGroupMapping object
5501 * in the ldap groups subtree
5503 * The gid is allocated by winbindd.
5506 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5507 TALLOC_CTX *tmp_ctx,
5508 const char *name,
5509 uint32_t *rid)
5511 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5512 NTSTATUS ret;
5513 LDAPMessage *entry = NULL;
5514 LDAPMessage *result = NULL;
5515 uint32_t num_result;
5516 bool is_new_entry = False;
5517 LDAPMod **mods = NULL;
5518 char *filter;
5519 char *groupsidstr;
5520 char *groupname;
5521 char *grouptype;
5522 char *gidstr;
5523 const char *dn = NULL;
5524 struct dom_sid group_sid;
5525 gid_t gid = -1;
5526 int rc;
5528 groupname = escape_ldap_string(talloc_tos(), name);
5529 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5530 groupname, LDAP_OBJ_POSIXGROUP);
5531 TALLOC_FREE(groupname);
5533 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5534 if (rc != LDAP_SUCCESS) {
5535 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5536 return NT_STATUS_UNSUCCESSFUL;
5538 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5540 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5542 if (num_result > 1) {
5543 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5544 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5547 if (num_result == 1) {
5548 char *tmp;
5549 /* check if it is just a posix group.
5550 * or if there is a sid attached to this entry
5553 entry = ldap_first_entry(priv2ld(ldap_state), result);
5554 if (!entry) {
5555 return NT_STATUS_UNSUCCESSFUL;
5558 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5559 if (tmp) {
5560 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5561 return NT_STATUS_GROUP_EXISTS;
5564 /* it is just a posix group, retrieve the gid and the dn for later use */
5565 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5566 if (!tmp) {
5567 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5568 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5571 gid = strtoul(tmp, NULL, 10);
5573 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5574 if (!dn) {
5575 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5576 return NT_STATUS_NO_MEMORY;
5580 if (num_result == 0) {
5581 is_new_entry = true;
5584 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5585 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5586 return ret;
5589 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5591 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5592 &group_sid));
5593 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5595 if (!groupsidstr || !grouptype) {
5596 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5597 return NT_STATUS_NO_MEMORY;
5600 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5601 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5602 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5603 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5605 if (is_new_entry) {
5606 char *escape_name;
5608 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5610 /* lets allocate a new groupid for this group */
5611 if (!winbind_allocate_gid(&gid)) {
5612 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5613 return NT_STATUS_UNSUCCESSFUL;
5616 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5618 escape_name = escape_rdn_val_string_alloc(name);
5619 if (!escape_name) {
5620 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5621 return NT_STATUS_NO_MEMORY;
5624 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
5626 SAFE_FREE(escape_name);
5628 if (!gidstr || !dn) {
5629 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5630 return NT_STATUS_NO_MEMORY;
5633 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5634 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5635 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5638 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5640 if (is_new_entry) {
5641 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5642 #if 0
5643 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5644 /* This call may fail with rfc2307bis schema */
5645 /* Retry adding a structural class */
5646 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5647 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5649 #endif
5650 } else {
5651 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5654 if (rc != LDAP_SUCCESS) {
5655 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5656 return NT_STATUS_UNSUCCESSFUL;
5659 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5661 return NT_STATUS_OK;
5664 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5666 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5667 LDAPMessage *result = NULL;
5668 LDAPMessage *entry = NULL;
5669 int num_result;
5670 const char *dn;
5671 char *gidstr;
5672 char *filter;
5673 struct dom_sid group_sid;
5674 int rc;
5676 /* get the group sid */
5677 sid_compose(&group_sid, get_global_sam_sid(), rid);
5679 filter = talloc_asprintf(tmp_ctx,
5680 "(&(sambaSID=%s)"
5681 "(objectClass=%s)"
5682 "(objectClass=%s))",
5683 sid_string_talloc(tmp_ctx, &group_sid),
5684 LDAP_OBJ_POSIXGROUP,
5685 LDAP_OBJ_GROUPMAP);
5686 if (filter == NULL) {
5687 return NT_STATUS_NO_MEMORY;
5690 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5691 if (rc != LDAP_SUCCESS) {
5692 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5693 return NT_STATUS_UNSUCCESSFUL;
5695 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5697 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5699 if (num_result == 0) {
5700 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5701 return NT_STATUS_NO_SUCH_GROUP;
5704 if (num_result > 1) {
5705 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5706 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5709 entry = ldap_first_entry(priv2ld(ldap_state), result);
5710 if (!entry) {
5711 return NT_STATUS_UNSUCCESSFUL;
5714 /* here it is, retrieve the dn for later use */
5715 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5716 if (!dn) {
5717 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5718 return NT_STATUS_NO_MEMORY;
5721 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5722 if (!gidstr) {
5723 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5724 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5727 /* check no user have this group marked as primary group */
5728 filter = talloc_asprintf(tmp_ctx,
5729 "(&(gidNumber=%s)"
5730 "(objectClass=%s)"
5731 "(objectClass=%s))",
5732 gidstr,
5733 LDAP_OBJ_POSIXACCOUNT,
5734 LDAP_OBJ_SAMBASAMACCOUNT);
5736 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5737 if (rc != LDAP_SUCCESS) {
5738 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5739 return NT_STATUS_UNSUCCESSFUL;
5741 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5743 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5745 if (num_result != 0) {
5746 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5747 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5750 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5751 if (rc != LDAP_SUCCESS) {
5752 return NT_STATUS_UNSUCCESSFUL;
5755 return NT_STATUS_OK;
5758 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5759 TALLOC_CTX *tmp_ctx,
5760 uint32_t group_rid,
5761 uint32_t member_rid,
5762 int modop)
5764 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5765 LDAPMessage *entry = NULL;
5766 LDAPMessage *result = NULL;
5767 uint32_t num_result;
5768 LDAPMod **mods = NULL;
5769 char *filter;
5770 char *uidstr;
5771 const char *dn = NULL;
5772 struct dom_sid group_sid;
5773 struct dom_sid member_sid;
5774 int rc;
5776 switch (modop) {
5777 case LDAP_MOD_ADD:
5778 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5779 break;
5780 case LDAP_MOD_DELETE:
5781 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5782 break;
5783 default:
5784 return NT_STATUS_UNSUCCESSFUL;
5787 /* get member sid */
5788 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5790 /* get the group sid */
5791 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5793 filter = talloc_asprintf(tmp_ctx,
5794 "(&(sambaSID=%s)"
5795 "(objectClass=%s)"
5796 "(objectClass=%s))",
5797 sid_string_talloc(tmp_ctx, &member_sid),
5798 LDAP_OBJ_POSIXACCOUNT,
5799 LDAP_OBJ_SAMBASAMACCOUNT);
5800 if (filter == NULL) {
5801 return NT_STATUS_NO_MEMORY;
5804 /* get the member uid */
5805 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5806 if (rc != LDAP_SUCCESS) {
5807 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5808 return NT_STATUS_UNSUCCESSFUL;
5810 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5812 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5814 if (num_result == 0) {
5815 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5816 return NT_STATUS_NO_SUCH_MEMBER;
5819 if (num_result > 1) {
5820 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5821 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5824 entry = ldap_first_entry(priv2ld(ldap_state), result);
5825 if (!entry) {
5826 return NT_STATUS_UNSUCCESSFUL;
5829 if (modop == LDAP_MOD_DELETE) {
5830 /* check if we are trying to remove the member from his primary group */
5831 char *gidstr;
5832 gid_t user_gid, group_gid;
5834 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5835 if (!gidstr) {
5836 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5837 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5840 user_gid = strtoul(gidstr, NULL, 10);
5842 if (!sid_to_gid(&group_sid, &group_gid)) {
5843 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5844 return NT_STATUS_UNSUCCESSFUL;
5847 if (user_gid == group_gid) {
5848 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5849 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5853 /* here it is, retrieve the uid for later use */
5854 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5855 if (!uidstr) {
5856 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5857 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5860 filter = talloc_asprintf(tmp_ctx,
5861 "(&(sambaSID=%s)"
5862 "(objectClass=%s)"
5863 "(objectClass=%s))",
5864 sid_string_talloc(tmp_ctx, &group_sid),
5865 LDAP_OBJ_POSIXGROUP,
5866 LDAP_OBJ_GROUPMAP);
5868 /* get the group */
5869 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5870 if (rc != LDAP_SUCCESS) {
5871 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5872 return NT_STATUS_UNSUCCESSFUL;
5874 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5876 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5878 if (num_result == 0) {
5879 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5880 return NT_STATUS_NO_SUCH_GROUP;
5883 if (num_result > 1) {
5884 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5885 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5888 entry = ldap_first_entry(priv2ld(ldap_state), result);
5889 if (!entry) {
5890 return NT_STATUS_UNSUCCESSFUL;
5893 /* here it is, retrieve the dn for later use */
5894 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5895 if (!dn) {
5896 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5897 return NT_STATUS_NO_MEMORY;
5900 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5902 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5904 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5905 if (rc != LDAP_SUCCESS) {
5906 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5907 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5908 return NT_STATUS_MEMBER_IN_GROUP;
5910 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5911 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5912 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5914 return NT_STATUS_UNSUCCESSFUL;
5917 return NT_STATUS_OK;
5920 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5921 TALLOC_CTX *tmp_ctx,
5922 uint32_t group_rid,
5923 uint32_t member_rid)
5925 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5927 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5928 TALLOC_CTX *tmp_ctx,
5929 uint32_t group_rid,
5930 uint32_t member_rid)
5932 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5935 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5936 TALLOC_CTX *mem_ctx,
5937 struct samu *sampass)
5939 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5940 LDAPMessage *entry = NULL;
5941 LDAPMessage *result = NULL;
5942 uint32_t num_result;
5943 LDAPMod **mods = NULL;
5944 char *filter;
5945 char *escape_username;
5946 char *gidstr;
5947 const char *dn = NULL;
5948 gid_t gid;
5949 int rc;
5951 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5953 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5954 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5955 return NT_STATUS_UNSUCCESSFUL;
5957 gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5958 if (!gidstr) {
5959 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5960 return NT_STATUS_NO_MEMORY;
5963 escape_username = escape_ldap_string(talloc_tos(),
5964 pdb_get_username(sampass));
5965 if (escape_username== NULL) {
5966 return NT_STATUS_NO_MEMORY;
5969 filter = talloc_asprintf(mem_ctx,
5970 "(&(uid=%s)"
5971 "(objectClass=%s)"
5972 "(objectClass=%s))",
5973 escape_username,
5974 LDAP_OBJ_POSIXACCOUNT,
5975 LDAP_OBJ_SAMBASAMACCOUNT);
5977 TALLOC_FREE(escape_username);
5979 if (filter == NULL) {
5980 return NT_STATUS_NO_MEMORY;
5983 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5984 if (rc != LDAP_SUCCESS) {
5985 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5986 return NT_STATUS_UNSUCCESSFUL;
5988 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
5990 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5992 if (num_result == 0) {
5993 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5994 return NT_STATUS_NO_SUCH_USER;
5997 if (num_result > 1) {
5998 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5999 return NT_STATUS_INTERNAL_DB_CORRUPTION;
6002 entry = ldap_first_entry(priv2ld(ldap_state), result);
6003 if (!entry) {
6004 return NT_STATUS_UNSUCCESSFUL;
6007 /* retrieve the dn for later use */
6008 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
6009 if (!dn) {
6010 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
6011 return NT_STATUS_NO_MEMORY;
6014 /* remove the old one, and add the new one, this way we do not risk races */
6015 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
6017 if (mods == NULL) {
6018 return NT_STATUS_OK;
6021 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6023 if (rc != LDAP_SUCCESS) {
6024 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6025 pdb_get_username(sampass), gidstr));
6026 return NT_STATUS_UNSUCCESSFUL;
6029 flush_pwnam_cache();
6031 return NT_STATUS_OK;
6035 /**********************************************************************
6036 trusted domains functions
6037 *********************************************************************/
6039 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6040 const char *domain)
6042 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6043 ldap_state->domain_dn);
6046 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6047 TALLOC_CTX *mem_ctx,
6048 const char *domain, LDAPMessage **entry)
6050 int rc;
6051 char *filter;
6052 int scope = LDAP_SCOPE_SUBTREE;
6053 const char **attrs = NULL; /* NULL: get all attrs */
6054 int attrsonly = 0; /* 0: return values too */
6055 LDAPMessage *result = NULL;
6056 char *trusted_dn;
6057 uint32_t num_result;
6059 filter = talloc_asprintf(talloc_tos(),
6060 "(&(objectClass=%s)(sambaDomainName=%s))",
6061 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6063 trusted_dn = trusteddom_dn(ldap_state, domain);
6064 if (trusted_dn == NULL) {
6065 return False;
6067 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6068 filter, attrs, attrsonly, &result);
6070 if (result != NULL) {
6071 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6074 if (rc == LDAP_NO_SUCH_OBJECT) {
6075 *entry = NULL;
6076 return True;
6079 if (rc != LDAP_SUCCESS) {
6080 return False;
6083 num_result = ldap_count_entries(priv2ld(ldap_state), result);
6085 if (num_result > 1) {
6086 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6087 "%s object for domain '%s'?!\n",
6088 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6089 return False;
6092 if (num_result == 0) {
6093 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6094 "%s object for domain %s.\n",
6095 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6096 *entry = NULL;
6097 } else {
6098 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6101 return True;
6104 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6105 const char *domain,
6106 char** pwd,
6107 struct dom_sid *sid,
6108 time_t *pass_last_set_time)
6110 struct ldapsam_privates *ldap_state =
6111 (struct ldapsam_privates *)methods->private_data;
6112 LDAPMessage *entry = NULL;
6114 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6116 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6117 (entry == NULL))
6119 return False;
6122 /* password */
6123 if (pwd != NULL) {
6124 char *pwd_str;
6125 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6126 entry, "sambaClearTextPassword", talloc_tos());
6127 if (pwd_str == NULL) {
6128 return False;
6130 /* trusteddom_pw routines do not use talloc yet... */
6131 *pwd = SMB_STRDUP(pwd_str);
6132 if (*pwd == NULL) {
6133 return False;
6137 /* last change time */
6138 if (pass_last_set_time != NULL) {
6139 char *time_str;
6140 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6141 entry, "sambaPwdLastSet", talloc_tos());
6142 if (time_str == NULL) {
6143 return False;
6145 *pass_last_set_time = (time_t)atol(time_str);
6148 /* domain sid */
6149 if (sid != NULL) {
6150 char *sid_str;
6151 struct dom_sid dom_sid;
6152 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6153 entry, "sambaSID",
6154 talloc_tos());
6155 if (sid_str == NULL) {
6156 return False;
6158 if (!string_to_sid(&dom_sid, sid_str)) {
6159 return False;
6161 sid_copy(sid, &dom_sid);
6164 return True;
6167 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6168 const char* domain,
6169 const char* pwd,
6170 const struct dom_sid *sid)
6172 struct ldapsam_privates *ldap_state =
6173 (struct ldapsam_privates *)methods->private_data;
6174 LDAPMessage *entry = NULL;
6175 LDAPMod **mods = NULL;
6176 char *prev_pwd = NULL;
6177 char *trusted_dn = NULL;
6178 int rc;
6180 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6183 * get the current entry (if there is one) in order to put the
6184 * current password into the previous password attribute
6186 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6187 return False;
6190 mods = NULL;
6191 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6192 LDAP_OBJ_TRUSTDOM_PASSWORD);
6193 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6194 domain);
6195 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6196 sid_string_tos(sid));
6197 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6198 talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6199 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6200 "sambaClearTextPassword", pwd);
6202 if (entry != NULL) {
6203 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6204 entry, "sambaClearTextPassword", talloc_tos());
6205 if (prev_pwd != NULL) {
6206 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6207 "sambaPreviousClearTextPassword",
6208 prev_pwd);
6212 smbldap_talloc_autofree_ldapmod(talloc_tos(), mods);
6214 trusted_dn = trusteddom_dn(ldap_state, domain);
6215 if (trusted_dn == NULL) {
6216 return False;
6218 if (entry == NULL) {
6219 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6220 } else {
6221 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6224 if (rc != LDAP_SUCCESS) {
6225 DEBUG(1, ("error writing trusted domain password!\n"));
6226 return False;
6229 return True;
6232 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6233 const char *domain)
6235 int rc;
6236 struct ldapsam_privates *ldap_state =
6237 (struct ldapsam_privates *)methods->private_data;
6238 LDAPMessage *entry = NULL;
6239 const char *trusted_dn;
6241 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6242 return False;
6245 if (entry == NULL) {
6246 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6247 "%s\n", domain));
6248 return True;
6251 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6252 entry);
6253 if (trusted_dn == NULL) {
6254 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6255 return False;
6258 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6259 if (rc != LDAP_SUCCESS) {
6260 return False;
6263 return True;
6266 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6267 TALLOC_CTX *mem_ctx,
6268 uint32_t *num_domains,
6269 struct trustdom_info ***domains)
6271 int rc;
6272 struct ldapsam_privates *ldap_state =
6273 (struct ldapsam_privates *)methods->private_data;
6274 char *filter;
6275 int scope = LDAP_SCOPE_SUBTREE;
6276 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6277 int attrsonly = 0; /* 0: return values too */
6278 LDAPMessage *result = NULL;
6279 LDAPMessage *entry = NULL;
6281 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6282 LDAP_OBJ_TRUSTDOM_PASSWORD);
6284 rc = smbldap_search(ldap_state->smbldap_state,
6285 ldap_state->domain_dn,
6286 scope,
6287 filter,
6288 attrs,
6289 attrsonly,
6290 &result);
6292 if (result != NULL) {
6293 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6296 if (rc != LDAP_SUCCESS) {
6297 return NT_STATUS_UNSUCCESSFUL;
6300 *num_domains = 0;
6301 if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6302 DEBUG(1, ("talloc failed\n"));
6303 return NT_STATUS_NO_MEMORY;
6306 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6307 entry != NULL;
6308 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6310 char *dom_name, *dom_sid_str;
6311 struct trustdom_info *dom_info;
6313 dom_info = talloc(*domains, struct trustdom_info);
6314 if (dom_info == NULL) {
6315 DEBUG(1, ("talloc failed\n"));
6316 return NT_STATUS_NO_MEMORY;
6319 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6320 entry,
6321 "sambaDomainName",
6322 talloc_tos());
6323 if (dom_name == NULL) {
6324 DEBUG(1, ("talloc failed\n"));
6325 return NT_STATUS_NO_MEMORY;
6327 dom_info->name = dom_name;
6329 dom_sid_str = smbldap_talloc_single_attribute(
6330 priv2ld(ldap_state), entry, "sambaSID",
6331 talloc_tos());
6332 if (dom_sid_str == NULL) {
6333 DEBUG(1, ("talloc failed\n"));
6334 return NT_STATUS_NO_MEMORY;
6336 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6337 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6338 dom_sid_str));
6339 return NT_STATUS_UNSUCCESSFUL;
6342 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6343 domains, num_domains);
6345 if (*domains == NULL) {
6346 DEBUG(1, ("talloc failed\n"));
6347 return NT_STATUS_NO_MEMORY;
6351 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6352 return NT_STATUS_OK;
6356 /**********************************************************************
6357 Housekeeping
6358 *********************************************************************/
6360 static void free_private_data(void **vp)
6362 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6364 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6366 if ((*ldap_state)->result != NULL) {
6367 ldap_msgfree((*ldap_state)->result);
6368 (*ldap_state)->result = NULL;
6370 if ((*ldap_state)->domain_dn != NULL) {
6371 SAFE_FREE((*ldap_state)->domain_dn);
6374 *ldap_state = NULL;
6376 /* No need to free any further, as it is talloc()ed */
6379 /*********************************************************************
6380 Intitalise the parts of the pdb_methods structure that are common to
6381 all pdb_ldap modes
6382 *********************************************************************/
6384 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6386 NTSTATUS nt_status;
6387 struct ldapsam_privates *ldap_state;
6388 char *bind_dn = NULL;
6389 char *bind_secret = NULL;
6391 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6392 return nt_status;
6395 (*pdb_method)->name = "ldapsam";
6397 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6398 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6399 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6400 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6401 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6402 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6404 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6405 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6406 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6407 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6408 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6409 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6410 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6412 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6413 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6415 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6417 (*pdb_method)->capabilities = ldapsam_capabilities;
6418 (*pdb_method)->new_rid = ldapsam_new_rid;
6420 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6421 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6422 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6423 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6425 /* TODO: Setup private data and free */
6427 if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6428 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6429 return NT_STATUS_NO_MEMORY;
6432 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
6433 DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
6434 return NT_STATUS_NO_MEMORY;
6437 nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
6438 location, false, bind_dn, bind_secret,
6439 &ldap_state->smbldap_state);
6440 memset(bind_secret, '\0', strlen(bind_secret));
6441 SAFE_FREE(bind_secret);
6442 SAFE_FREE(bind_dn);
6443 if ( !NT_STATUS_IS_OK(nt_status) ) {
6444 return nt_status;
6447 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6448 return NT_STATUS_NO_MEMORY;
6451 (*pdb_method)->private_data = ldap_state;
6453 (*pdb_method)->free_private_data = free_private_data;
6455 return NT_STATUS_OK;
6458 static bool ldapsam_is_responsible_for_wellknown(struct pdb_methods *m)
6460 return true;
6463 /**********************************************************************
6464 Initialise the normal mode for pdb_ldap
6465 *********************************************************************/
6467 NTSTATUS pdb_ldapsam_init_common(struct pdb_methods **pdb_method,
6468 const char *location)
6470 NTSTATUS nt_status;
6471 struct ldapsam_privates *ldap_state = NULL;
6472 uint32_t alg_rid_base;
6473 char *alg_rid_base_string = NULL;
6474 LDAPMessage *result = NULL;
6475 LDAPMessage *entry = NULL;
6476 struct dom_sid ldap_domain_sid;
6477 struct dom_sid secrets_domain_sid;
6478 char *domain_sid_string = NULL;
6479 char *dn = NULL;
6480 char *uri = talloc_strdup( NULL, location );
6482 trim_char( uri, '\"', '\"' );
6483 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6485 TALLOC_FREE(uri);
6487 if (!NT_STATUS_IS_OK(nt_status)) {
6488 return nt_status;
6491 (*pdb_method)->name = "ldapsam";
6493 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6494 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6495 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6496 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6497 (*pdb_method)->search_users = ldapsam_search_users;
6498 (*pdb_method)->search_groups = ldapsam_search_groups;
6499 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6500 (*pdb_method)->is_responsible_for_wellknown =
6501 ldapsam_is_responsible_for_wellknown;
6503 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6504 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6505 (*pdb_method)->enum_group_memberships =
6506 ldapsam_enum_group_memberships;
6507 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6508 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6509 (*pdb_method)->id_to_sid = ldapsam_id_to_sid;
6511 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6512 (*pdb_method)->create_user = ldapsam_create_user;
6513 (*pdb_method)->delete_user = ldapsam_delete_user;
6514 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6515 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6516 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6517 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6518 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6522 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6523 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6525 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6527 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6528 &result,
6529 ldap_state->domain_name, True);
6531 if ( !NT_STATUS_IS_OK(nt_status) ) {
6532 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6533 "info, nor add one to the domain. "
6534 "We cannot work reliably without it.\n"));
6535 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6538 /* Given that the above might fail, everything below this must be
6539 * optional */
6541 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6542 result);
6543 if (!entry) {
6544 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6545 "entry\n"));
6546 ldap_msgfree(result);
6547 return NT_STATUS_UNSUCCESSFUL;
6550 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6551 if (!dn) {
6552 ldap_msgfree(result);
6553 return NT_STATUS_UNSUCCESSFUL;
6556 ldap_state->domain_dn = smb_xstrdup(dn);
6557 TALLOC_FREE(dn);
6559 domain_sid_string = smbldap_talloc_single_attribute(
6560 ldap_state->smbldap_state->ldap_struct,
6561 entry,
6562 get_userattr_key2string(ldap_state->schema_ver,
6563 LDAP_ATTR_USER_SID),
6564 talloc_tos());
6566 if (domain_sid_string) {
6567 bool found_sid;
6568 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6569 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6570 "read as a valid SID\n", domain_sid_string));
6571 ldap_msgfree(result);
6572 TALLOC_FREE(domain_sid_string);
6573 return NT_STATUS_INVALID_PARAMETER;
6575 found_sid = PDB_secrets_fetch_domain_sid(ldap_state->domain_name,
6576 &secrets_domain_sid);
6577 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6578 &ldap_domain_sid)) {
6579 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6580 "%s based on pdb_ldap results %s -> %s\n",
6581 ldap_state->domain_name,
6582 sid_string_dbg(&secrets_domain_sid),
6583 sid_string_dbg(&ldap_domain_sid)));
6585 /* reset secrets.tdb sid */
6586 PDB_secrets_store_domain_sid(ldap_state->domain_name,
6587 &ldap_domain_sid);
6588 DEBUG(1, ("New global sam SID: %s\n",
6589 sid_string_dbg(get_global_sam_sid())));
6591 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6592 TALLOC_FREE(domain_sid_string);
6595 alg_rid_base_string = smbldap_talloc_single_attribute(
6596 ldap_state->smbldap_state->ldap_struct,
6597 entry,
6598 get_attr_key2string( dominfo_attr_list,
6599 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6600 talloc_tos());
6601 if (alg_rid_base_string) {
6602 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6603 if (alg_rid_base != algorithmic_rid_base()) {
6604 DEBUG(0, ("The value of 'algorithmic RID base' has "
6605 "changed since the LDAP\n"
6606 "database was initialised. Aborting. \n"));
6607 ldap_msgfree(result);
6608 TALLOC_FREE(alg_rid_base_string);
6609 return NT_STATUS_UNSUCCESSFUL;
6611 TALLOC_FREE(alg_rid_base_string);
6613 ldap_msgfree(result);
6615 return NT_STATUS_OK;
6618 NTSTATUS pdb_ldapsam_init(void)
6620 NTSTATUS nt_status;
6622 nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION,
6623 "ldapsam",
6624 pdb_ldapsam_init_common);
6625 if (!NT_STATUS_IS_OK(nt_status)) {
6626 return nt_status;
6629 /* Let pdb_nds register backends */
6630 pdb_nds_init();
6632 pdb_ipa_init();
6634 return NT_STATUS_OK;