librpc: Shorten dcerpc_binding_handle_call a bit
[Samba/gebeck_regimport.git] / source3 / passdb / pdb_ldap.c
blob0905ab4eeb0dd65c07e334eac85e246bfc9a674b
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 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 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 *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_array(ctx, uint8,
859 pwHistLen * PW_HISTORY_ENTRY_LEN);
860 if (pwhist == NULL) {
861 DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
862 goto fn_exit;
864 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
866 if (smbldap_get_single_attribute(
867 ldap_state->smbldap_state->ldap_struct,
868 entry,
869 get_userattr_key2string(ldap_state->schema_ver,
870 LDAP_ATTR_PWD_HISTORY),
871 history_string,
872 MAX_PW_HISTORY_LEN*64)) {
873 bool hex_failed = false;
874 for (i = 0; i < pwHistLen; i++){
875 /* Get the 16 byte salt. */
876 if (!pdb_gethexpwd(&history_string[i*64],
877 &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
878 hex_failed = true;
879 break;
881 /* Get the 16 byte MD5 hash of salt+passwd. */
882 if (!pdb_gethexpwd(&history_string[(i*64)+32],
883 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
884 PW_HISTORY_SALT_LEN])) {
885 hex_failed = True;
886 break;
889 if (hex_failed) {
890 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
891 username));
892 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
895 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
896 goto fn_exit;
900 temp = smbldap_talloc_single_attribute(
901 ldap_state->smbldap_state->ldap_struct,
902 entry,
903 get_userattr_key2string(ldap_state->schema_ver,
904 LDAP_ATTR_ACB_INFO),
905 ctx);
906 if (temp) {
907 acct_ctrl = pdb_decode_acct_ctrl(temp);
909 if (acct_ctrl == 0) {
910 acct_ctrl |= ACB_NORMAL;
913 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
914 } else {
915 acct_ctrl |= ACB_NORMAL;
918 pdb_set_hours_len(sampass, hours_len, PDB_SET);
919 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
921 temp = smbldap_talloc_single_attribute(
922 ldap_state->smbldap_state->ldap_struct,
923 entry,
924 get_userattr_key2string(ldap_state->schema_ver,
925 LDAP_ATTR_BAD_PASSWORD_COUNT),
926 ctx);
927 if (temp) {
928 bad_password_count = (uint32_t) atol(temp);
929 pdb_set_bad_password_count(sampass,
930 bad_password_count, PDB_SET);
933 temp = smbldap_talloc_single_attribute(
934 ldap_state->smbldap_state->ldap_struct,
935 entry,
936 get_userattr_key2string(ldap_state->schema_ver,
937 LDAP_ATTR_BAD_PASSWORD_TIME),
938 ctx);
939 if (temp) {
940 bad_password_time = (time_t) atol(temp);
941 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
945 temp = smbldap_talloc_single_attribute(
946 ldap_state->smbldap_state->ldap_struct,
947 entry,
948 get_userattr_key2string(ldap_state->schema_ver,
949 LDAP_ATTR_LOGON_COUNT),
950 ctx);
951 if (temp) {
952 logon_count = (uint32_t) atol(temp);
953 pdb_set_logon_count(sampass, logon_count, PDB_SET);
956 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
958 temp = smbldap_talloc_single_attribute(
959 ldap_state->smbldap_state->ldap_struct,
960 entry,
961 get_userattr_key2string(ldap_state->schema_ver,
962 LDAP_ATTR_LOGON_HOURS),
963 ctx);
964 if (temp) {
965 pdb_gethexhours(temp, hours);
966 memset((char *)temp, '\0', strlen(temp) +1);
967 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
968 ZERO_STRUCT(hours);
971 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
972 struct passwd unix_pw;
973 bool have_uid = false;
974 bool have_gid = false;
975 struct dom_sid mapped_gsid;
976 const struct dom_sid *primary_gsid;
977 struct unixid id;
979 ZERO_STRUCT(unix_pw);
981 unix_pw.pw_name = username;
982 unix_pw.pw_passwd = discard_const_p(char, "x");
984 temp = smbldap_talloc_single_attribute(
985 priv2ld(ldap_state),
986 entry,
987 "uidNumber",
988 ctx);
989 if (temp) {
990 /* We've got a uid, feed the cache */
991 unix_pw.pw_uid = strtoul(temp, NULL, 10);
992 have_uid = true;
994 temp = smbldap_talloc_single_attribute(
995 priv2ld(ldap_state),
996 entry,
997 "gidNumber",
998 ctx);
999 if (temp) {
1000 /* We've got a uid, feed the cache */
1001 unix_pw.pw_gid = strtoul(temp, NULL, 10);
1002 have_gid = true;
1004 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1005 priv2ld(ldap_state),
1006 entry,
1007 "gecos",
1008 ctx);
1009 if (unix_pw.pw_gecos) {
1010 unix_pw.pw_gecos = fullname;
1012 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1013 priv2ld(ldap_state),
1014 entry,
1015 "homeDirectory",
1016 ctx);
1017 if (unix_pw.pw_dir) {
1018 unix_pw.pw_dir = discard_const_p(char, "");
1020 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1021 priv2ld(ldap_state),
1022 entry,
1023 "loginShell",
1024 ctx);
1025 if (unix_pw.pw_shell) {
1026 unix_pw.pw_shell = discard_const_p(char, "");
1029 if (have_uid && have_gid) {
1030 sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1031 } else {
1032 sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1035 if (sampass->unix_pw == NULL) {
1036 DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1037 pdb_get_username(sampass)));
1038 goto fn_exit;
1041 id.id = sampass->unix_pw->pw_uid;
1042 id.type = ID_TYPE_UID;
1044 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1046 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1047 primary_gsid = pdb_get_group_sid(sampass);
1048 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1049 id.id = sampass->unix_pw->pw_gid;
1050 id.type = ID_TYPE_GID;
1052 idmap_cache_set_sid2unixid(primary_gsid, &id);
1056 /* check the timestamp of the cache vs ldap entry */
1057 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1058 entry))) {
1059 ret = true;
1060 goto fn_exit;
1063 /* see if we have newer updates */
1064 if (!login_cache_read(sampass, &cache_entry)) {
1065 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1066 (unsigned int)pdb_get_bad_password_count(sampass),
1067 (unsigned int)pdb_get_bad_password_time(sampass)));
1068 ret = true;
1069 goto fn_exit;
1072 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1073 (unsigned int)ldap_entry_time,
1074 (unsigned int)cache_entry.entry_timestamp,
1075 (unsigned int)cache_entry.bad_password_time));
1077 if (ldap_entry_time > cache_entry.entry_timestamp) {
1078 /* cache is older than directory , so
1079 we need to delete the entry but allow the
1080 fields to be written out */
1081 login_cache_delentry(sampass);
1082 } else {
1083 /* read cache in */
1084 pdb_set_acct_ctrl(sampass,
1085 pdb_get_acct_ctrl(sampass) |
1086 (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1087 PDB_SET);
1088 pdb_set_bad_password_count(sampass,
1089 cache_entry.bad_password_count,
1090 PDB_SET);
1091 pdb_set_bad_password_time(sampass,
1092 cache_entry.bad_password_time,
1093 PDB_SET);
1096 ret = true;
1098 fn_exit:
1100 TALLOC_FREE(ctx);
1101 return ret;
1104 /**********************************************************************
1105 Initialize the ldap db from a struct samu. Called on update.
1106 (Based on init_buffer_from_sam in pdb_tdb.c)
1107 *********************************************************************/
1109 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1110 LDAPMessage *existing,
1111 LDAPMod *** mods, struct samu * sampass,
1112 bool (*need_update)(const struct samu *,
1113 enum pdb_elements))
1115 char *temp = NULL;
1117 if (mods == NULL || sampass == NULL) {
1118 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1119 return False;
1122 *mods = NULL;
1125 * took out adding "objectclass: sambaAccount"
1126 * do this on a per-mod basis
1128 if (need_update(sampass, PDB_USERNAME)) {
1129 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1130 "uid", pdb_get_username(sampass));
1131 if (ldap_state->is_nds_ldap) {
1132 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1133 "cn", pdb_get_username(sampass));
1134 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1135 "sn", pdb_get_username(sampass));
1139 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1141 /* only update the RID if we actually need to */
1142 if (need_update(sampass, PDB_USERSID)) {
1143 fstring sid_string;
1144 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1146 switch ( ldap_state->schema_ver ) {
1147 case SCHEMAVER_SAMBASAMACCOUNT:
1148 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1149 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1150 sid_to_fstring(sid_string, user_sid));
1151 break;
1153 default:
1154 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1155 break;
1159 /* we don't need to store the primary group RID - so leaving it
1160 'free' to hang off the unix primary group makes life easier */
1162 if (need_update(sampass, PDB_GROUPSID)) {
1163 fstring sid_string;
1164 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1166 switch ( ldap_state->schema_ver ) {
1167 case SCHEMAVER_SAMBASAMACCOUNT:
1168 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1169 get_userattr_key2string(ldap_state->schema_ver,
1170 LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1171 break;
1173 default:
1174 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1175 break;
1180 /* displayName, cn, and gecos should all be the same
1181 * most easily accomplished by giving them the same OID
1182 * gecos isn't set here b/c it should be handled by the
1183 * add-user script
1184 * We change displayName only and fall back to cn if
1185 * it does not exist.
1188 if (need_update(sampass, PDB_FULLNAME))
1189 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1190 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME),
1191 pdb_get_fullname(sampass));
1193 if (need_update(sampass, PDB_ACCTDESC))
1194 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1195 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC),
1196 pdb_get_acct_desc(sampass));
1198 if (need_update(sampass, PDB_WORKSTATIONS))
1199 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1200 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS),
1201 pdb_get_workstations(sampass));
1203 if (need_update(sampass, PDB_MUNGEDDIAL))
1204 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1205 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL),
1206 pdb_get_munged_dial(sampass));
1208 if (need_update(sampass, PDB_SMBHOME))
1209 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1210 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH),
1211 pdb_get_homedir(sampass));
1213 if (need_update(sampass, PDB_DRIVE))
1214 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1215 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE),
1216 pdb_get_dir_drive(sampass));
1218 if (need_update(sampass, PDB_LOGONSCRIPT))
1219 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1220 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT),
1221 pdb_get_logon_script(sampass));
1223 if (need_update(sampass, PDB_PROFILE))
1224 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1225 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH),
1226 pdb_get_profile_path(sampass));
1228 if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1229 return false;
1231 if (need_update(sampass, PDB_LOGONTIME))
1232 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1233 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1234 SAFE_FREE(temp);
1236 if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1237 return false;
1239 if (need_update(sampass, PDB_LOGOFFTIME))
1240 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1241 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1242 SAFE_FREE(temp);
1244 if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1245 return false;
1247 if (need_update(sampass, PDB_KICKOFFTIME))
1248 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1249 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1250 SAFE_FREE(temp);
1252 if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1253 return false;
1255 if (need_update(sampass, PDB_CANCHANGETIME))
1256 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1257 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1258 SAFE_FREE(temp);
1260 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1261 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1263 if (need_update(sampass, PDB_LMPASSWD)) {
1264 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1265 if (lm_pw) {
1266 char pwstr[34];
1267 pdb_sethexpwd(pwstr, lm_pw,
1268 pdb_get_acct_ctrl(sampass));
1269 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1270 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1271 pwstr);
1272 } else {
1273 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1274 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1275 NULL);
1278 if (need_update(sampass, PDB_NTPASSWD)) {
1279 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1280 if (nt_pw) {
1281 char pwstr[34];
1282 pdb_sethexpwd(pwstr, nt_pw,
1283 pdb_get_acct_ctrl(sampass));
1284 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1285 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1286 pwstr);
1287 } else {
1288 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1289 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1290 NULL);
1294 if (need_update(sampass, PDB_PWHISTORY)) {
1295 char *pwstr = NULL;
1296 uint32_t pwHistLen = 0;
1297 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1299 pwstr = SMB_MALLOC_ARRAY(char, 1024);
1300 if (!pwstr) {
1301 return false;
1303 if (pwHistLen == 0) {
1304 /* Remove any password history from the LDAP store. */
1305 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1306 pwstr[64] = '\0';
1307 } else {
1308 int i;
1309 uint32_t currHistLen = 0;
1310 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1311 if (pwhist != NULL) {
1312 /* We can only store (1024-1/64 password history entries. */
1313 pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1314 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1315 /* Store the salt. */
1316 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1317 /* Followed by the md5 hash of salt + md4 hash */
1318 pdb_sethexpwd(&pwstr[(i*64)+32],
1319 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1320 DEBUG(100, ("pwstr=%s\n", pwstr));
1324 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1325 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1326 pwstr);
1327 SAFE_FREE(pwstr);
1330 if (need_update(sampass, PDB_PASSLASTSET)) {
1331 if (asprintf(&temp, "%li",
1332 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1333 return false;
1335 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1336 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1337 temp);
1338 SAFE_FREE(temp);
1342 if (need_update(sampass, PDB_HOURS)) {
1343 const uint8 *hours = pdb_get_hours(sampass);
1344 if (hours) {
1345 char hourstr[44];
1346 pdb_sethexhours(hourstr, hours);
1347 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1348 existing,
1349 mods,
1350 get_userattr_key2string(ldap_state->schema_ver,
1351 LDAP_ATTR_LOGON_HOURS),
1352 hourstr);
1356 if (need_update(sampass, PDB_ACCTCTRL))
1357 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1358 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1359 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1361 /* password lockout cache:
1362 - If we are now autolocking or clearing, we write to ldap
1363 - If we are clearing, we delete the cache entry
1364 - If the count is > 0, we update the cache
1366 This even means when autolocking, we cache, just in case the
1367 update doesn't work, and we have to cache the autolock flag */
1369 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1370 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1371 uint16_t badcount = pdb_get_bad_password_count(sampass);
1372 time_t badtime = pdb_get_bad_password_time(sampass);
1373 uint32_t pol;
1374 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1376 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1377 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1379 if ((badcount >= pol) || (badcount == 0)) {
1380 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1381 (unsigned int)badcount, (unsigned int)badtime));
1382 if (asprintf(&temp, "%li", (long)badcount) < 0) {
1383 return false;
1385 smbldap_make_mod(
1386 ldap_state->smbldap_state->ldap_struct,
1387 existing, mods,
1388 get_userattr_key2string(
1389 ldap_state->schema_ver,
1390 LDAP_ATTR_BAD_PASSWORD_COUNT),
1391 temp);
1392 SAFE_FREE(temp);
1394 if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1395 return false;
1397 smbldap_make_mod(
1398 ldap_state->smbldap_state->ldap_struct,
1399 existing, mods,
1400 get_userattr_key2string(
1401 ldap_state->schema_ver,
1402 LDAP_ATTR_BAD_PASSWORD_TIME),
1403 temp);
1404 SAFE_FREE(temp);
1406 if (badcount == 0) {
1407 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1408 login_cache_delentry(sampass);
1409 } else {
1410 struct login_cache cache_entry;
1412 cache_entry.entry_timestamp = time(NULL);
1413 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1414 cache_entry.bad_password_count = badcount;
1415 cache_entry.bad_password_time = badtime;
1417 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1418 login_cache_write(sampass, &cache_entry);
1422 return True;
1425 /**********************************************************************
1426 End enumeration of the LDAP password list.
1427 *********************************************************************/
1429 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1431 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1432 if (ldap_state->result) {
1433 ldap_msgfree(ldap_state->result);
1434 ldap_state->result = NULL;
1438 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1439 const char *new_attr)
1441 int i;
1443 if (new_attr == NULL) {
1444 return;
1447 for (i=0; (*attr_list)[i] != NULL; i++) {
1451 (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1452 const char *, i+2);
1453 SMB_ASSERT((*attr_list) != NULL);
1454 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1455 (*attr_list)[i+1] = NULL;
1458 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1459 const char ***attr_list)
1461 append_attr(mem_ctx, attr_list, "uidNumber");
1462 append_attr(mem_ctx, attr_list, "gidNumber");
1463 append_attr(mem_ctx, attr_list, "homeDirectory");
1464 append_attr(mem_ctx, attr_list, "loginShell");
1465 append_attr(mem_ctx, attr_list, "gecos");
1468 /**********************************************************************
1469 Get struct samu entry from LDAP by username.
1470 *********************************************************************/
1472 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1474 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1475 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1476 LDAPMessage *result = NULL;
1477 LDAPMessage *entry = NULL;
1478 int count;
1479 const char ** attr_list;
1480 int rc;
1482 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1483 append_attr(user, &attr_list,
1484 get_userattr_key2string(ldap_state->schema_ver,
1485 LDAP_ATTR_MOD_TIMESTAMP));
1486 ldapsam_add_unix_attributes(user, &attr_list);
1487 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1488 attr_list);
1489 TALLOC_FREE( attr_list );
1491 if ( rc != LDAP_SUCCESS )
1492 return NT_STATUS_NO_SUCH_USER;
1494 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1496 if (count < 1) {
1497 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1498 ldap_msgfree(result);
1499 return NT_STATUS_NO_SUCH_USER;
1500 } else if (count > 1) {
1501 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1502 ldap_msgfree(result);
1503 return NT_STATUS_NO_SUCH_USER;
1506 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1507 if (entry) {
1508 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1509 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1510 ldap_msgfree(result);
1511 return NT_STATUS_NO_SUCH_USER;
1513 pdb_set_backend_private_data(user, result, NULL,
1514 my_methods, PDB_CHANGED);
1515 smbldap_talloc_autofree_ldapmsg(user, result);
1516 ret = NT_STATUS_OK;
1517 } else {
1518 ldap_msgfree(result);
1520 return ret;
1523 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1524 const struct dom_sid *sid, LDAPMessage **result)
1526 int rc = -1;
1527 const char ** attr_list;
1529 switch ( ldap_state->schema_ver ) {
1530 case SCHEMAVER_SAMBASAMACCOUNT: {
1531 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1532 if (tmp_ctx == NULL) {
1533 return LDAP_NO_MEMORY;
1536 attr_list = get_userattr_list(tmp_ctx,
1537 ldap_state->schema_ver);
1538 append_attr(tmp_ctx, &attr_list,
1539 get_userattr_key2string(
1540 ldap_state->schema_ver,
1541 LDAP_ATTR_MOD_TIMESTAMP));
1542 ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1543 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1544 result, attr_list);
1545 TALLOC_FREE(tmp_ctx);
1547 if ( rc != LDAP_SUCCESS )
1548 return rc;
1549 break;
1552 default:
1553 DEBUG(0,("Invalid schema version specified\n"));
1554 break;
1556 return rc;
1559 /**********************************************************************
1560 Get struct samu entry from LDAP by SID.
1561 *********************************************************************/
1563 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1565 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1566 LDAPMessage *result = NULL;
1567 LDAPMessage *entry = NULL;
1568 int count;
1569 int rc;
1571 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1572 sid, &result);
1573 if (rc != LDAP_SUCCESS)
1574 return NT_STATUS_NO_SUCH_USER;
1576 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1578 if (count < 1) {
1579 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1580 "count=%d\n", sid_string_dbg(sid), count));
1581 ldap_msgfree(result);
1582 return NT_STATUS_NO_SUCH_USER;
1583 } else if (count > 1) {
1584 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1585 "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1586 count));
1587 ldap_msgfree(result);
1588 return NT_STATUS_NO_SUCH_USER;
1591 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1592 if (!entry) {
1593 ldap_msgfree(result);
1594 return NT_STATUS_NO_SUCH_USER;
1597 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1598 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1599 ldap_msgfree(result);
1600 return NT_STATUS_NO_SUCH_USER;
1603 pdb_set_backend_private_data(user, result, NULL,
1604 my_methods, PDB_CHANGED);
1605 smbldap_talloc_autofree_ldapmsg(user, result);
1606 return NT_STATUS_OK;
1609 /********************************************************************
1610 Do the actual modification - also change a plaintext passord if
1611 it it set.
1612 **********************************************************************/
1614 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1615 struct samu *newpwd, char *dn,
1616 LDAPMod **mods, int ldap_op,
1617 bool (*need_update)(const struct samu *, enum pdb_elements))
1619 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1620 int rc;
1622 if (!newpwd || !dn) {
1623 return NT_STATUS_INVALID_PARAMETER;
1626 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1627 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1628 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1629 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1630 BerElement *ber;
1631 struct berval *bv;
1632 char *retoid = NULL;
1633 struct berval *retdata = NULL;
1634 char *utf8_password;
1635 char *utf8_dn;
1636 size_t converted_size;
1637 int ret;
1639 if (!ldap_state->is_nds_ldap) {
1641 if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct,
1642 LDAP_EXOP_MODIFY_PASSWD)) {
1643 DEBUG(2, ("ldap password change requested, but LDAP "
1644 "server does not support it -- ignoring\n"));
1645 return NT_STATUS_OK;
1649 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1650 pdb_get_plaintext_passwd(newpwd),
1651 &converted_size))
1653 return NT_STATUS_NO_MEMORY;
1656 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1657 TALLOC_FREE(utf8_password);
1658 return NT_STATUS_NO_MEMORY;
1661 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1662 DEBUG(0,("ber_alloc_t returns NULL\n"));
1663 TALLOC_FREE(utf8_password);
1664 TALLOC_FREE(utf8_dn);
1665 return NT_STATUS_UNSUCCESSFUL;
1668 if ((ber_printf (ber, "{") < 0) ||
1669 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1670 utf8_dn) < 0)) {
1671 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1672 "value <0\n"));
1673 ber_free(ber,1);
1674 TALLOC_FREE(utf8_dn);
1675 TALLOC_FREE(utf8_password);
1676 return NT_STATUS_UNSUCCESSFUL;
1679 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1680 ret = ber_printf(ber, "ts}",
1681 LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1682 utf8_password);
1683 } else {
1684 ret = ber_printf(ber, "}");
1687 if (ret < 0) {
1688 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1689 "value <0\n"));
1690 ber_free(ber,1);
1691 TALLOC_FREE(utf8_dn);
1692 TALLOC_FREE(utf8_password);
1693 return NT_STATUS_UNSUCCESSFUL;
1696 if ((rc = ber_flatten (ber, &bv))<0) {
1697 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1698 ber_free(ber,1);
1699 TALLOC_FREE(utf8_dn);
1700 TALLOC_FREE(utf8_password);
1701 return NT_STATUS_UNSUCCESSFUL;
1704 TALLOC_FREE(utf8_dn);
1705 TALLOC_FREE(utf8_password);
1706 ber_free(ber, 1);
1708 if (!ldap_state->is_nds_ldap) {
1709 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1710 LDAP_EXOP_MODIFY_PASSWD,
1711 bv, NULL, NULL, &retoid,
1712 &retdata);
1713 } else {
1714 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1715 pdb_get_plaintext_passwd(newpwd));
1717 if (rc != LDAP_SUCCESS) {
1718 char *ld_error = NULL;
1720 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1721 DEBUG(3, ("Could not set userPassword "
1722 "attribute due to an objectClass "
1723 "violation -- ignoring\n"));
1724 ber_bvfree(bv);
1725 return NT_STATUS_OK;
1728 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1729 &ld_error);
1730 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1731 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1732 SAFE_FREE(ld_error);
1733 ber_bvfree(bv);
1734 #if defined(LDAP_CONSTRAINT_VIOLATION)
1735 if (rc == LDAP_CONSTRAINT_VIOLATION)
1736 return NT_STATUS_PASSWORD_RESTRICTION;
1737 #endif
1738 return NT_STATUS_UNSUCCESSFUL;
1739 } else {
1740 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1741 #ifdef DEBUG_PASSWORD
1742 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1743 #endif
1744 if (retdata)
1745 ber_bvfree(retdata);
1746 if (retoid)
1747 ldap_memfree(retoid);
1749 ber_bvfree(bv);
1752 if (!mods) {
1753 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1754 /* may be password change below however */
1755 } else {
1756 switch(ldap_op) {
1757 case LDAP_MOD_ADD:
1758 if (ldap_state->is_nds_ldap) {
1759 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1760 "objectclass",
1761 "inetOrgPerson");
1762 } else {
1763 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1764 "objectclass",
1765 LDAP_OBJ_ACCOUNT);
1767 rc = smbldap_add(ldap_state->smbldap_state,
1768 dn, mods);
1769 break;
1770 case LDAP_MOD_REPLACE:
1771 rc = smbldap_modify(ldap_state->smbldap_state,
1772 dn ,mods);
1773 break;
1774 default:
1775 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1776 ldap_op));
1777 return NT_STATUS_INVALID_PARAMETER;
1780 if (rc!=LDAP_SUCCESS) {
1781 return NT_STATUS_UNSUCCESSFUL;
1785 return NT_STATUS_OK;
1788 /**********************************************************************
1789 Delete entry from LDAP for username.
1790 *********************************************************************/
1792 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1793 struct samu * sam_acct)
1795 struct ldapsam_privates *priv =
1796 (struct ldapsam_privates *)my_methods->private_data;
1797 const char *sname;
1798 int rc;
1799 LDAPMessage *msg, *entry;
1800 NTSTATUS result = NT_STATUS_NO_MEMORY;
1801 const char **attr_list;
1802 TALLOC_CTX *mem_ctx;
1804 if (!sam_acct) {
1805 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1806 return NT_STATUS_INVALID_PARAMETER;
1809 sname = pdb_get_username(sam_acct);
1811 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1812 "LDAP.\n", sname));
1814 mem_ctx = talloc_new(NULL);
1815 if (mem_ctx == NULL) {
1816 DEBUG(0, ("talloc_new failed\n"));
1817 goto done;
1820 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1821 if (attr_list == NULL) {
1822 goto done;
1825 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1827 if ((rc != LDAP_SUCCESS) ||
1828 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1829 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1830 DEBUG(5, ("Could not find user %s\n", sname));
1831 result = NT_STATUS_NO_SUCH_USER;
1832 goto done;
1835 rc = ldapsam_delete_entry(
1836 priv, mem_ctx, entry,
1837 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1838 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1839 attr_list);
1841 result = (rc == LDAP_SUCCESS) ?
1842 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1844 done:
1845 TALLOC_FREE(mem_ctx);
1846 return result;
1849 /**********************************************************************
1850 Update struct samu.
1851 *********************************************************************/
1853 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1855 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1856 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1857 int rc = 0;
1858 char *dn;
1859 LDAPMessage *result = NULL;
1860 LDAPMessage *entry = NULL;
1861 LDAPMod **mods = NULL;
1862 const char **attr_list;
1864 result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1865 if (!result) {
1866 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1867 if (pdb_get_username(newpwd) == NULL) {
1868 return NT_STATUS_INVALID_PARAMETER;
1870 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1871 TALLOC_FREE( attr_list );
1872 if (rc != LDAP_SUCCESS) {
1873 return NT_STATUS_UNSUCCESSFUL;
1875 pdb_set_backend_private_data(newpwd, result, NULL,
1876 my_methods, PDB_CHANGED);
1877 smbldap_talloc_autofree_ldapmsg(newpwd, result);
1880 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1881 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1882 return NT_STATUS_UNSUCCESSFUL;
1885 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1886 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1887 if (!dn) {
1888 return NT_STATUS_UNSUCCESSFUL;
1891 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1893 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1894 pdb_element_is_changed)) {
1895 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1896 TALLOC_FREE(dn);
1897 if (mods != NULL)
1898 ldap_mods_free(mods,True);
1899 return NT_STATUS_UNSUCCESSFUL;
1902 if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1903 && (mods == NULL)) {
1904 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1905 pdb_get_username(newpwd)));
1906 TALLOC_FREE(dn);
1907 return NT_STATUS_OK;
1910 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1912 if (mods != NULL) {
1913 ldap_mods_free(mods,True);
1916 TALLOC_FREE(dn);
1919 * We need to set the backend private data to NULL here. For example
1920 * setuserinfo level 25 does a pdb_update_sam_account twice on the
1921 * same one, and with the explicit delete / add logic for attribute
1922 * values the second time we would use the wrong "old" value which
1923 * does not exist in LDAP anymore. Thus the LDAP server would refuse
1924 * the update.
1925 * The existing LDAPMessage is still being auto-freed by the
1926 * destructor.
1928 pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1929 PDB_CHANGED);
1931 if (!NT_STATUS_IS_OK(ret)) {
1932 return ret;
1935 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1936 pdb_get_username(newpwd)));
1937 return NT_STATUS_OK;
1940 /***************************************************************************
1941 Renames a struct samu
1942 - The "rename user script" has full responsibility for changing everything
1943 ***************************************************************************/
1945 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1946 TALLOC_CTX *tmp_ctx,
1947 uint32_t group_rid,
1948 uint32_t member_rid);
1950 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1951 TALLOC_CTX *mem_ctx,
1952 struct samu *user,
1953 struct dom_sid **pp_sids,
1954 gid_t **pp_gids,
1955 uint32_t *p_num_groups);
1957 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1958 struct samu *old_acct,
1959 const char *newname)
1961 const char *oldname;
1962 int rc;
1963 char *rename_script = NULL;
1964 fstring oldname_lower, newname_lower;
1966 if (!old_acct) {
1967 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1968 return NT_STATUS_INVALID_PARAMETER;
1970 if (!newname) {
1971 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1972 return NT_STATUS_INVALID_PARAMETER;
1975 oldname = pdb_get_username(old_acct);
1977 /* rename the posix user */
1978 rename_script = lp_renameuser_script(talloc_tos());
1979 if (rename_script == NULL) {
1980 return NT_STATUS_NO_MEMORY;
1983 if (!(*rename_script)) {
1984 TALLOC_FREE(rename_script);
1985 return NT_STATUS_ACCESS_DENIED;
1988 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
1989 oldname, newname));
1991 /* We have to allow the account name to end with a '$'.
1992 Also, follow the semantics in _samr_create_user() and lower case the
1993 posix name but preserve the case in passdb */
1995 fstrcpy( oldname_lower, oldname );
1996 if (!strlower_m( oldname_lower )) {
1997 return NT_STATUS_INVALID_PARAMETER;
1999 fstrcpy( newname_lower, newname );
2000 if (!strlower_m( newname_lower )) {
2001 return NT_STATUS_INVALID_PARAMETER;
2004 rename_script = realloc_string_sub2(rename_script,
2005 "%unew",
2006 newname_lower,
2007 true,
2008 true);
2009 if (!rename_script) {
2010 return NT_STATUS_NO_MEMORY;
2012 rename_script = realloc_string_sub2(rename_script,
2013 "%uold",
2014 oldname_lower,
2015 true,
2016 true);
2017 rc = smbrun(rename_script, NULL);
2019 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2020 rename_script, rc));
2022 TALLOC_FREE(rename_script);
2024 if (rc == 0) {
2025 smb_nscd_flush_user_cache();
2028 if (rc)
2029 return NT_STATUS_UNSUCCESSFUL;
2031 return NT_STATUS_OK;
2034 /**********************************************************************
2035 Add struct samu to LDAP.
2036 *********************************************************************/
2038 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2040 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2041 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2042 int rc;
2043 LDAPMessage *result = NULL;
2044 LDAPMessage *entry = NULL;
2045 LDAPMod **mods = NULL;
2046 int ldap_op = LDAP_MOD_REPLACE;
2047 uint32_t num_result;
2048 const char **attr_list;
2049 char *escape_user = NULL;
2050 const char *username = pdb_get_username(newpwd);
2051 const struct dom_sid *sid = pdb_get_user_sid(newpwd);
2052 char *filter = NULL;
2053 char *dn = NULL;
2054 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2055 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2057 if (!ctx) {
2058 return NT_STATUS_NO_MEMORY;
2061 if (!username || !*username) {
2062 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2063 status = NT_STATUS_INVALID_PARAMETER;
2064 goto fn_exit;
2067 /* free this list after the second search or in case we exit on failure */
2068 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2070 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2072 if (rc != LDAP_SUCCESS) {
2073 goto fn_exit;
2076 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2077 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2078 username));
2079 goto fn_exit;
2081 ldap_msgfree(result);
2082 result = NULL;
2084 if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2085 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2086 sid, &result);
2087 if (rc == LDAP_SUCCESS) {
2088 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2089 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2090 "already in the base, with samba "
2091 "attributes\n", sid_string_dbg(sid)));
2092 goto fn_exit;
2094 ldap_msgfree(result);
2095 result = NULL;
2099 /* does the entry already exist but without a samba attributes?
2100 we need to return the samba attributes here */
2102 escape_user = escape_ldap_string(talloc_tos(), username);
2103 filter = talloc_strdup(attr_list, "(uid=%u)");
2104 if (!filter) {
2105 status = NT_STATUS_NO_MEMORY;
2106 goto fn_exit;
2108 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2109 TALLOC_FREE(escape_user);
2110 if (!filter) {
2111 status = NT_STATUS_NO_MEMORY;
2112 goto fn_exit;
2115 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2116 filter, attr_list, &result);
2117 if ( rc != LDAP_SUCCESS ) {
2118 goto fn_exit;
2121 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2123 if (num_result > 1) {
2124 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2125 goto fn_exit;
2128 /* Check if we need to update an existing entry */
2129 if (num_result == 1) {
2130 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2131 ldap_op = LDAP_MOD_REPLACE;
2132 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2133 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2134 if (!dn) {
2135 status = NT_STATUS_NO_MEMORY;
2136 goto fn_exit;
2139 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2141 /* There might be a SID for this account already - say an idmap entry */
2143 filter = talloc_asprintf(ctx,
2144 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2145 get_userattr_key2string(ldap_state->schema_ver,
2146 LDAP_ATTR_USER_SID),
2147 sid_string_talloc(ctx, sid),
2148 LDAP_OBJ_IDMAP_ENTRY,
2149 LDAP_OBJ_SID_ENTRY);
2150 if (!filter) {
2151 status = NT_STATUS_NO_MEMORY;
2152 goto fn_exit;
2155 /* free old result before doing a new search */
2156 if (result != NULL) {
2157 ldap_msgfree(result);
2158 result = NULL;
2160 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2161 filter, attr_list, &result);
2163 if ( rc != LDAP_SUCCESS ) {
2164 goto fn_exit;
2167 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2169 if (num_result > 1) {
2170 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2171 goto fn_exit;
2174 /* Check if we need to update an existing entry */
2175 if (num_result == 1) {
2177 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2178 ldap_op = LDAP_MOD_REPLACE;
2179 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2180 dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2181 if (!dn) {
2182 status = NT_STATUS_NO_MEMORY;
2183 goto fn_exit;
2188 if (num_result == 0) {
2189 char *escape_username;
2190 /* Check if we need to add an entry */
2191 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2192 ldap_op = LDAP_MOD_ADD;
2194 escape_username = escape_rdn_val_string_alloc(username);
2195 if (!escape_username) {
2196 status = NT_STATUS_NO_MEMORY;
2197 goto fn_exit;
2200 if (username[strlen(username)-1] == '$') {
2201 dn = talloc_asprintf(ctx,
2202 "uid=%s,%s",
2203 escape_username,
2204 lp_ldap_machine_suffix(talloc_tos()));
2205 } else {
2206 dn = talloc_asprintf(ctx,
2207 "uid=%s,%s",
2208 escape_username,
2209 lp_ldap_user_suffix(talloc_tos()));
2212 SAFE_FREE(escape_username);
2213 if (!dn) {
2214 status = NT_STATUS_NO_MEMORY;
2215 goto fn_exit;
2219 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2220 pdb_element_is_set_or_changed)) {
2221 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2222 if (mods != NULL) {
2223 ldap_mods_free(mods, true);
2225 goto fn_exit;
2228 if (mods == NULL) {
2229 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2230 goto fn_exit;
2232 switch ( ldap_state->schema_ver ) {
2233 case SCHEMAVER_SAMBASAMACCOUNT:
2234 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2235 break;
2236 default:
2237 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2238 break;
2241 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2242 if (!NT_STATUS_IS_OK(ret)) {
2243 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2244 pdb_get_username(newpwd),dn));
2245 ldap_mods_free(mods, true);
2246 goto fn_exit;
2249 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2250 ldap_mods_free(mods, true);
2252 status = NT_STATUS_OK;
2254 fn_exit:
2256 TALLOC_FREE(ctx);
2257 if (result) {
2258 ldap_msgfree(result);
2260 return status;
2263 /**********************************************************************
2264 *********************************************************************/
2266 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2267 const char *filter,
2268 LDAPMessage ** result)
2270 int scope = LDAP_SCOPE_SUBTREE;
2271 int rc;
2272 const char **attr_list;
2274 attr_list = get_attr_list(NULL, groupmap_attr_list);
2275 rc = smbldap_search(ldap_state->smbldap_state,
2276 lp_ldap_suffix (talloc_tos()), scope,
2277 filter, attr_list, 0, result);
2278 TALLOC_FREE(attr_list);
2280 return rc;
2283 /**********************************************************************
2284 *********************************************************************/
2286 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2287 GROUP_MAP *map, LDAPMessage *entry)
2289 char *temp = NULL;
2290 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2292 if (ldap_state == NULL || map == NULL || entry == NULL ||
2293 ldap_state->smbldap_state->ldap_struct == NULL) {
2294 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2295 TALLOC_FREE(ctx);
2296 return false;
2299 temp = smbldap_talloc_single_attribute(
2300 ldap_state->smbldap_state->ldap_struct,
2301 entry,
2302 get_attr_key2string(groupmap_attr_list,
2303 LDAP_ATTR_GIDNUMBER),
2304 ctx);
2305 if (!temp) {
2306 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2307 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2308 TALLOC_FREE(ctx);
2309 return false;
2311 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2313 map->gid = (gid_t)atol(temp);
2315 TALLOC_FREE(temp);
2316 temp = smbldap_talloc_single_attribute(
2317 ldap_state->smbldap_state->ldap_struct,
2318 entry,
2319 get_attr_key2string(groupmap_attr_list,
2320 LDAP_ATTR_GROUP_SID),
2321 ctx);
2322 if (!temp) {
2323 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2324 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2325 TALLOC_FREE(ctx);
2326 return false;
2329 if (!string_to_sid(&map->sid, temp)) {
2330 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2331 TALLOC_FREE(ctx);
2332 return false;
2335 TALLOC_FREE(temp);
2336 temp = smbldap_talloc_single_attribute(
2337 ldap_state->smbldap_state->ldap_struct,
2338 entry,
2339 get_attr_key2string(groupmap_attr_list,
2340 LDAP_ATTR_GROUP_TYPE),
2341 ctx);
2342 if (!temp) {
2343 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2344 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2345 TALLOC_FREE(ctx);
2346 return false;
2348 map->sid_name_use = (enum lsa_SidType)atol(temp);
2350 if ((map->sid_name_use < SID_NAME_USER) ||
2351 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2352 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2353 TALLOC_FREE(ctx);
2354 return false;
2357 TALLOC_FREE(temp);
2358 temp = smbldap_talloc_single_attribute(
2359 ldap_state->smbldap_state->ldap_struct,
2360 entry,
2361 get_attr_key2string(groupmap_attr_list,
2362 LDAP_ATTR_DISPLAY_NAME),
2363 ctx);
2364 if (!temp) {
2365 temp = smbldap_talloc_single_attribute(
2366 ldap_state->smbldap_state->ldap_struct,
2367 entry,
2368 get_attr_key2string(groupmap_attr_list,
2369 LDAP_ATTR_CN),
2370 ctx);
2371 if (!temp) {
2372 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2373 for gidNumber(%lu)\n",(unsigned long)map->gid));
2374 TALLOC_FREE(ctx);
2375 return false;
2378 map->nt_name = talloc_strdup(map, temp);
2379 if (!map->nt_name) {
2380 TALLOC_FREE(ctx);
2381 return false;
2384 TALLOC_FREE(temp);
2385 temp = smbldap_talloc_single_attribute(
2386 ldap_state->smbldap_state->ldap_struct,
2387 entry,
2388 get_attr_key2string(groupmap_attr_list,
2389 LDAP_ATTR_DESC),
2390 ctx);
2391 if (!temp) {
2392 temp = talloc_strdup(ctx, "");
2393 if (!temp) {
2394 TALLOC_FREE(ctx);
2395 return false;
2398 map->comment = talloc_strdup(map, temp);
2399 if (!map->comment) {
2400 TALLOC_FREE(ctx);
2401 return false;
2404 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2405 struct unixid id;
2406 id.id = map->gid;
2407 id.type = ID_TYPE_GID;
2409 idmap_cache_set_sid2unixid(&map->sid, &id);
2412 TALLOC_FREE(ctx);
2413 return true;
2416 /**********************************************************************
2417 *********************************************************************/
2419 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2420 const char *filter,
2421 GROUP_MAP *map)
2423 struct ldapsam_privates *ldap_state =
2424 (struct ldapsam_privates *)methods->private_data;
2425 LDAPMessage *result = NULL;
2426 LDAPMessage *entry = NULL;
2427 int count;
2429 if (ldapsam_search_one_group(ldap_state, filter, &result)
2430 != LDAP_SUCCESS) {
2431 return NT_STATUS_NO_SUCH_GROUP;
2434 count = ldap_count_entries(priv2ld(ldap_state), result);
2436 if (count < 1) {
2437 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2438 "%s\n", filter));
2439 ldap_msgfree(result);
2440 return NT_STATUS_NO_SUCH_GROUP;
2443 if (count > 1) {
2444 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2445 "count=%d\n", filter, count));
2446 ldap_msgfree(result);
2447 return NT_STATUS_NO_SUCH_GROUP;
2450 entry = ldap_first_entry(priv2ld(ldap_state), result);
2452 if (!entry) {
2453 ldap_msgfree(result);
2454 return NT_STATUS_UNSUCCESSFUL;
2457 if (!init_group_from_ldap(ldap_state, map, entry)) {
2458 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2459 "group filter %s\n", filter));
2460 ldap_msgfree(result);
2461 return NT_STATUS_NO_SUCH_GROUP;
2464 ldap_msgfree(result);
2465 return NT_STATUS_OK;
2468 /**********************************************************************
2469 *********************************************************************/
2471 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2472 struct dom_sid sid)
2474 char *filter = NULL;
2475 NTSTATUS status;
2476 fstring tmp;
2478 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2479 LDAP_OBJ_GROUPMAP,
2480 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2481 sid_to_fstring(tmp, &sid)) < 0) {
2482 return NT_STATUS_NO_MEMORY;
2485 status = ldapsam_getgroup(methods, filter, map);
2486 SAFE_FREE(filter);
2487 return status;
2490 /**********************************************************************
2491 *********************************************************************/
2493 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2494 gid_t gid)
2496 char *filter = NULL;
2497 NTSTATUS status;
2499 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2500 LDAP_OBJ_GROUPMAP,
2501 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2502 (unsigned long)gid) < 0) {
2503 return NT_STATUS_NO_MEMORY;
2506 status = ldapsam_getgroup(methods, filter, map);
2507 SAFE_FREE(filter);
2508 return status;
2511 /**********************************************************************
2512 *********************************************************************/
2514 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2515 const char *name)
2517 char *filter = NULL;
2518 char *escape_name = escape_ldap_string(talloc_tos(), name);
2519 NTSTATUS status;
2521 if (!escape_name) {
2522 return NT_STATUS_NO_MEMORY;
2525 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2526 LDAP_OBJ_GROUPMAP,
2527 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2528 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2529 escape_name) < 0) {
2530 TALLOC_FREE(escape_name);
2531 return NT_STATUS_NO_MEMORY;
2534 TALLOC_FREE(escape_name);
2535 status = ldapsam_getgroup(methods, filter, map);
2536 SAFE_FREE(filter);
2537 return status;
2540 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2541 LDAPMessage *entry,
2542 const struct dom_sid *domain_sid,
2543 uint32_t *rid)
2545 fstring str;
2546 struct dom_sid sid;
2548 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2549 str, sizeof(str)-1)) {
2550 DEBUG(10, ("Could not find sambaSID attribute\n"));
2551 return False;
2554 if (!string_to_sid(&sid, str)) {
2555 DEBUG(10, ("Could not convert string %s to sid\n", str));
2556 return False;
2559 if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2560 DEBUG(10, ("SID %s is not in expected domain %s\n",
2561 str, sid_string_dbg(domain_sid)));
2562 return False;
2565 if (!sid_peek_rid(&sid, rid)) {
2566 DEBUG(10, ("Could not peek into RID\n"));
2567 return False;
2570 return True;
2573 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2574 TALLOC_CTX *mem_ctx,
2575 const struct dom_sid *group,
2576 uint32_t **pp_member_rids,
2577 size_t *p_num_members)
2579 struct ldapsam_privates *ldap_state =
2580 (struct ldapsam_privates *)methods->private_data;
2581 struct smbldap_state *conn = ldap_state->smbldap_state;
2582 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2583 const char *sid_attrs[] = { "sambaSID", NULL };
2584 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2585 LDAPMessage *result = NULL;
2586 LDAPMessage *entry;
2587 char *filter;
2588 char **values = NULL;
2589 char **memberuid;
2590 char *gidstr;
2591 int rc, count;
2593 *pp_member_rids = NULL;
2594 *p_num_members = 0;
2596 filter = talloc_asprintf(mem_ctx,
2597 "(&(objectClass=%s)"
2598 "(objectClass=%s)"
2599 "(sambaSID=%s))",
2600 LDAP_OBJ_POSIXGROUP,
2601 LDAP_OBJ_GROUPMAP,
2602 sid_string_talloc(mem_ctx, group));
2603 if (filter == NULL) {
2604 ret = NT_STATUS_NO_MEMORY;
2605 goto done;
2608 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2609 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2610 &result);
2612 if (rc != LDAP_SUCCESS)
2613 goto done;
2615 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2617 count = ldap_count_entries(conn->ldap_struct, result);
2619 if (count > 1) {
2620 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2621 sid_string_dbg(group)));
2622 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2623 goto done;
2626 if (count == 0) {
2627 ret = NT_STATUS_NO_SUCH_GROUP;
2628 goto done;
2631 entry = ldap_first_entry(conn->ldap_struct, result);
2632 if (entry == NULL)
2633 goto done;
2635 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2636 if (!gidstr) {
2637 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2638 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2639 goto done;
2642 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2644 if ((values != NULL) && (values[0] != NULL)) {
2646 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2647 if (filter == NULL) {
2648 ret = NT_STATUS_NO_MEMORY;
2649 goto done;
2652 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2653 char *escape_memberuid;
2655 escape_memberuid = escape_ldap_string(talloc_tos(),
2656 *memberuid);
2657 if (escape_memberuid == NULL) {
2658 ret = NT_STATUS_NO_MEMORY;
2659 goto done;
2662 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2663 TALLOC_FREE(escape_memberuid);
2664 if (filter == NULL) {
2665 ret = NT_STATUS_NO_MEMORY;
2666 goto done;
2670 filter = talloc_asprintf_append_buffer(filter, "))");
2671 if (filter == NULL) {
2672 ret = NT_STATUS_NO_MEMORY;
2673 goto done;
2676 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2677 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2678 &result);
2680 if (rc != LDAP_SUCCESS)
2681 goto done;
2683 count = ldap_count_entries(conn->ldap_struct, result);
2684 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2686 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2688 for (entry = ldap_first_entry(conn->ldap_struct, result);
2689 entry != NULL;
2690 entry = ldap_next_entry(conn->ldap_struct, entry))
2692 char *sidstr;
2693 struct dom_sid sid;
2694 uint32_t rid;
2696 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2697 entry, "sambaSID",
2698 mem_ctx);
2699 if (!sidstr) {
2700 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2701 "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2702 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2703 goto done;
2706 if (!string_to_sid(&sid, sidstr))
2707 goto done;
2709 if (!sid_check_is_in_our_sam(&sid)) {
2710 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2711 "in our domain\n"));
2712 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2713 goto done;
2716 sid_peek_rid(&sid, &rid);
2718 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2719 p_num_members)) {
2720 ret = NT_STATUS_NO_MEMORY;
2721 goto done;
2726 filter = talloc_asprintf(mem_ctx,
2727 "(&(objectClass=%s)"
2728 "(gidNumber=%s))",
2729 LDAP_OBJ_SAMBASAMACCOUNT,
2730 gidstr);
2732 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2733 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2734 &result);
2736 if (rc != LDAP_SUCCESS)
2737 goto done;
2739 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2741 for (entry = ldap_first_entry(conn->ldap_struct, result);
2742 entry != NULL;
2743 entry = ldap_next_entry(conn->ldap_struct, entry))
2745 uint32_t rid;
2747 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2748 entry,
2749 get_global_sam_sid(),
2750 &rid)) {
2751 DEBUG(0, ("Severe DB error, %s can't miss the samba SID" "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2752 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2753 goto done;
2756 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2757 p_num_members)) {
2758 ret = NT_STATUS_NO_MEMORY;
2759 goto done;
2763 ret = NT_STATUS_OK;
2765 done:
2767 if (values)
2768 ldap_value_free(values);
2770 return ret;
2773 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2774 TALLOC_CTX *mem_ctx,
2775 struct samu *user,
2776 struct dom_sid **pp_sids,
2777 gid_t **pp_gids,
2778 uint32_t *p_num_groups)
2780 struct ldapsam_privates *ldap_state =
2781 (struct ldapsam_privates *)methods->private_data;
2782 struct smbldap_state *conn = ldap_state->smbldap_state;
2783 char *filter;
2784 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2785 char *escape_name;
2786 int rc, count;
2787 LDAPMessage *result = NULL;
2788 LDAPMessage *entry;
2789 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2790 uint32_t num_sids;
2791 uint32_t num_gids;
2792 char *gidstr;
2793 gid_t primary_gid = -1;
2795 *pp_sids = NULL;
2796 num_sids = 0;
2798 if (pdb_get_username(user) == NULL) {
2799 return NT_STATUS_INVALID_PARAMETER;
2802 escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2803 if (escape_name == NULL)
2804 return NT_STATUS_NO_MEMORY;
2806 if (user->unix_pw) {
2807 primary_gid = user->unix_pw->pw_gid;
2808 } else {
2809 /* retrieve the users primary gid */
2810 filter = talloc_asprintf(mem_ctx,
2811 "(&(objectClass=%s)(uid=%s))",
2812 LDAP_OBJ_SAMBASAMACCOUNT,
2813 escape_name);
2814 if (filter == NULL) {
2815 ret = NT_STATUS_NO_MEMORY;
2816 goto done;
2819 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2820 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2822 if (rc != LDAP_SUCCESS)
2823 goto done;
2825 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2827 count = ldap_count_entries(priv2ld(ldap_state), result);
2829 switch (count) {
2830 case 0:
2831 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2832 ret = NT_STATUS_NO_SUCH_USER;
2833 goto done;
2834 case 1:
2835 entry = ldap_first_entry(priv2ld(ldap_state), result);
2837 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2838 if (!gidstr) {
2839 DEBUG (1, ("Unable to find the member's gid!\n"));
2840 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2841 goto done;
2843 primary_gid = strtoul(gidstr, NULL, 10);
2844 break;
2845 default:
2846 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2847 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2848 goto done;
2852 filter = talloc_asprintf(mem_ctx,
2853 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2854 LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2855 if (filter == NULL) {
2856 ret = NT_STATUS_NO_MEMORY;
2857 goto done;
2860 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2861 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2863 if (rc != LDAP_SUCCESS)
2864 goto done;
2866 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2868 num_gids = 0;
2869 *pp_gids = NULL;
2871 num_sids = 0;
2872 *pp_sids = NULL;
2874 /* We need to add the primary group as the first gid/sid */
2876 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2877 ret = NT_STATUS_NO_MEMORY;
2878 goto done;
2881 /* This sid will be replaced later */
2883 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2884 &num_sids);
2885 if (!NT_STATUS_IS_OK(ret)) {
2886 goto done;
2889 for (entry = ldap_first_entry(conn->ldap_struct, result);
2890 entry != NULL;
2891 entry = ldap_next_entry(conn->ldap_struct, entry))
2893 fstring str;
2894 struct dom_sid sid;
2895 gid_t gid;
2896 char *end;
2898 if (!smbldap_get_single_attribute(conn->ldap_struct,
2899 entry, "sambaSID",
2900 str, sizeof(str)-1))
2901 continue;
2903 if (!string_to_sid(&sid, str))
2904 goto done;
2906 if (!smbldap_get_single_attribute(conn->ldap_struct,
2907 entry, "gidNumber",
2908 str, sizeof(str)-1))
2909 continue;
2911 gid = strtoul(str, &end, 10);
2913 if (PTR_DIFF(end, str) != strlen(str))
2914 goto done;
2916 if (gid == primary_gid) {
2917 sid_copy(&(*pp_sids)[0], &sid);
2918 } else {
2919 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2920 &num_gids)) {
2921 ret = NT_STATUS_NO_MEMORY;
2922 goto done;
2924 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2925 &num_sids);
2926 if (!NT_STATUS_IS_OK(ret)) {
2927 goto done;
2932 if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2933 DEBUG(3, ("primary group of [%s] not found\n",
2934 pdb_get_username(user)));
2935 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2936 goto done;
2939 *p_num_groups = num_sids;
2941 ret = NT_STATUS_OK;
2943 done:
2945 TALLOC_FREE(escape_name);
2946 return ret;
2949 /**********************************************************************
2950 * Augment a posixGroup object with a sambaGroupMapping domgroup
2951 *********************************************************************/
2953 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2954 struct ldapsam_privates *ldap_state,
2955 GROUP_MAP *map)
2957 const char *filter, *dn;
2958 LDAPMessage *msg, *entry;
2959 LDAPMod **mods;
2960 int rc;
2962 filter = talloc_asprintf(mem_ctx,
2963 "(&(objectClass=%s)(gidNumber=%u))",
2964 LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2965 if (filter == NULL) {
2966 return NT_STATUS_NO_MEMORY;
2969 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2970 get_attr_list(mem_ctx, groupmap_attr_list),
2971 &msg);
2972 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
2974 if ((rc != LDAP_SUCCESS) ||
2975 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2976 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2977 return NT_STATUS_NO_SUCH_GROUP;
2980 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2981 if (dn == NULL) {
2982 return NT_STATUS_NO_MEMORY;
2985 mods = NULL;
2986 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2987 LDAP_OBJ_GROUPMAP);
2988 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2989 sid_string_talloc(mem_ctx, &map->sid));
2990 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2991 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2992 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2993 map->nt_name);
2994 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2995 map->comment);
2996 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
2998 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2999 if (rc != LDAP_SUCCESS) {
3000 return NT_STATUS_ACCESS_DENIED;
3003 return NT_STATUS_OK;
3006 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3007 GROUP_MAP *map)
3009 struct ldapsam_privates *ldap_state =
3010 (struct ldapsam_privates *)methods->private_data;
3011 LDAPMessage *msg = NULL;
3012 LDAPMod **mods = NULL;
3013 const char *attrs[] = { NULL };
3014 char *filter;
3016 char *dn;
3017 TALLOC_CTX *mem_ctx;
3018 NTSTATUS result;
3020 struct dom_sid sid;
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 if (pdb_gid_to_sid(map->gid, &sid)) {
3087 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3088 "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3089 result = NT_STATUS_GROUP_EXISTS;
3090 goto done;
3093 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3094 * the best we can get out of LDAP. */
3096 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3097 sid_string_talloc(mem_ctx, &map->sid),
3098 lp_ldap_group_suffix(talloc_tos()));
3099 if (dn == NULL) {
3100 result = NT_STATUS_NO_MEMORY;
3101 goto done;
3104 mods = NULL;
3106 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3107 LDAP_OBJ_SID_ENTRY);
3108 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3109 LDAP_OBJ_GROUPMAP);
3110 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3111 sid_string_talloc(mem_ctx, &map->sid));
3112 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3113 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3114 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3115 map->nt_name);
3116 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3117 map->comment);
3118 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3119 talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3120 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3122 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3124 result = (rc == LDAP_SUCCESS) ?
3125 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3127 done:
3128 TALLOC_FREE(mem_ctx);
3129 return result;
3132 /**********************************************************************
3133 * Update a group mapping entry. We're quite strict about what can be changed:
3134 * Only the description and displayname may be changed. It simply does not
3135 * make any sense to change the SID, gid or the type in a mapping.
3136 *********************************************************************/
3138 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3139 GROUP_MAP *map)
3141 struct ldapsam_privates *ldap_state =
3142 (struct ldapsam_privates *)methods->private_data;
3143 int rc;
3144 const char *filter, *dn;
3145 LDAPMessage *msg = NULL;
3146 LDAPMessage *entry = NULL;
3147 LDAPMod **mods = NULL;
3148 TALLOC_CTX *mem_ctx;
3149 NTSTATUS result;
3151 mem_ctx = talloc_new(NULL);
3152 if (mem_ctx == NULL) {
3153 DEBUG(0, ("talloc_new failed\n"));
3154 return NT_STATUS_NO_MEMORY;
3157 /* Make 100% sure that sid, gid and type are not changed by looking up
3158 * exactly the values we're given in LDAP. */
3160 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3161 "(sambaSid=%s)(gidNumber=%u)"
3162 "(sambaGroupType=%d))",
3163 LDAP_OBJ_GROUPMAP,
3164 sid_string_talloc(mem_ctx, &map->sid),
3165 (unsigned int)map->gid, map->sid_name_use);
3166 if (filter == NULL) {
3167 result = NT_STATUS_NO_MEMORY;
3168 goto done;
3171 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3172 get_attr_list(mem_ctx, groupmap_attr_list),
3173 &msg);
3174 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3176 if ((rc != LDAP_SUCCESS) ||
3177 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3178 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3179 result = NT_STATUS_NO_SUCH_GROUP;
3180 goto done;
3183 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3185 if (dn == NULL) {
3186 result = NT_STATUS_NO_MEMORY;
3187 goto done;
3190 mods = NULL;
3191 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3192 map->nt_name);
3193 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3194 map->comment);
3195 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3197 if (mods == NULL) {
3198 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3199 "nothing to do\n"));
3200 result = NT_STATUS_OK;
3201 goto done;
3204 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3206 if (rc != LDAP_SUCCESS) {
3207 result = NT_STATUS_ACCESS_DENIED;
3208 goto done;
3211 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3212 "group %lu in LDAP\n", (unsigned long)map->gid));
3214 result = NT_STATUS_OK;
3216 done:
3217 TALLOC_FREE(mem_ctx);
3218 return result;
3221 /**********************************************************************
3222 *********************************************************************/
3224 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3225 struct dom_sid sid)
3227 struct ldapsam_privates *priv =
3228 (struct ldapsam_privates *)methods->private_data;
3229 LDAPMessage *msg, *entry;
3230 int rc;
3231 NTSTATUS result;
3232 TALLOC_CTX *mem_ctx;
3233 char *filter;
3235 mem_ctx = talloc_new(NULL);
3236 if (mem_ctx == NULL) {
3237 DEBUG(0, ("talloc_new failed\n"));
3238 return NT_STATUS_NO_MEMORY;
3241 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3242 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3243 sid_string_talloc(mem_ctx, &sid));
3244 if (filter == NULL) {
3245 result = NT_STATUS_NO_MEMORY;
3246 goto done;
3248 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3249 get_attr_list(mem_ctx, groupmap_attr_list),
3250 &msg);
3251 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3253 if ((rc != LDAP_SUCCESS) ||
3254 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3255 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3256 result = NT_STATUS_NO_SUCH_GROUP;
3257 goto done;
3260 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3261 get_attr_list(mem_ctx,
3262 groupmap_attr_list_to_delete));
3264 if ((rc == LDAP_NAMING_VIOLATION) ||
3265 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3266 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3267 const char *attrs[] = { "sambaGroupType", "description",
3268 "displayName", "sambaSIDList",
3269 NULL };
3271 /* Second try. Don't delete the sambaSID attribute, this is
3272 for "old" entries that are tacked on a winbind
3273 sambaIdmapEntry. */
3275 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3276 LDAP_OBJ_GROUPMAP, attrs);
3279 if ((rc == LDAP_NAMING_VIOLATION) ||
3280 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3281 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3282 const char *attrs[] = { "sambaGroupType", "description",
3283 "displayName", "sambaSIDList",
3284 "gidNumber", NULL };
3286 /* Third try. This is a post-3.0.21 alias (containing only
3287 * sambaSidEntry and sambaGroupMapping classes), we also have
3288 * to delete the gidNumber attribute, only the sambaSidEntry
3289 * remains */
3291 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3292 LDAP_OBJ_GROUPMAP, attrs);
3295 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3297 done:
3298 TALLOC_FREE(mem_ctx);
3299 return result;
3302 /**********************************************************************
3303 *********************************************************************/
3305 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3306 bool update)
3308 struct ldapsam_privates *ldap_state =
3309 (struct ldapsam_privates *)my_methods->private_data;
3310 char *filter = NULL;
3311 int rc;
3312 const char **attr_list;
3314 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3315 if (!filter) {
3316 return NT_STATUS_NO_MEMORY;
3318 attr_list = get_attr_list( NULL, groupmap_attr_list );
3319 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3320 LDAP_SCOPE_SUBTREE, filter,
3321 attr_list, 0, &ldap_state->result);
3322 TALLOC_FREE(attr_list);
3324 if (rc != LDAP_SUCCESS) {
3325 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3326 ldap_err2string(rc)));
3327 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3328 lp_ldap_suffix(talloc_tos()), filter));
3329 ldap_msgfree(ldap_state->result);
3330 ldap_state->result = NULL;
3331 TALLOC_FREE(filter);
3332 return NT_STATUS_UNSUCCESSFUL;
3335 TALLOC_FREE(filter);
3337 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3338 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3339 ldap_state->result)));
3341 ldap_state->entry =
3342 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3343 ldap_state->result);
3344 ldap_state->index = 0;
3346 return NT_STATUS_OK;
3349 /**********************************************************************
3350 *********************************************************************/
3352 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3354 ldapsam_endsampwent(my_methods);
3357 /**********************************************************************
3358 *********************************************************************/
3360 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3361 GROUP_MAP *map)
3363 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3364 struct ldapsam_privates *ldap_state =
3365 (struct ldapsam_privates *)my_methods->private_data;
3366 bool bret = False;
3368 while (!bret) {
3369 if (!ldap_state->entry)
3370 return ret;
3372 ldap_state->index++;
3373 bret = init_group_from_ldap(ldap_state, map,
3374 ldap_state->entry);
3376 ldap_state->entry =
3377 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3378 ldap_state->entry);
3381 return NT_STATUS_OK;
3384 /**********************************************************************
3385 *********************************************************************/
3387 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3388 const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3389 GROUP_MAP ***pp_rmap,
3390 size_t *p_num_entries,
3391 bool unix_only)
3393 GROUP_MAP *map = NULL;
3394 size_t entries = 0;
3396 *p_num_entries = 0;
3397 *pp_rmap = NULL;
3399 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3400 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3401 "passdb\n"));
3402 return NT_STATUS_ACCESS_DENIED;
3405 while (true) {
3407 map = talloc_zero(NULL, GROUP_MAP);
3408 if (!map) {
3409 return NT_STATUS_NO_MEMORY;
3412 if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
3413 TALLOC_FREE(map);
3414 break;
3417 if (sid_name_use != SID_NAME_UNKNOWN &&
3418 sid_name_use != map->sid_name_use) {
3419 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3420 "not of the requested type\n",
3421 map->nt_name));
3422 continue;
3424 if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
3425 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3426 "non mapped\n", map->nt_name));
3427 continue;
3430 *pp_rmap = talloc_realloc(NULL, *pp_rmap,
3431 GROUP_MAP *, entries + 1);
3432 if (!(*pp_rmap)) {
3433 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3434 "enlarge group map!\n"));
3435 return NT_STATUS_UNSUCCESSFUL;
3438 (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
3440 entries += 1;
3443 ldapsam_endsamgrent(methods);
3445 *p_num_entries = entries;
3447 return NT_STATUS_OK;
3450 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3451 const struct dom_sid *alias,
3452 const struct dom_sid *member,
3453 int modop)
3455 struct ldapsam_privates *ldap_state =
3456 (struct ldapsam_privates *)methods->private_data;
3457 char *dn = NULL;
3458 LDAPMessage *result = NULL;
3459 LDAPMessage *entry = NULL;
3460 int count;
3461 LDAPMod **mods = NULL;
3462 int rc;
3463 enum lsa_SidType type = SID_NAME_USE_NONE;
3464 fstring tmp;
3466 char *filter = NULL;
3468 if (sid_check_is_in_builtin(alias)) {
3469 type = SID_NAME_ALIAS;
3472 if (sid_check_is_in_our_sam(alias)) {
3473 type = SID_NAME_ALIAS;
3476 if (type == SID_NAME_USE_NONE) {
3477 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3478 sid_string_dbg(alias)));
3479 return NT_STATUS_NO_SUCH_ALIAS;
3482 if (asprintf(&filter,
3483 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3484 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3485 type) < 0) {
3486 return NT_STATUS_NO_MEMORY;
3489 if (ldapsam_search_one_group(ldap_state, filter,
3490 &result) != LDAP_SUCCESS) {
3491 SAFE_FREE(filter);
3492 return NT_STATUS_NO_SUCH_ALIAS;
3495 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3496 result);
3498 if (count < 1) {
3499 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3500 ldap_msgfree(result);
3501 SAFE_FREE(filter);
3502 return NT_STATUS_NO_SUCH_ALIAS;
3505 if (count > 1) {
3506 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3507 "filter %s: count=%d\n", filter, count));
3508 ldap_msgfree(result);
3509 SAFE_FREE(filter);
3510 return NT_STATUS_NO_SUCH_ALIAS;
3513 SAFE_FREE(filter);
3515 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3516 result);
3518 if (!entry) {
3519 ldap_msgfree(result);
3520 return NT_STATUS_UNSUCCESSFUL;
3523 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3524 if (!dn) {
3525 ldap_msgfree(result);
3526 return NT_STATUS_UNSUCCESSFUL;
3529 smbldap_set_mod(&mods, modop,
3530 get_attr_key2string(groupmap_attr_list,
3531 LDAP_ATTR_SID_LIST),
3532 sid_to_fstring(tmp, member));
3534 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3536 ldap_mods_free(mods, True);
3537 ldap_msgfree(result);
3538 TALLOC_FREE(dn);
3540 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3541 return NT_STATUS_MEMBER_IN_ALIAS;
3544 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3545 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3548 if (rc != LDAP_SUCCESS) {
3549 return NT_STATUS_UNSUCCESSFUL;
3552 return NT_STATUS_OK;
3555 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3556 const struct dom_sid *alias,
3557 const struct dom_sid *member)
3559 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3562 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3563 const struct dom_sid *alias,
3564 const struct dom_sid *member)
3566 return ldapsam_modify_aliasmem(methods, alias, member,
3567 LDAP_MOD_DELETE);
3570 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3571 const struct dom_sid *alias,
3572 TALLOC_CTX *mem_ctx,
3573 struct dom_sid **pp_members,
3574 size_t *p_num_members)
3576 struct ldapsam_privates *ldap_state =
3577 (struct ldapsam_privates *)methods->private_data;
3578 LDAPMessage *result = NULL;
3579 LDAPMessage *entry = NULL;
3580 int count;
3581 char **values = NULL;
3582 int i;
3583 char *filter = NULL;
3584 uint32_t num_members = 0;
3585 enum lsa_SidType type = SID_NAME_USE_NONE;
3586 fstring tmp;
3588 *pp_members = NULL;
3589 *p_num_members = 0;
3591 if (sid_check_is_in_builtin(alias)) {
3592 type = SID_NAME_ALIAS;
3595 if (sid_check_is_in_our_sam(alias)) {
3596 type = SID_NAME_ALIAS;
3599 if (type == SID_NAME_USE_NONE) {
3600 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3601 sid_string_dbg(alias)));
3602 return NT_STATUS_NO_SUCH_ALIAS;
3605 if (asprintf(&filter,
3606 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3607 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3608 type) < 0) {
3609 return NT_STATUS_NO_MEMORY;
3612 if (ldapsam_search_one_group(ldap_state, filter,
3613 &result) != LDAP_SUCCESS) {
3614 SAFE_FREE(filter);
3615 return NT_STATUS_NO_SUCH_ALIAS;
3618 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3619 result);
3621 if (count < 1) {
3622 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3623 ldap_msgfree(result);
3624 SAFE_FREE(filter);
3625 return NT_STATUS_NO_SUCH_ALIAS;
3628 if (count > 1) {
3629 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3630 "filter %s: count=%d\n", filter, count));
3631 ldap_msgfree(result);
3632 SAFE_FREE(filter);
3633 return NT_STATUS_NO_SUCH_ALIAS;
3636 SAFE_FREE(filter);
3638 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3639 result);
3641 if (!entry) {
3642 ldap_msgfree(result);
3643 return NT_STATUS_UNSUCCESSFUL;
3646 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3647 entry,
3648 get_attr_key2string(groupmap_attr_list,
3649 LDAP_ATTR_SID_LIST));
3651 if (values == NULL) {
3652 ldap_msgfree(result);
3653 return NT_STATUS_OK;
3656 count = ldap_count_values(values);
3658 for (i=0; i<count; i++) {
3659 struct dom_sid member;
3660 NTSTATUS status;
3662 if (!string_to_sid(&member, values[i]))
3663 continue;
3665 status = add_sid_to_array(mem_ctx, &member, pp_members,
3666 &num_members);
3667 if (!NT_STATUS_IS_OK(status)) {
3668 ldap_value_free(values);
3669 ldap_msgfree(result);
3670 return status;
3674 *p_num_members = num_members;
3675 ldap_value_free(values);
3676 ldap_msgfree(result);
3678 return NT_STATUS_OK;
3681 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3682 TALLOC_CTX *mem_ctx,
3683 const struct dom_sid *domain_sid,
3684 const struct dom_sid *members,
3685 size_t num_members,
3686 uint32_t **pp_alias_rids,
3687 size_t *p_num_alias_rids)
3689 struct ldapsam_privates *ldap_state =
3690 (struct ldapsam_privates *)methods->private_data;
3691 LDAP *ldap_struct;
3693 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3695 LDAPMessage *result = NULL;
3696 LDAPMessage *entry = NULL;
3697 int i;
3698 int rc;
3699 char *filter;
3700 enum lsa_SidType type = SID_NAME_USE_NONE;
3701 bool is_builtin = false;
3702 bool sid_added = false;
3704 *pp_alias_rids = NULL;
3705 *p_num_alias_rids = 0;
3707 if (sid_check_is_builtin(domain_sid)) {
3708 is_builtin = true;
3709 type = SID_NAME_ALIAS;
3712 if (sid_check_is_our_sam(domain_sid)) {
3713 type = SID_NAME_ALIAS;
3716 if (type == SID_NAME_USE_NONE) {
3717 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3718 sid_string_dbg(domain_sid)));
3719 return NT_STATUS_UNSUCCESSFUL;
3722 if (num_members == 0) {
3723 return NT_STATUS_OK;
3726 filter = talloc_asprintf(mem_ctx,
3727 "(&(objectclass=%s)(sambaGroupType=%d)(|",
3728 LDAP_OBJ_GROUPMAP, type);
3730 for (i=0; i<num_members; i++)
3731 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3732 filter,
3733 sid_string_talloc(mem_ctx,
3734 &members[i]));
3736 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3738 if (filter == NULL) {
3739 return NT_STATUS_NO_MEMORY;
3742 if (is_builtin &&
3743 ldap_state->search_cache.filter &&
3744 strcmp(ldap_state->search_cache.filter, filter) == 0) {
3745 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3746 result = ldap_state->search_cache.result;
3747 ldap_state->search_cache.result = NULL;
3748 } else {
3749 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3750 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3751 if (rc != LDAP_SUCCESS) {
3752 return NT_STATUS_UNSUCCESSFUL;
3754 smbldap_talloc_autofree_ldapmsg(filter, result);
3757 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3759 for (entry = ldap_first_entry(ldap_struct, result);
3760 entry != NULL;
3761 entry = ldap_next_entry(ldap_struct, entry))
3763 fstring sid_str;
3764 struct dom_sid sid;
3765 uint32_t rid;
3767 if (!smbldap_get_single_attribute(ldap_struct, entry,
3768 LDAP_ATTRIBUTE_SID,
3769 sid_str,
3770 sizeof(sid_str)-1))
3771 continue;
3773 if (!string_to_sid(&sid, sid_str))
3774 continue;
3776 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3777 continue;
3779 sid_added = true;
3781 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3782 p_num_alias_rids)) {
3783 return NT_STATUS_NO_MEMORY;
3787 if (!is_builtin && !sid_added) {
3788 TALLOC_FREE(ldap_state->search_cache.filter);
3790 * Note: result is a talloc child of filter because of the
3791 * smbldap_talloc_autofree_ldapmsg() usage
3793 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3794 ldap_state->search_cache.result = result;
3797 return NT_STATUS_OK;
3800 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3801 enum pdb_policy_type type,
3802 uint32_t value)
3804 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3805 int rc;
3806 LDAPMod **mods = NULL;
3807 fstring value_string;
3808 const char *policy_attr = NULL;
3810 struct ldapsam_privates *ldap_state =
3811 (struct ldapsam_privates *)methods->private_data;
3813 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3815 if (!ldap_state->domain_dn) {
3816 return NT_STATUS_INVALID_PARAMETER;
3819 policy_attr = get_account_policy_attr(type);
3820 if (policy_attr == NULL) {
3821 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3822 "policy\n"));
3823 return ntstatus;
3826 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3828 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3830 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3831 mods);
3833 ldap_mods_free(mods, True);
3835 if (rc != LDAP_SUCCESS) {
3836 return ntstatus;
3839 if (!cache_account_policy_set(type, value)) {
3840 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3841 "update local tdb cache\n"));
3842 return ntstatus;
3845 return NT_STATUS_OK;
3848 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3849 enum pdb_policy_type type,
3850 uint32_t value)
3852 return ldapsam_set_account_policy_in_ldap(methods, type,
3853 value);
3856 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3857 enum pdb_policy_type type,
3858 uint32_t *value)
3860 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3861 LDAPMessage *result = NULL;
3862 LDAPMessage *entry = NULL;
3863 int count;
3864 int rc;
3865 char **vals = NULL;
3866 char *filter;
3867 const char *policy_attr = NULL;
3869 struct ldapsam_privates *ldap_state =
3870 (struct ldapsam_privates *)methods->private_data;
3872 const char *attrs[2];
3874 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3876 if (!ldap_state->domain_dn) {
3877 return NT_STATUS_INVALID_PARAMETER;
3880 policy_attr = get_account_policy_attr(type);
3881 if (!policy_attr) {
3882 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3883 "policy index: %d\n", type));
3884 return ntstatus;
3887 attrs[0] = policy_attr;
3888 attrs[1] = NULL;
3890 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3891 if (filter == NULL) {
3892 return NT_STATUS_NO_MEMORY;
3894 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3895 LDAP_SCOPE_BASE, filter, attrs, 0,
3896 &result);
3897 TALLOC_FREE(filter);
3898 if (rc != LDAP_SUCCESS) {
3899 return ntstatus;
3902 count = ldap_count_entries(priv2ld(ldap_state), result);
3903 if (count < 1) {
3904 goto out;
3907 entry = ldap_first_entry(priv2ld(ldap_state), result);
3908 if (entry == NULL) {
3909 goto out;
3912 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3913 if (vals == NULL) {
3914 goto out;
3917 *value = (uint32_t)atol(vals[0]);
3919 ntstatus = NT_STATUS_OK;
3921 out:
3922 if (vals)
3923 ldap_value_free(vals);
3924 ldap_msgfree(result);
3926 return ntstatus;
3929 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3931 - if user hasn't decided to use account policies inside LDAP just reuse the
3932 old tdb values
3934 - if there is a valid cache entry, return that
3935 - if there is an LDAP entry, update cache and return
3936 - otherwise set to default, update cache and return
3938 Guenther
3940 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3941 enum pdb_policy_type type,
3942 uint32_t *value)
3944 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3946 if (cache_account_policy_get(type, value)) {
3947 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3948 "cache\n"));
3949 return NT_STATUS_OK;
3952 ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3953 value);
3954 if (NT_STATUS_IS_OK(ntstatus)) {
3955 goto update_cache;
3958 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3959 "ldap\n"));
3961 #if 0
3962 /* should we automagically migrate old tdb value here ? */
3963 if (account_policy_get(type, value))
3964 goto update_ldap;
3966 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3967 "default\n", type));
3968 #endif
3970 if (!account_policy_get_default(type, value)) {
3971 return ntstatus;
3974 /* update_ldap: */
3976 ntstatus = ldapsam_set_account_policy(methods, type, *value);
3977 if (!NT_STATUS_IS_OK(ntstatus)) {
3978 return ntstatus;
3981 update_cache:
3983 if (!cache_account_policy_set(type, *value)) {
3984 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3985 "tdb as a cache\n"));
3986 return NT_STATUS_UNSUCCESSFUL;
3989 return NT_STATUS_OK;
3992 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3993 const struct dom_sid *domain_sid,
3994 int num_rids,
3995 uint32_t *rids,
3996 const char **names,
3997 enum lsa_SidType *attrs)
3999 struct ldapsam_privates *ldap_state =
4000 (struct ldapsam_privates *)methods->private_data;
4001 LDAPMessage *msg = NULL;
4002 LDAPMessage *entry;
4003 char *allsids = NULL;
4004 int i, rc, num_mapped;
4005 NTSTATUS result = NT_STATUS_NO_MEMORY;
4006 TALLOC_CTX *mem_ctx;
4007 LDAP *ld;
4008 bool is_builtin;
4010 mem_ctx = talloc_new(NULL);
4011 if (mem_ctx == NULL) {
4012 DEBUG(0, ("talloc_new failed\n"));
4013 goto done;
4016 if (!sid_check_is_builtin(domain_sid) &&
4017 !sid_check_is_our_sam(domain_sid)) {
4018 result = NT_STATUS_INVALID_PARAMETER;
4019 goto done;
4022 if (num_rids == 0) {
4023 result = NT_STATUS_NONE_MAPPED;
4024 goto done;
4027 for (i=0; i<num_rids; i++)
4028 attrs[i] = SID_NAME_UNKNOWN;
4030 allsids = talloc_strdup(mem_ctx, "");
4031 if (allsids == NULL) {
4032 goto done;
4035 for (i=0; i<num_rids; i++) {
4036 struct dom_sid sid;
4037 sid_compose(&sid, domain_sid, rids[i]);
4038 allsids = talloc_asprintf_append_buffer(
4039 allsids, "(sambaSid=%s)",
4040 sid_string_talloc(mem_ctx, &sid));
4041 if (allsids == NULL) {
4042 goto done;
4046 /* First look for users */
4049 char *filter;
4050 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4052 filter = talloc_asprintf(
4053 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4054 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4056 if (filter == NULL) {
4057 goto done;
4060 rc = smbldap_search(ldap_state->smbldap_state,
4061 lp_ldap_user_suffix(talloc_tos()),
4062 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4063 &msg);
4064 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4067 if (rc != LDAP_SUCCESS)
4068 goto done;
4070 ld = ldap_state->smbldap_state->ldap_struct;
4071 num_mapped = 0;
4073 for (entry = ldap_first_entry(ld, msg);
4074 entry != NULL;
4075 entry = ldap_next_entry(ld, entry)) {
4076 uint32_t rid;
4077 int rid_index;
4078 const char *name;
4080 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4081 &rid)) {
4082 DEBUG(2, ("Could not find sid from ldap entry\n"));
4083 continue;
4086 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4087 names);
4088 if (name == NULL) {
4089 DEBUG(2, ("Could not retrieve uid attribute\n"));
4090 continue;
4093 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4094 if (rid == rids[rid_index])
4095 break;
4098 if (rid_index == num_rids) {
4099 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4100 continue;
4103 attrs[rid_index] = SID_NAME_USER;
4104 names[rid_index] = name;
4105 num_mapped += 1;
4108 if (num_mapped == num_rids) {
4109 /* No need to look for groups anymore -- we're done */
4110 result = NT_STATUS_OK;
4111 goto done;
4114 /* Same game for groups */
4117 char *filter;
4118 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4119 "sambaGroupType", NULL };
4121 filter = talloc_asprintf(
4122 mem_ctx, "(&(objectClass=%s)(|%s))",
4123 LDAP_OBJ_GROUPMAP, allsids);
4124 if (filter == NULL) {
4125 goto done;
4128 rc = smbldap_search(ldap_state->smbldap_state,
4129 lp_ldap_suffix(talloc_tos()),
4130 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4131 &msg);
4132 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4135 if (rc != LDAP_SUCCESS)
4136 goto done;
4138 /* ldap_struct might have changed due to a reconnect */
4140 ld = ldap_state->smbldap_state->ldap_struct;
4142 /* For consistency checks, we already checked we're only domain or builtin */
4144 is_builtin = sid_check_is_builtin(domain_sid);
4146 for (entry = ldap_first_entry(ld, msg);
4147 entry != NULL;
4148 entry = ldap_next_entry(ld, entry))
4150 uint32_t rid;
4151 int rid_index;
4152 const char *attr;
4153 enum lsa_SidType type;
4154 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4156 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4157 mem_ctx);
4158 if (attr == NULL) {
4159 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4160 dn));
4161 continue;
4164 type = (enum lsa_SidType)atol(attr);
4166 /* Consistency checks */
4167 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4168 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4169 (type != SID_NAME_DOM_GRP)))) {
4170 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4173 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4174 &rid)) {
4175 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4176 continue;
4179 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4181 if (attr == NULL) {
4182 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4183 dn));
4184 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4187 if (attr == NULL) {
4188 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4189 dn));
4190 continue;
4193 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4194 if (rid == rids[rid_index])
4195 break;
4198 if (rid_index == num_rids) {
4199 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4200 continue;
4203 attrs[rid_index] = type;
4204 names[rid_index] = attr;
4205 num_mapped += 1;
4208 result = NT_STATUS_NONE_MAPPED;
4210 if (num_mapped > 0)
4211 result = (num_mapped == num_rids) ?
4212 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4213 done:
4214 TALLOC_FREE(mem_ctx);
4215 return result;
4218 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4220 char *filter = NULL;
4221 char *escaped = NULL;
4222 char *result = NULL;
4224 if (asprintf(&filter, "(&%s(objectclass=%s))",
4225 "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4226 goto done;
4229 escaped = escape_ldap_string(talloc_tos(), username);
4230 if (escaped == NULL) goto done;
4232 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4234 done:
4235 SAFE_FREE(filter);
4236 TALLOC_FREE(escaped);
4238 return result;
4241 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4243 int i, num = 0;
4244 va_list ap;
4245 const char **result;
4247 va_start(ap, mem_ctx);
4248 while (va_arg(ap, const char *) != NULL)
4249 num += 1;
4250 va_end(ap);
4252 if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4253 return NULL;
4256 va_start(ap, mem_ctx);
4257 for (i=0; i<num; i++) {
4258 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4259 if (result[i] == NULL) {
4260 talloc_free(result);
4261 va_end(ap);
4262 return NULL;
4265 va_end(ap);
4267 result[num] = NULL;
4268 return result;
4271 struct ldap_search_state {
4272 struct smbldap_state *connection;
4274 uint32_t acct_flags;
4275 uint16_t group_type;
4277 const char *base;
4278 int scope;
4279 const char *filter;
4280 const char **attrs;
4281 int attrsonly;
4282 void *pagedresults_cookie;
4284 LDAPMessage *entries, *current_entry;
4285 bool (*ldap2displayentry)(struct ldap_search_state *state,
4286 TALLOC_CTX *mem_ctx,
4287 LDAP *ld, LDAPMessage *entry,
4288 struct samr_displayentry *result);
4291 static bool ldapsam_search_firstpage(struct pdb_search *search)
4293 struct ldap_search_state *state =
4294 (struct ldap_search_state *)search->private_data;
4295 LDAP *ld;
4296 int rc = LDAP_OPERATIONS_ERROR;
4298 state->entries = NULL;
4300 if (state->connection->paged_results) {
4301 rc = smbldap_search_paged(state->connection, state->base,
4302 state->scope, state->filter,
4303 state->attrs, state->attrsonly,
4304 lp_ldap_page_size(), &state->entries,
4305 &state->pagedresults_cookie);
4308 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4310 if (state->entries != NULL) {
4311 /* Left over from unsuccessful paged attempt */
4312 ldap_msgfree(state->entries);
4313 state->entries = NULL;
4316 rc = smbldap_search(state->connection, state->base,
4317 state->scope, state->filter, state->attrs,
4318 state->attrsonly, &state->entries);
4320 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4321 return False;
4323 /* Ok, the server was lying. It told us it could do paged
4324 * searches when it could not. */
4325 state->connection->paged_results = False;
4328 ld = state->connection->ldap_struct;
4329 if ( ld == NULL) {
4330 DEBUG(5, ("Don't have an LDAP connection right after a "
4331 "search\n"));
4332 return False;
4334 state->current_entry = ldap_first_entry(ld, state->entries);
4336 return True;
4339 static bool ldapsam_search_nextpage(struct pdb_search *search)
4341 struct ldap_search_state *state =
4342 (struct ldap_search_state *)search->private_data;
4343 int rc;
4345 if (!state->connection->paged_results) {
4346 /* There is no next page when there are no paged results */
4347 return False;
4350 rc = smbldap_search_paged(state->connection, state->base,
4351 state->scope, state->filter, state->attrs,
4352 state->attrsonly, lp_ldap_page_size(),
4353 &state->entries,
4354 &state->pagedresults_cookie);
4356 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4357 return False;
4359 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4361 if (state->current_entry == NULL) {
4362 ldap_msgfree(state->entries);
4363 state->entries = NULL;
4364 return false;
4367 return True;
4370 static bool ldapsam_search_next_entry(struct pdb_search *search,
4371 struct samr_displayentry *entry)
4373 struct ldap_search_state *state =
4374 (struct ldap_search_state *)search->private_data;
4375 bool result;
4377 retry:
4378 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4379 return False;
4381 if ((state->entries == NULL) &&
4382 !ldapsam_search_nextpage(search))
4383 return False;
4385 if (state->current_entry == NULL) {
4386 return false;
4389 result = state->ldap2displayentry(state, search,
4390 state->connection->ldap_struct,
4391 state->current_entry, entry);
4393 if (!result) {
4394 char *dn;
4395 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4396 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4397 if (dn != NULL) ldap_memfree(dn);
4400 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4402 if (state->current_entry == NULL) {
4403 ldap_msgfree(state->entries);
4404 state->entries = NULL;
4407 if (!result) goto retry;
4409 return True;
4412 static void ldapsam_search_end(struct pdb_search *search)
4414 struct ldap_search_state *state =
4415 (struct ldap_search_state *)search->private_data;
4416 int rc;
4418 if (state->pagedresults_cookie == NULL)
4419 return;
4421 if (state->entries != NULL)
4422 ldap_msgfree(state->entries);
4424 state->entries = NULL;
4425 state->current_entry = NULL;
4427 if (!state->connection->paged_results)
4428 return;
4430 /* Tell the LDAP server we're not interested in the rest anymore. */
4432 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4433 state->filter, state->attrs,
4434 state->attrsonly, 0, &state->entries,
4435 &state->pagedresults_cookie);
4437 if (rc != LDAP_SUCCESS)
4438 DEBUG(5, ("Could not end search properly\n"));
4440 return;
4443 static bool ldapuser2displayentry(struct ldap_search_state *state,
4444 TALLOC_CTX *mem_ctx,
4445 LDAP *ld, LDAPMessage *entry,
4446 struct samr_displayentry *result)
4448 char **vals;
4449 size_t converted_size;
4450 struct dom_sid sid;
4451 uint32_t acct_flags;
4453 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4454 if ((vals == NULL) || (vals[0] == NULL)) {
4455 acct_flags = ACB_NORMAL;
4456 } else {
4457 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4458 ldap_value_free(vals);
4461 if ((state->acct_flags != 0) &&
4462 ((state->acct_flags & acct_flags) == 0))
4463 return False;
4465 result->acct_flags = acct_flags;
4466 result->account_name = "";
4467 result->fullname = "";
4468 result->description = "";
4470 vals = ldap_get_values(ld, entry, "uid");
4471 if ((vals == NULL) || (vals[0] == NULL)) {
4472 DEBUG(5, ("\"uid\" not found\n"));
4473 return False;
4475 if (!pull_utf8_talloc(mem_ctx,
4476 discard_const_p(char *, &result->account_name),
4477 vals[0], &converted_size))
4479 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4480 strerror(errno)));
4483 ldap_value_free(vals);
4485 vals = ldap_get_values(ld, entry, "displayName");
4486 if ((vals == NULL) || (vals[0] == NULL))
4487 DEBUG(8, ("\"displayName\" not found\n"));
4488 else if (!pull_utf8_talloc(mem_ctx,
4489 discard_const_p(char *, &result->fullname),
4490 vals[0], &converted_size))
4492 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4493 strerror(errno)));
4496 ldap_value_free(vals);
4498 vals = ldap_get_values(ld, entry, "description");
4499 if ((vals == NULL) || (vals[0] == NULL))
4500 DEBUG(8, ("\"description\" not found\n"));
4501 else if (!pull_utf8_talloc(mem_ctx,
4502 discard_const_p(char *, &result->description),
4503 vals[0], &converted_size))
4505 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4506 strerror(errno)));
4509 ldap_value_free(vals);
4511 if ((result->account_name == NULL) ||
4512 (result->fullname == NULL) ||
4513 (result->description == NULL)) {
4514 DEBUG(0, ("talloc failed\n"));
4515 return False;
4518 vals = ldap_get_values(ld, entry, "sambaSid");
4519 if ((vals == NULL) || (vals[0] == NULL)) {
4520 DEBUG(0, ("\"objectSid\" not found\n"));
4521 return False;
4524 if (!string_to_sid(&sid, vals[0])) {
4525 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4526 ldap_value_free(vals);
4527 return False;
4529 ldap_value_free(vals);
4531 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4532 DEBUG(0, ("sid %s does not belong to our domain\n",
4533 sid_string_dbg(&sid)));
4534 return False;
4537 return True;
4541 static bool ldapsam_search_users(struct pdb_methods *methods,
4542 struct pdb_search *search,
4543 uint32_t acct_flags)
4545 struct ldapsam_privates *ldap_state =
4546 (struct ldapsam_privates *)methods->private_data;
4547 struct ldap_search_state *state;
4549 state = talloc(search, struct ldap_search_state);
4550 if (state == NULL) {
4551 DEBUG(0, ("talloc failed\n"));
4552 return False;
4555 state->connection = ldap_state->smbldap_state;
4557 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4558 state->base = lp_ldap_user_suffix(talloc_tos());
4559 else if ((acct_flags != 0) &&
4560 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4561 state->base = lp_ldap_machine_suffix(talloc_tos());
4562 else
4563 state->base = lp_ldap_suffix(talloc_tos());
4565 state->acct_flags = acct_flags;
4566 state->base = talloc_strdup(search, state->base);
4567 state->scope = LDAP_SCOPE_SUBTREE;
4568 state->filter = get_ldap_filter(search, "*");
4569 state->attrs = talloc_attrs(search, "uid", "sambaSid",
4570 "displayName", "description",
4571 "sambaAcctFlags", NULL);
4572 state->attrsonly = 0;
4573 state->pagedresults_cookie = NULL;
4574 state->entries = NULL;
4575 state->ldap2displayentry = ldapuser2displayentry;
4577 if ((state->filter == NULL) || (state->attrs == NULL)) {
4578 DEBUG(0, ("talloc failed\n"));
4579 return False;
4582 search->private_data = state;
4583 search->next_entry = ldapsam_search_next_entry;
4584 search->search_end = ldapsam_search_end;
4586 return ldapsam_search_firstpage(search);
4589 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4590 TALLOC_CTX *mem_ctx,
4591 LDAP *ld, LDAPMessage *entry,
4592 struct samr_displayentry *result)
4594 char **vals;
4595 size_t converted_size;
4596 struct dom_sid sid;
4597 uint16_t group_type;
4599 result->account_name = "";
4600 result->fullname = "";
4601 result->description = "";
4604 vals = ldap_get_values(ld, entry, "sambaGroupType");
4605 if ((vals == NULL) || (vals[0] == NULL)) {
4606 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4607 if (vals != NULL) {
4608 ldap_value_free(vals);
4610 return False;
4613 group_type = atoi(vals[0]);
4615 if ((state->group_type != 0) &&
4616 ((state->group_type != group_type))) {
4617 ldap_value_free(vals);
4618 return False;
4621 ldap_value_free(vals);
4623 /* display name is the NT group name */
4625 vals = ldap_get_values(ld, entry, "displayName");
4626 if ((vals == NULL) || (vals[0] == NULL)) {
4627 DEBUG(8, ("\"displayName\" not found\n"));
4629 /* fallback to the 'cn' attribute */
4630 vals = ldap_get_values(ld, entry, "cn");
4631 if ((vals == NULL) || (vals[0] == NULL)) {
4632 DEBUG(5, ("\"cn\" not found\n"));
4633 return False;
4635 if (!pull_utf8_talloc(mem_ctx,
4636 discard_const_p(char *,
4637 &result->account_name),
4638 vals[0], &converted_size))
4640 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4641 "failed: %s", strerror(errno)));
4644 else if (!pull_utf8_talloc(mem_ctx,
4645 discard_const_p(char *,
4646 &result->account_name),
4647 vals[0], &converted_size))
4649 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4650 strerror(errno)));
4653 ldap_value_free(vals);
4655 vals = ldap_get_values(ld, entry, "description");
4656 if ((vals == NULL) || (vals[0] == NULL))
4657 DEBUG(8, ("\"description\" not found\n"));
4658 else if (!pull_utf8_talloc(mem_ctx,
4659 discard_const_p(char *, &result->description),
4660 vals[0], &converted_size))
4662 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4663 strerror(errno)));
4665 ldap_value_free(vals);
4667 if ((result->account_name == NULL) ||
4668 (result->fullname == NULL) ||
4669 (result->description == NULL)) {
4670 DEBUG(0, ("talloc failed\n"));
4671 return False;
4674 vals = ldap_get_values(ld, entry, "sambaSid");
4675 if ((vals == NULL) || (vals[0] == NULL)) {
4676 DEBUG(0, ("\"objectSid\" not found\n"));
4677 if (vals != NULL) {
4678 ldap_value_free(vals);
4680 return False;
4683 if (!string_to_sid(&sid, vals[0])) {
4684 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4685 return False;
4688 ldap_value_free(vals);
4690 switch (group_type) {
4691 case SID_NAME_DOM_GRP:
4692 case SID_NAME_ALIAS:
4694 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4695 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4697 DEBUG(0, ("%s is not in our domain\n",
4698 sid_string_dbg(&sid)));
4699 return False;
4701 break;
4703 default:
4704 DEBUG(0,("unknown group type: %d\n", group_type));
4705 return False;
4708 result->acct_flags = 0;
4710 return True;
4713 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4714 struct pdb_search *search,
4715 const struct dom_sid *sid,
4716 enum lsa_SidType type)
4718 struct ldapsam_privates *ldap_state =
4719 (struct ldapsam_privates *)methods->private_data;
4720 struct ldap_search_state *state;
4721 fstring tmp;
4723 state = talloc(search, struct ldap_search_state);
4724 if (state == NULL) {
4725 DEBUG(0, ("talloc failed\n"));
4726 return False;
4729 state->connection = ldap_state->smbldap_state;
4731 state->base = lp_ldap_suffix(search);
4732 state->connection = ldap_state->smbldap_state;
4733 state->scope = LDAP_SCOPE_SUBTREE;
4734 state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4735 "(sambaGroupType=%d)(sambaSID=%s*))",
4736 LDAP_OBJ_GROUPMAP,
4737 type, sid_to_fstring(tmp, sid));
4738 state->attrs = talloc_attrs(search, "cn", "sambaSid",
4739 "displayName", "description",
4740 "sambaGroupType", NULL);
4741 state->attrsonly = 0;
4742 state->pagedresults_cookie = NULL;
4743 state->entries = NULL;
4744 state->group_type = type;
4745 state->ldap2displayentry = ldapgroup2displayentry;
4747 if ((state->filter == NULL) || (state->attrs == NULL)) {
4748 DEBUG(0, ("talloc failed\n"));
4749 return False;
4752 search->private_data = state;
4753 search->next_entry = ldapsam_search_next_entry;
4754 search->search_end = ldapsam_search_end;
4756 return ldapsam_search_firstpage(search);
4759 static bool ldapsam_search_groups(struct pdb_methods *methods,
4760 struct pdb_search *search)
4762 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4765 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4766 struct pdb_search *search,
4767 const struct dom_sid *sid)
4769 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4772 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4774 return PDB_CAP_STORE_RIDS;
4777 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4778 uint32_t *rid)
4780 struct smbldap_state *smbldap_state = priv->smbldap_state;
4782 LDAPMessage *result = NULL;
4783 LDAPMessage *entry = NULL;
4784 LDAPMod **mods = NULL;
4785 NTSTATUS status;
4786 char *value;
4787 int rc;
4788 uint32_t nextRid = 0;
4789 const char *dn;
4791 TALLOC_CTX *mem_ctx;
4793 mem_ctx = talloc_new(NULL);
4794 if (mem_ctx == NULL) {
4795 DEBUG(0, ("talloc_new failed\n"));
4796 return NT_STATUS_NO_MEMORY;
4799 status = smbldap_search_domain_info(smbldap_state, &result,
4800 get_global_sam_name(), False);
4801 if (!NT_STATUS_IS_OK(status)) {
4802 DEBUG(3, ("Could not get domain info: %s\n",
4803 nt_errstr(status)));
4804 goto done;
4807 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4809 entry = ldap_first_entry(priv2ld(priv), result);
4810 if (entry == NULL) {
4811 DEBUG(0, ("Could not get domain info entry\n"));
4812 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4813 goto done;
4816 /* Find the largest of the three attributes "sambaNextRid",
4817 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4818 concept of differentiating between user and group rids, and will
4819 use only "sambaNextRid" in the future. But for compatibility
4820 reasons I look if others have chosen different strategies -- VL */
4822 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4823 "sambaNextRid", mem_ctx);
4824 if (value != NULL) {
4825 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4826 nextRid = MAX(nextRid, tmp);
4829 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4830 "sambaNextUserRid", mem_ctx);
4831 if (value != NULL) {
4832 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4833 nextRid = MAX(nextRid, tmp);
4836 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4837 "sambaNextGroupRid", mem_ctx);
4838 if (value != NULL) {
4839 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4840 nextRid = MAX(nextRid, tmp);
4843 if (nextRid == 0) {
4844 nextRid = BASE_RID-1;
4847 nextRid += 1;
4849 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4850 talloc_asprintf(mem_ctx, "%d", nextRid));
4851 smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
4853 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4854 status = NT_STATUS_NO_MEMORY;
4855 goto done;
4858 rc = smbldap_modify(smbldap_state, dn, mods);
4860 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4861 * please retry" */
4863 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4865 done:
4866 if (NT_STATUS_IS_OK(status)) {
4867 *rid = nextRid;
4870 TALLOC_FREE(mem_ctx);
4871 return status;
4874 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4876 int i;
4878 for (i=0; i<10; i++) {
4879 NTSTATUS result = ldapsam_get_new_rid(
4880 (struct ldapsam_privates *)methods->private_data, rid);
4881 if (NT_STATUS_IS_OK(result)) {
4882 return result;
4885 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4886 return result;
4889 /* The ldap update failed (maybe a race condition), retry */
4892 /* Tried 10 times, fail. */
4893 return NT_STATUS_ACCESS_DENIED;
4896 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4898 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4899 return NT_STATUS_IS_OK(result) ? True : False;
4902 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4903 const struct dom_sid *sid,
4904 struct unixid *id)
4906 struct ldapsam_privates *priv =
4907 (struct ldapsam_privates *)methods->private_data;
4908 char *filter;
4909 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4910 NULL };
4911 LDAPMessage *result = NULL;
4912 LDAPMessage *entry = NULL;
4913 bool ret = False;
4914 char *value;
4915 int rc;
4917 TALLOC_CTX *mem_ctx;
4919 if (!sid_check_object_is_for_passdb(sid)) {
4920 return false;
4923 ret = pdb_sid_to_id_unix_users_and_groups(sid, id);
4924 if (ret == true) {
4925 return true;
4928 mem_ctx = talloc_new(NULL);
4929 if (mem_ctx == NULL) {
4930 DEBUG(0, ("talloc_new failed\n"));
4931 return False;
4934 filter = talloc_asprintf(mem_ctx,
4935 "(&(sambaSid=%s)"
4936 "(|(objectClass=%s)(objectClass=%s)))",
4937 sid_string_talloc(mem_ctx, sid),
4938 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4939 if (filter == NULL) {
4940 DEBUG(5, ("talloc_asprintf failed\n"));
4941 goto done;
4944 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4945 attrs, &result);
4946 if (rc != LDAP_SUCCESS) {
4947 goto done;
4949 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4951 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4952 DEBUG(10, ("Got %d entries, expected one\n",
4953 ldap_count_entries(priv2ld(priv), result)));
4954 goto done;
4957 entry = ldap_first_entry(priv2ld(priv), result);
4959 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4960 "sambaGroupType", mem_ctx);
4962 if (value != NULL) {
4963 const char *gid_str;
4964 /* It's a group */
4966 gid_str = smbldap_talloc_single_attribute(
4967 priv2ld(priv), entry, "gidNumber", mem_ctx);
4968 if (gid_str == NULL) {
4969 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4970 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4971 entry)));
4972 goto done;
4975 id->id = strtoul(gid_str, NULL, 10);
4976 id->type = ID_TYPE_GID;
4977 idmap_cache_set_sid2unixid(sid, id);
4978 ret = True;
4979 goto done;
4982 /* It must be a user */
4984 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4985 "uidNumber", mem_ctx);
4986 if (value == NULL) {
4987 DEBUG(1, ("Could not find uidNumber in %s\n",
4988 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4989 goto done;
4992 id->id = strtoul(value, NULL, 10);
4993 id->type = ID_TYPE_UID;
4994 idmap_cache_set_sid2unixid(sid, id);
4996 ret = True;
4997 done:
4998 TALLOC_FREE(mem_ctx);
4999 return ret;
5003 * Find the SID for a uid.
5004 * This is shortcut is only used if ldapsam:trusted is set to true.
5006 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5007 struct dom_sid *sid)
5009 struct ldapsam_privates *priv =
5010 (struct ldapsam_privates *)methods->private_data;
5011 char *filter;
5012 const char *attrs[] = { "sambaSID", NULL };
5013 LDAPMessage *result = NULL;
5014 LDAPMessage *entry = NULL;
5015 bool ret = false;
5016 char *user_sid_string;
5017 struct dom_sid user_sid;
5018 int rc;
5019 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5020 struct unixid id;
5022 filter = talloc_asprintf(tmp_ctx,
5023 "(&(uidNumber=%u)"
5024 "(objectClass=%s)"
5025 "(objectClass=%s))",
5026 (unsigned int)uid,
5027 LDAP_OBJ_POSIXACCOUNT,
5028 LDAP_OBJ_SAMBASAMACCOUNT);
5029 if (filter == NULL) {
5030 DEBUG(3, ("talloc_asprintf failed\n"));
5031 goto done;
5034 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5035 if (rc != LDAP_SUCCESS) {
5036 goto done;
5038 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5040 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5041 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5042 ldap_count_entries(priv2ld(priv), result),
5043 (unsigned int)uid));
5044 goto done;
5047 entry = ldap_first_entry(priv2ld(priv), result);
5049 user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5050 "sambaSID", tmp_ctx);
5051 if (user_sid_string == NULL) {
5052 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5053 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5054 goto done;
5057 if (!string_to_sid(&user_sid, user_sid_string)) {
5058 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5059 user_sid_string));
5060 goto done;
5063 sid_copy(sid, &user_sid);
5065 id.id = uid;
5066 id.type = ID_TYPE_UID;
5068 idmap_cache_set_sid2unixid(sid, &id);
5070 ret = true;
5072 done:
5073 TALLOC_FREE(tmp_ctx);
5074 return ret;
5078 * Find the SID for a gid.
5079 * This is shortcut is only used if ldapsam:trusted is set to true.
5081 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5082 struct dom_sid *sid)
5084 struct ldapsam_privates *priv =
5085 (struct ldapsam_privates *)methods->private_data;
5086 char *filter;
5087 const char *attrs[] = { "sambaSID", NULL };
5088 LDAPMessage *result = NULL;
5089 LDAPMessage *entry = NULL;
5090 bool ret = false;
5091 char *group_sid_string;
5092 struct dom_sid group_sid;
5093 int rc;
5094 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5095 struct unixid id;
5097 filter = talloc_asprintf(tmp_ctx,
5098 "(&(gidNumber=%u)"
5099 "(objectClass=%s))",
5100 (unsigned int)gid,
5101 LDAP_OBJ_GROUPMAP);
5102 if (filter == NULL) {
5103 DEBUG(3, ("talloc_asprintf failed\n"));
5104 goto done;
5107 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5108 if (rc != LDAP_SUCCESS) {
5109 goto done;
5111 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5113 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5114 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5115 ldap_count_entries(priv2ld(priv), result),
5116 (unsigned int)gid));
5117 goto done;
5120 entry = ldap_first_entry(priv2ld(priv), result);
5122 group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5123 "sambaSID", tmp_ctx);
5124 if (group_sid_string == NULL) {
5125 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5126 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5127 goto done;
5130 if (!string_to_sid(&group_sid, group_sid_string)) {
5131 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5132 group_sid_string));
5133 goto done;
5136 sid_copy(sid, &group_sid);
5138 id.id = gid;
5139 id.type = ID_TYPE_GID;
5141 idmap_cache_set_sid2unixid(sid, &id);
5143 ret = true;
5145 done:
5146 TALLOC_FREE(tmp_ctx);
5147 return ret;
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 LDAPMod **mods = NULL;
5176 struct samu *user;
5177 char *filter;
5178 char *username;
5179 char *homedir;
5180 char *gidstr;
5181 char *uidstr;
5182 char *shell;
5183 const char *dn = NULL;
5184 struct dom_sid group_sid;
5185 struct dom_sid user_sid;
5186 gid_t gid = -1;
5187 uid_t uid = -1;
5188 NTSTATUS ret;
5189 int rc;
5191 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5192 acb_info & ACB_WSTRUST ||
5193 acb_info & ACB_SVRTRUST ||
5194 acb_info & ACB_DOMTRUST) {
5195 is_machine = True;
5198 username = escape_ldap_string(talloc_tos(), name);
5199 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5200 username, LDAP_OBJ_POSIXACCOUNT);
5201 TALLOC_FREE(username);
5203 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5204 if (rc != LDAP_SUCCESS) {
5205 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5206 return NT_STATUS_ACCESS_DENIED;
5208 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5210 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5212 if (num_result > 1) {
5213 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5214 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5217 if (num_result == 1) {
5218 char *tmp;
5219 /* check if it is just a posix account.
5220 * or if there is a sid attached to this entry
5223 entry = ldap_first_entry(priv2ld(ldap_state), result);
5224 if (!entry) {
5225 return NT_STATUS_UNSUCCESSFUL;
5228 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5229 if (tmp) {
5230 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5231 return NT_STATUS_USER_EXISTS;
5234 /* it is just a posix account, retrieve the dn for later use */
5235 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5236 if (!dn) {
5237 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5238 return NT_STATUS_NO_MEMORY;
5242 if (num_result == 0) {
5243 add_posix = True;
5246 /* Create the basic samu structure and generate the mods for the ldap commit */
5247 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5248 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5249 return ret;
5252 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5254 user = samu_new(tmp_ctx);
5255 if (!user) {
5256 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5257 return NT_STATUS_NO_MEMORY;
5260 if (!pdb_set_username(user, name, PDB_SET)) {
5261 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5262 return NT_STATUS_UNSUCCESSFUL;
5264 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5265 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5266 return NT_STATUS_UNSUCCESSFUL;
5268 if (is_machine) {
5269 if (acb_info & ACB_NORMAL) {
5270 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5271 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5272 return NT_STATUS_UNSUCCESSFUL;
5274 } else {
5275 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5276 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5277 return NT_STATUS_UNSUCCESSFUL;
5280 } else {
5281 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5282 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5283 return NT_STATUS_UNSUCCESSFUL;
5287 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5288 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5289 return NT_STATUS_UNSUCCESSFUL;
5292 if (!init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed)) {
5293 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5294 return NT_STATUS_UNSUCCESSFUL;
5297 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5298 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5300 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5302 if (add_posix) {
5303 char *escape_name;
5305 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5307 /* retrieve the Domain Users group gid */
5308 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5309 !sid_to_gid(&group_sid, &gid)) {
5310 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5311 return NT_STATUS_INVALID_PRIMARY_GROUP;
5314 /* lets allocate a new userid for this user */
5315 if (!winbind_allocate_uid(&uid)) {
5316 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5317 return NT_STATUS_UNSUCCESSFUL;
5321 if (is_machine) {
5322 /* TODO: choose a more appropriate default for machines */
5323 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5324 shell = talloc_strdup(tmp_ctx, "/bin/false");
5325 } else {
5326 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5327 shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5329 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5330 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5332 escape_name = escape_rdn_val_string_alloc(name);
5333 if (!escape_name) {
5334 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5335 return NT_STATUS_NO_MEMORY;
5338 if (is_machine) {
5339 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
5340 } else {
5341 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
5344 SAFE_FREE(escape_name);
5346 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5347 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5348 return NT_STATUS_NO_MEMORY;
5351 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5352 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5353 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5354 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5355 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5356 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5357 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5360 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5362 if (add_posix) {
5363 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5364 } else {
5365 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5368 if (rc != LDAP_SUCCESS) {
5369 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5370 return NT_STATUS_UNSUCCESSFUL;
5373 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5375 flush_pwnam_cache();
5377 return NT_STATUS_OK;
5380 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5382 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5383 LDAPMessage *result = NULL;
5384 LDAPMessage *entry = NULL;
5385 int num_result;
5386 const char *dn;
5387 char *filter;
5388 int rc;
5390 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5392 filter = talloc_asprintf(tmp_ctx,
5393 "(&(uid=%s)"
5394 "(objectClass=%s)"
5395 "(objectClass=%s))",
5396 pdb_get_username(sam_acct),
5397 LDAP_OBJ_POSIXACCOUNT,
5398 LDAP_OBJ_SAMBASAMACCOUNT);
5399 if (filter == NULL) {
5400 return NT_STATUS_NO_MEMORY;
5403 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5404 if (rc != LDAP_SUCCESS) {
5405 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5406 return NT_STATUS_UNSUCCESSFUL;
5408 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5410 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5412 if (num_result == 0) {
5413 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5414 return NT_STATUS_NO_SUCH_USER;
5417 if (num_result > 1) {
5418 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5419 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5422 entry = ldap_first_entry(priv2ld(ldap_state), result);
5423 if (!entry) {
5424 return NT_STATUS_UNSUCCESSFUL;
5427 /* it is just a posix account, retrieve the dn for later use */
5428 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5429 if (!dn) {
5430 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5431 return NT_STATUS_NO_MEMORY;
5434 /* try to remove memberships first */
5436 NTSTATUS status;
5437 struct dom_sid *sids = NULL;
5438 gid_t *gids = NULL;
5439 uint32_t num_groups = 0;
5440 int i;
5441 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5443 status = ldapsam_enum_group_memberships(my_methods,
5444 tmp_ctx,
5445 sam_acct,
5446 &sids,
5447 &gids,
5448 &num_groups);
5449 if (!NT_STATUS_IS_OK(status)) {
5450 goto delete_dn;
5453 for (i=0; i < num_groups; i++) {
5455 uint32_t group_rid;
5457 sid_peek_rid(&sids[i], &group_rid);
5459 ldapsam_del_groupmem(my_methods,
5460 tmp_ctx,
5461 group_rid,
5462 user_rid);
5466 delete_dn:
5468 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5469 if (rc != LDAP_SUCCESS) {
5470 return NT_STATUS_UNSUCCESSFUL;
5473 flush_pwnam_cache();
5475 return NT_STATUS_OK;
5479 * ldapsam_create_group creates a new
5480 * posixGroup and sambaGroupMapping object
5481 * in the ldap groups subtree
5483 * The gid is allocated by winbindd.
5486 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5487 TALLOC_CTX *tmp_ctx,
5488 const char *name,
5489 uint32_t *rid)
5491 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5492 NTSTATUS ret;
5493 LDAPMessage *entry = NULL;
5494 LDAPMessage *result = NULL;
5495 uint32_t num_result;
5496 bool is_new_entry = False;
5497 LDAPMod **mods = NULL;
5498 char *filter;
5499 char *groupsidstr;
5500 char *groupname;
5501 char *grouptype;
5502 char *gidstr;
5503 const char *dn = NULL;
5504 struct dom_sid group_sid;
5505 gid_t gid = -1;
5506 int rc;
5508 groupname = escape_ldap_string(talloc_tos(), name);
5509 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5510 groupname, LDAP_OBJ_POSIXGROUP);
5511 TALLOC_FREE(groupname);
5513 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5514 if (rc != LDAP_SUCCESS) {
5515 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5516 return NT_STATUS_UNSUCCESSFUL;
5518 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5520 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5522 if (num_result > 1) {
5523 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5524 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5527 if (num_result == 1) {
5528 char *tmp;
5529 /* check if it is just a posix group.
5530 * or if there is a sid attached to this entry
5533 entry = ldap_first_entry(priv2ld(ldap_state), result);
5534 if (!entry) {
5535 return NT_STATUS_UNSUCCESSFUL;
5538 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5539 if (tmp) {
5540 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5541 return NT_STATUS_GROUP_EXISTS;
5544 /* it is just a posix group, retrieve the gid and the dn for later use */
5545 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5546 if (!tmp) {
5547 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5548 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5551 gid = strtoul(tmp, NULL, 10);
5553 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5554 if (!dn) {
5555 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5556 return NT_STATUS_NO_MEMORY;
5560 if (num_result == 0) {
5561 is_new_entry = true;
5564 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5565 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5566 return ret;
5569 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5571 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5572 &group_sid));
5573 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5575 if (!groupsidstr || !grouptype) {
5576 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5577 return NT_STATUS_NO_MEMORY;
5580 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5581 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5582 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5583 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5585 if (is_new_entry) {
5586 char *escape_name;
5588 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5590 /* lets allocate a new groupid for this group */
5591 if (!winbind_allocate_gid(&gid)) {
5592 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5593 return NT_STATUS_UNSUCCESSFUL;
5596 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5598 escape_name = escape_rdn_val_string_alloc(name);
5599 if (!escape_name) {
5600 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5601 return NT_STATUS_NO_MEMORY;
5604 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
5606 SAFE_FREE(escape_name);
5608 if (!gidstr || !dn) {
5609 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5610 return NT_STATUS_NO_MEMORY;
5613 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5614 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5615 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5618 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5620 if (is_new_entry) {
5621 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5622 #if 0
5623 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5624 /* This call may fail with rfc2307bis schema */
5625 /* Retry adding a structural class */
5626 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5627 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5629 #endif
5630 } else {
5631 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5634 if (rc != LDAP_SUCCESS) {
5635 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5636 return NT_STATUS_UNSUCCESSFUL;
5639 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5641 return NT_STATUS_OK;
5644 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5646 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5647 LDAPMessage *result = NULL;
5648 LDAPMessage *entry = NULL;
5649 int num_result;
5650 const char *dn;
5651 char *gidstr;
5652 char *filter;
5653 struct dom_sid group_sid;
5654 int rc;
5656 /* get the group sid */
5657 sid_compose(&group_sid, get_global_sam_sid(), rid);
5659 filter = talloc_asprintf(tmp_ctx,
5660 "(&(sambaSID=%s)"
5661 "(objectClass=%s)"
5662 "(objectClass=%s))",
5663 sid_string_talloc(tmp_ctx, &group_sid),
5664 LDAP_OBJ_POSIXGROUP,
5665 LDAP_OBJ_GROUPMAP);
5666 if (filter == NULL) {
5667 return NT_STATUS_NO_MEMORY;
5670 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5671 if (rc != LDAP_SUCCESS) {
5672 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5673 return NT_STATUS_UNSUCCESSFUL;
5675 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5677 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5679 if (num_result == 0) {
5680 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5681 return NT_STATUS_NO_SUCH_GROUP;
5684 if (num_result > 1) {
5685 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5686 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5689 entry = ldap_first_entry(priv2ld(ldap_state), result);
5690 if (!entry) {
5691 return NT_STATUS_UNSUCCESSFUL;
5694 /* here it is, retrieve the dn for later use */
5695 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5696 if (!dn) {
5697 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5698 return NT_STATUS_NO_MEMORY;
5701 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5702 if (!gidstr) {
5703 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5704 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5707 /* check no user have this group marked as primary group */
5708 filter = talloc_asprintf(tmp_ctx,
5709 "(&(gidNumber=%s)"
5710 "(objectClass=%s)"
5711 "(objectClass=%s))",
5712 gidstr,
5713 LDAP_OBJ_POSIXACCOUNT,
5714 LDAP_OBJ_SAMBASAMACCOUNT);
5716 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5717 if (rc != LDAP_SUCCESS) {
5718 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5719 return NT_STATUS_UNSUCCESSFUL;
5721 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5723 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5725 if (num_result != 0) {
5726 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5727 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5730 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5731 if (rc != LDAP_SUCCESS) {
5732 return NT_STATUS_UNSUCCESSFUL;
5735 return NT_STATUS_OK;
5738 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5739 TALLOC_CTX *tmp_ctx,
5740 uint32_t group_rid,
5741 uint32_t member_rid,
5742 int modop)
5744 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5745 LDAPMessage *entry = NULL;
5746 LDAPMessage *result = NULL;
5747 uint32_t num_result;
5748 LDAPMod **mods = NULL;
5749 char *filter;
5750 char *uidstr;
5751 const char *dn = NULL;
5752 struct dom_sid group_sid;
5753 struct dom_sid member_sid;
5754 int rc;
5756 switch (modop) {
5757 case LDAP_MOD_ADD:
5758 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5759 break;
5760 case LDAP_MOD_DELETE:
5761 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5762 break;
5763 default:
5764 return NT_STATUS_UNSUCCESSFUL;
5767 /* get member sid */
5768 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5770 /* get the group sid */
5771 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5773 filter = talloc_asprintf(tmp_ctx,
5774 "(&(sambaSID=%s)"
5775 "(objectClass=%s)"
5776 "(objectClass=%s))",
5777 sid_string_talloc(tmp_ctx, &member_sid),
5778 LDAP_OBJ_POSIXACCOUNT,
5779 LDAP_OBJ_SAMBASAMACCOUNT);
5780 if (filter == NULL) {
5781 return NT_STATUS_NO_MEMORY;
5784 /* get the member uid */
5785 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5786 if (rc != LDAP_SUCCESS) {
5787 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5788 return NT_STATUS_UNSUCCESSFUL;
5790 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5792 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5794 if (num_result == 0) {
5795 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5796 return NT_STATUS_NO_SUCH_MEMBER;
5799 if (num_result > 1) {
5800 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5801 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5804 entry = ldap_first_entry(priv2ld(ldap_state), result);
5805 if (!entry) {
5806 return NT_STATUS_UNSUCCESSFUL;
5809 if (modop == LDAP_MOD_DELETE) {
5810 /* check if we are trying to remove the member from his primary group */
5811 char *gidstr;
5812 gid_t user_gid, group_gid;
5814 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5815 if (!gidstr) {
5816 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5817 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5820 user_gid = strtoul(gidstr, NULL, 10);
5822 if (!sid_to_gid(&group_sid, &group_gid)) {
5823 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5824 return NT_STATUS_UNSUCCESSFUL;
5827 if (user_gid == group_gid) {
5828 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5829 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5833 /* here it is, retrieve the uid for later use */
5834 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5835 if (!uidstr) {
5836 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5837 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5840 filter = talloc_asprintf(tmp_ctx,
5841 "(&(sambaSID=%s)"
5842 "(objectClass=%s)"
5843 "(objectClass=%s))",
5844 sid_string_talloc(tmp_ctx, &group_sid),
5845 LDAP_OBJ_POSIXGROUP,
5846 LDAP_OBJ_GROUPMAP);
5848 /* get the group */
5849 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5850 if (rc != LDAP_SUCCESS) {
5851 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5852 return NT_STATUS_UNSUCCESSFUL;
5854 smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5856 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5858 if (num_result == 0) {
5859 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5860 return NT_STATUS_NO_SUCH_GROUP;
5863 if (num_result > 1) {
5864 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5865 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5868 entry = ldap_first_entry(priv2ld(ldap_state), result);
5869 if (!entry) {
5870 return NT_STATUS_UNSUCCESSFUL;
5873 /* here it is, retrieve the dn for later use */
5874 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5875 if (!dn) {
5876 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5877 return NT_STATUS_NO_MEMORY;
5880 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5882 smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5884 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5885 if (rc != LDAP_SUCCESS) {
5886 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5887 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5888 return NT_STATUS_MEMBER_IN_GROUP;
5890 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5891 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5892 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5894 return NT_STATUS_UNSUCCESSFUL;
5897 return NT_STATUS_OK;
5900 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5901 TALLOC_CTX *tmp_ctx,
5902 uint32_t group_rid,
5903 uint32_t member_rid)
5905 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5907 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5908 TALLOC_CTX *tmp_ctx,
5909 uint32_t group_rid,
5910 uint32_t member_rid)
5912 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5915 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5916 TALLOC_CTX *mem_ctx,
5917 struct samu *sampass)
5919 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5920 LDAPMessage *entry = NULL;
5921 LDAPMessage *result = NULL;
5922 uint32_t num_result;
5923 LDAPMod **mods = NULL;
5924 char *filter;
5925 char *escape_username;
5926 char *gidstr;
5927 const char *dn = NULL;
5928 gid_t gid;
5929 int rc;
5931 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5933 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5934 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5935 return NT_STATUS_UNSUCCESSFUL;
5937 gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5938 if (!gidstr) {
5939 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5940 return NT_STATUS_NO_MEMORY;
5943 escape_username = escape_ldap_string(talloc_tos(),
5944 pdb_get_username(sampass));
5945 if (escape_username== NULL) {
5946 return NT_STATUS_NO_MEMORY;
5949 filter = talloc_asprintf(mem_ctx,
5950 "(&(uid=%s)"
5951 "(objectClass=%s)"
5952 "(objectClass=%s))",
5953 escape_username,
5954 LDAP_OBJ_POSIXACCOUNT,
5955 LDAP_OBJ_SAMBASAMACCOUNT);
5957 TALLOC_FREE(escape_username);
5959 if (filter == NULL) {
5960 return NT_STATUS_NO_MEMORY;
5963 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5964 if (rc != LDAP_SUCCESS) {
5965 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5966 return NT_STATUS_UNSUCCESSFUL;
5968 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
5970 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5972 if (num_result == 0) {
5973 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5974 return NT_STATUS_NO_SUCH_USER;
5977 if (num_result > 1) {
5978 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5979 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5982 entry = ldap_first_entry(priv2ld(ldap_state), result);
5983 if (!entry) {
5984 return NT_STATUS_UNSUCCESSFUL;
5987 /* retrieve the dn for later use */
5988 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5989 if (!dn) {
5990 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5991 return NT_STATUS_NO_MEMORY;
5994 /* remove the old one, and add the new one, this way we do not risk races */
5995 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
5997 if (mods == NULL) {
5998 return NT_STATUS_OK;
6001 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6003 if (rc != LDAP_SUCCESS) {
6004 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6005 pdb_get_username(sampass), gidstr));
6006 return NT_STATUS_UNSUCCESSFUL;
6009 flush_pwnam_cache();
6011 return NT_STATUS_OK;
6015 /**********************************************************************
6016 trusted domains functions
6017 *********************************************************************/
6019 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6020 const char *domain)
6022 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6023 ldap_state->domain_dn);
6026 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6027 TALLOC_CTX *mem_ctx,
6028 const char *domain, LDAPMessage **entry)
6030 int rc;
6031 char *filter;
6032 int scope = LDAP_SCOPE_SUBTREE;
6033 const char **attrs = NULL; /* NULL: get all attrs */
6034 int attrsonly = 0; /* 0: return values too */
6035 LDAPMessage *result = NULL;
6036 char *trusted_dn;
6037 uint32_t num_result;
6039 filter = talloc_asprintf(talloc_tos(),
6040 "(&(objectClass=%s)(sambaDomainName=%s))",
6041 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6043 trusted_dn = trusteddom_dn(ldap_state, domain);
6044 if (trusted_dn == NULL) {
6045 return False;
6047 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6048 filter, attrs, attrsonly, &result);
6050 if (result != NULL) {
6051 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6054 if (rc == LDAP_NO_SUCH_OBJECT) {
6055 *entry = NULL;
6056 return True;
6059 if (rc != LDAP_SUCCESS) {
6060 return False;
6063 num_result = ldap_count_entries(priv2ld(ldap_state), result);
6065 if (num_result > 1) {
6066 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6067 "%s object for domain '%s'?!\n",
6068 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6069 return False;
6072 if (num_result == 0) {
6073 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6074 "%s object for domain %s.\n",
6075 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6076 *entry = NULL;
6077 } else {
6078 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6081 return True;
6084 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6085 const char *domain,
6086 char** pwd,
6087 struct dom_sid *sid,
6088 time_t *pass_last_set_time)
6090 struct ldapsam_privates *ldap_state =
6091 (struct ldapsam_privates *)methods->private_data;
6092 LDAPMessage *entry = NULL;
6094 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6096 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6097 (entry == NULL))
6099 return False;
6102 /* password */
6103 if (pwd != NULL) {
6104 char *pwd_str;
6105 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6106 entry, "sambaClearTextPassword", talloc_tos());
6107 if (pwd_str == NULL) {
6108 return False;
6110 /* trusteddom_pw routines do not use talloc yet... */
6111 *pwd = SMB_STRDUP(pwd_str);
6112 if (*pwd == NULL) {
6113 return False;
6117 /* last change time */
6118 if (pass_last_set_time != NULL) {
6119 char *time_str;
6120 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6121 entry, "sambaPwdLastSet", talloc_tos());
6122 if (time_str == NULL) {
6123 return False;
6125 *pass_last_set_time = (time_t)atol(time_str);
6128 /* domain sid */
6129 if (sid != NULL) {
6130 char *sid_str;
6131 struct dom_sid dom_sid;
6132 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6133 entry, "sambaSID",
6134 talloc_tos());
6135 if (sid_str == NULL) {
6136 return False;
6138 if (!string_to_sid(&dom_sid, sid_str)) {
6139 return False;
6141 sid_copy(sid, &dom_sid);
6144 return True;
6147 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6148 const char* domain,
6149 const char* pwd,
6150 const struct dom_sid *sid)
6152 struct ldapsam_privates *ldap_state =
6153 (struct ldapsam_privates *)methods->private_data;
6154 LDAPMessage *entry = NULL;
6155 LDAPMod **mods = NULL;
6156 char *prev_pwd = NULL;
6157 char *trusted_dn = NULL;
6158 int rc;
6160 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6163 * get the current entry (if there is one) in order to put the
6164 * current password into the previous password attribute
6166 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6167 return False;
6170 mods = NULL;
6171 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6172 LDAP_OBJ_TRUSTDOM_PASSWORD);
6173 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6174 domain);
6175 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6176 sid_string_tos(sid));
6177 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6178 talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6179 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6180 "sambaClearTextPassword", pwd);
6182 if (entry != NULL) {
6183 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6184 entry, "sambaClearTextPassword", talloc_tos());
6185 if (prev_pwd != NULL) {
6186 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6187 "sambaPreviousClearTextPassword",
6188 prev_pwd);
6192 smbldap_talloc_autofree_ldapmod(talloc_tos(), mods);
6194 trusted_dn = trusteddom_dn(ldap_state, domain);
6195 if (trusted_dn == NULL) {
6196 return False;
6198 if (entry == NULL) {
6199 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6200 } else {
6201 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6204 if (rc != LDAP_SUCCESS) {
6205 DEBUG(1, ("error writing trusted domain password!\n"));
6206 return False;
6209 return True;
6212 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6213 const char *domain)
6215 int rc;
6216 struct ldapsam_privates *ldap_state =
6217 (struct ldapsam_privates *)methods->private_data;
6218 LDAPMessage *entry = NULL;
6219 const char *trusted_dn;
6221 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6222 return False;
6225 if (entry == NULL) {
6226 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6227 "%s\n", domain));
6228 return True;
6231 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6232 entry);
6233 if (trusted_dn == NULL) {
6234 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6235 return False;
6238 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6239 if (rc != LDAP_SUCCESS) {
6240 return False;
6243 return True;
6246 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6247 TALLOC_CTX *mem_ctx,
6248 uint32_t *num_domains,
6249 struct trustdom_info ***domains)
6251 int rc;
6252 struct ldapsam_privates *ldap_state =
6253 (struct ldapsam_privates *)methods->private_data;
6254 char *filter;
6255 int scope = LDAP_SCOPE_SUBTREE;
6256 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6257 int attrsonly = 0; /* 0: return values too */
6258 LDAPMessage *result = NULL;
6259 LDAPMessage *entry = NULL;
6261 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6262 LDAP_OBJ_TRUSTDOM_PASSWORD);
6264 rc = smbldap_search(ldap_state->smbldap_state,
6265 ldap_state->domain_dn,
6266 scope,
6267 filter,
6268 attrs,
6269 attrsonly,
6270 &result);
6272 if (result != NULL) {
6273 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6276 if (rc != LDAP_SUCCESS) {
6277 return NT_STATUS_UNSUCCESSFUL;
6280 *num_domains = 0;
6281 if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6282 DEBUG(1, ("talloc failed\n"));
6283 return NT_STATUS_NO_MEMORY;
6286 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6287 entry != NULL;
6288 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6290 char *dom_name, *dom_sid_str;
6291 struct trustdom_info *dom_info;
6293 dom_info = talloc(*domains, struct trustdom_info);
6294 if (dom_info == NULL) {
6295 DEBUG(1, ("talloc failed\n"));
6296 return NT_STATUS_NO_MEMORY;
6299 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6300 entry,
6301 "sambaDomainName",
6302 talloc_tos());
6303 if (dom_name == NULL) {
6304 DEBUG(1, ("talloc failed\n"));
6305 return NT_STATUS_NO_MEMORY;
6307 dom_info->name = dom_name;
6309 dom_sid_str = smbldap_talloc_single_attribute(
6310 priv2ld(ldap_state), entry, "sambaSID",
6311 talloc_tos());
6312 if (dom_sid_str == NULL) {
6313 DEBUG(1, ("talloc failed\n"));
6314 return NT_STATUS_NO_MEMORY;
6316 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6317 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6318 dom_sid_str));
6319 return NT_STATUS_UNSUCCESSFUL;
6322 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6323 domains, num_domains);
6325 if (*domains == NULL) {
6326 DEBUG(1, ("talloc failed\n"));
6327 return NT_STATUS_NO_MEMORY;
6331 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6332 return NT_STATUS_OK;
6336 /**********************************************************************
6337 Housekeeping
6338 *********************************************************************/
6340 static void free_private_data(void **vp)
6342 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6344 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6346 if ((*ldap_state)->result != NULL) {
6347 ldap_msgfree((*ldap_state)->result);
6348 (*ldap_state)->result = NULL;
6350 if ((*ldap_state)->domain_dn != NULL) {
6351 SAFE_FREE((*ldap_state)->domain_dn);
6354 *ldap_state = NULL;
6356 /* No need to free any further, as it is talloc()ed */
6359 /*********************************************************************
6360 Intitalise the parts of the pdb_methods structure that are common to
6361 all pdb_ldap modes
6362 *********************************************************************/
6364 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6366 NTSTATUS nt_status;
6367 struct ldapsam_privates *ldap_state;
6368 char *bind_dn = NULL;
6369 char *bind_secret = NULL;
6371 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6372 return nt_status;
6375 (*pdb_method)->name = "ldapsam";
6377 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6378 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6379 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6380 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6381 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6382 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6384 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6385 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6386 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6387 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6388 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6389 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6390 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6392 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6393 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6395 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6397 (*pdb_method)->capabilities = ldapsam_capabilities;
6398 (*pdb_method)->new_rid = ldapsam_new_rid;
6400 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6401 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6402 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6403 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6405 /* TODO: Setup private data and free */
6407 if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6408 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6409 return NT_STATUS_NO_MEMORY;
6412 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
6413 DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
6414 return NT_STATUS_NO_MEMORY;
6417 nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
6418 location, false, bind_dn, bind_secret,
6419 &ldap_state->smbldap_state);
6420 memset(bind_secret, '\0', strlen(bind_secret));
6421 SAFE_FREE(bind_secret);
6422 SAFE_FREE(bind_dn);
6423 if ( !NT_STATUS_IS_OK(nt_status) ) {
6424 return nt_status;
6427 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6428 return NT_STATUS_NO_MEMORY;
6431 (*pdb_method)->private_data = ldap_state;
6433 (*pdb_method)->free_private_data = free_private_data;
6435 return NT_STATUS_OK;
6438 /**********************************************************************
6439 Initialise the normal mode for pdb_ldap
6440 *********************************************************************/
6442 NTSTATUS pdb_ldapsam_init_common(struct pdb_methods **pdb_method,
6443 const char *location)
6445 NTSTATUS nt_status;
6446 struct ldapsam_privates *ldap_state = NULL;
6447 uint32_t alg_rid_base;
6448 char *alg_rid_base_string = NULL;
6449 LDAPMessage *result = NULL;
6450 LDAPMessage *entry = NULL;
6451 struct dom_sid ldap_domain_sid;
6452 struct dom_sid secrets_domain_sid;
6453 char *domain_sid_string = NULL;
6454 char *dn = NULL;
6455 char *uri = talloc_strdup( NULL, location );
6457 trim_char( uri, '\"', '\"' );
6458 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6460 TALLOC_FREE(uri);
6462 if (!NT_STATUS_IS_OK(nt_status)) {
6463 return nt_status;
6466 (*pdb_method)->name = "ldapsam";
6468 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6469 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6470 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6471 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6472 (*pdb_method)->search_users = ldapsam_search_users;
6473 (*pdb_method)->search_groups = ldapsam_search_groups;
6474 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6476 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6477 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6478 (*pdb_method)->enum_group_memberships =
6479 ldapsam_enum_group_memberships;
6480 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6481 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6482 (*pdb_method)->uid_to_sid = ldapsam_uid_to_sid;
6483 (*pdb_method)->gid_to_sid = ldapsam_gid_to_sid;
6485 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6486 (*pdb_method)->create_user = ldapsam_create_user;
6487 (*pdb_method)->delete_user = ldapsam_delete_user;
6488 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6489 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6490 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6491 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6492 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6496 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6497 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6499 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6501 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6502 &result,
6503 ldap_state->domain_name, True);
6505 if ( !NT_STATUS_IS_OK(nt_status) ) {
6506 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6507 "info, nor add one to the domain. "
6508 "We cannot work reliably without it.\n"));
6509 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6512 /* Given that the above might fail, everything below this must be
6513 * optional */
6515 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6516 result);
6517 if (!entry) {
6518 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6519 "entry\n"));
6520 ldap_msgfree(result);
6521 return NT_STATUS_UNSUCCESSFUL;
6524 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6525 if (!dn) {
6526 ldap_msgfree(result);
6527 return NT_STATUS_UNSUCCESSFUL;
6530 ldap_state->domain_dn = smb_xstrdup(dn);
6531 TALLOC_FREE(dn);
6533 domain_sid_string = smbldap_talloc_single_attribute(
6534 ldap_state->smbldap_state->ldap_struct,
6535 entry,
6536 get_userattr_key2string(ldap_state->schema_ver,
6537 LDAP_ATTR_USER_SID),
6538 talloc_tos());
6540 if (domain_sid_string) {
6541 bool found_sid;
6542 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6543 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6544 "read as a valid SID\n", domain_sid_string));
6545 ldap_msgfree(result);
6546 TALLOC_FREE(domain_sid_string);
6547 return NT_STATUS_INVALID_PARAMETER;
6549 found_sid = PDB_secrets_fetch_domain_sid(ldap_state->domain_name,
6550 &secrets_domain_sid);
6551 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6552 &ldap_domain_sid)) {
6553 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6554 "%s based on pdb_ldap results %s -> %s\n",
6555 ldap_state->domain_name,
6556 sid_string_dbg(&secrets_domain_sid),
6557 sid_string_dbg(&ldap_domain_sid)));
6559 /* reset secrets.tdb sid */
6560 PDB_secrets_store_domain_sid(ldap_state->domain_name,
6561 &ldap_domain_sid);
6562 DEBUG(1, ("New global sam SID: %s\n",
6563 sid_string_dbg(get_global_sam_sid())));
6565 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6566 TALLOC_FREE(domain_sid_string);
6569 alg_rid_base_string = smbldap_talloc_single_attribute(
6570 ldap_state->smbldap_state->ldap_struct,
6571 entry,
6572 get_attr_key2string( dominfo_attr_list,
6573 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6574 talloc_tos());
6575 if (alg_rid_base_string) {
6576 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6577 if (alg_rid_base != algorithmic_rid_base()) {
6578 DEBUG(0, ("The value of 'algorithmic RID base' has "
6579 "changed since the LDAP\n"
6580 "database was initialised. Aborting. \n"));
6581 ldap_msgfree(result);
6582 TALLOC_FREE(alg_rid_base_string);
6583 return NT_STATUS_UNSUCCESSFUL;
6585 TALLOC_FREE(alg_rid_base_string);
6587 ldap_msgfree(result);
6589 return NT_STATUS_OK;
6592 NTSTATUS pdb_ldapsam_init(void)
6594 NTSTATUS nt_status;
6596 nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION,
6597 "ldapsam",
6598 pdb_ldapsam_init_common);
6599 if (!NT_STATUS_IS_OK(nt_status)) {
6600 return nt_status;
6603 /* Let pdb_nds register backends */
6604 pdb_nds_init();
6606 pdb_ipa_init();
6608 return NT_STATUS_OK;