s3:libsmb: add a tcon_flags helper variable
[Samba/gebeck_regimport.git] / source3 / passdb / pdb_ldap.c
blob56225a2965da9b3ec2adcfbd80848fe2694b61e7
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"
57 #undef DBGC_CLASS
58 #define DBGC_CLASS DBGC_PASSDB
60 #include <lber.h>
61 #include <ldap.h>
64 #include "smbldap.h"
65 #include "passdb/pdb_ldap.h"
66 #include "passdb/pdb_nds.h"
67 #include "passdb/pdb_ipa.h"
68 #include "passdb/pdb_ldap_util.h"
69 #include "passdb/pdb_ldap_schema.h"
71 /**********************************************************************
72 Simple helper function to make stuff better readable
73 **********************************************************************/
75 LDAP *priv2ld(struct ldapsam_privates *priv)
77 return priv->smbldap_state->ldap_struct;
80 /**********************************************************************
81 Get the attribute name given a user schame version.
82 **********************************************************************/
84 static const char* get_userattr_key2string( int schema_ver, int key )
86 switch ( schema_ver ) {
87 case SCHEMAVER_SAMBASAMACCOUNT:
88 return get_attr_key2string( attrib_map_v30, key );
90 default:
91 DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
92 break;
94 return NULL;
97 /**********************************************************************
98 Return the list of attribute names given a user schema version.
99 **********************************************************************/
101 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
103 switch ( schema_ver ) {
104 case SCHEMAVER_SAMBASAMACCOUNT:
105 return get_attr_list( mem_ctx, attrib_map_v30 );
106 default:
107 DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
108 break;
111 return NULL;
114 /**************************************************************************
115 Return the list of attribute names to delete given a user schema version.
116 **************************************************************************/
118 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
119 int schema_ver )
121 switch ( schema_ver ) {
122 case SCHEMAVER_SAMBASAMACCOUNT:
123 return get_attr_list( mem_ctx,
124 attrib_map_to_delete_v30 );
125 default:
126 DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
127 break;
130 return NULL;
134 /*******************************************************************
135 Generate the LDAP search filter for the objectclass based on the
136 version of the schema we are using.
137 ******************************************************************/
139 static const char* get_objclass_filter( int schema_ver )
141 fstring objclass_filter;
142 char *result;
144 switch( schema_ver ) {
145 case SCHEMAVER_SAMBASAMACCOUNT:
146 fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
147 break;
148 default:
149 DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
150 objclass_filter[0] = '\0';
151 break;
154 result = talloc_strdup(talloc_tos(), objclass_filter);
155 SMB_ASSERT(result != NULL);
156 return result;
159 /*****************************************************************
160 Scan a sequence number off OpenLDAP's syncrepl contextCSN
161 ******************************************************************/
163 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
165 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
166 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
167 LDAPMessage *msg = NULL;
168 LDAPMessage *entry = NULL;
169 TALLOC_CTX *mem_ctx;
170 char **values = NULL;
171 int rc, num_result, num_values, rid;
172 char *suffix = NULL;
173 char *tok;
174 const char *p;
175 const char **attrs;
177 /* Unfortunatly there is no proper way to detect syncrepl-support in
178 * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
179 * but do not show up in the root-DSE yet. Neither we can query the
180 * subschema-context for the syncProviderSubentry or syncConsumerSubentry
181 * objectclass. Currently we require lp_ldap_suffix() to show up as
182 * namingContext. - Guenther
185 if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
186 return ntstatus;
189 if (!seq_num) {
190 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
191 return ntstatus;
194 if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix(talloc_tos()))) {
195 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
196 "as top-level namingContext\n", lp_ldap_suffix(talloc_tos())));
197 return ntstatus;
200 mem_ctx = talloc_init("ldapsam_get_seq_num");
202 if (mem_ctx == NULL)
203 return NT_STATUS_NO_MEMORY;
205 if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
206 ntstatus = NT_STATUS_NO_MEMORY;
207 goto done;
210 /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
211 rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
212 if (rid > 0) {
214 /* consumer syncreplCookie: */
215 /* csn=20050126161620Z#0000001#00#00000 */
216 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
217 attrs[1] = NULL;
218 suffix = talloc_asprintf(mem_ctx,
219 "cn=syncrepl%d,%s", rid, lp_ldap_suffix(talloc_tos()));
220 if (!suffix) {
221 ntstatus = NT_STATUS_NO_MEMORY;
222 goto done;
224 } else {
226 /* provider contextCSN */
227 /* 20050126161620Z#000009#00#000000 */
228 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
229 attrs[1] = NULL;
230 suffix = talloc_asprintf(mem_ctx,
231 "cn=ldapsync,%s", lp_ldap_suffix(talloc_tos()));
233 if (!suffix) {
234 ntstatus = NT_STATUS_NO_MEMORY;
235 goto done;
239 rc = smbldap_search(ldap_state->smbldap_state, suffix,
240 LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
242 if (rc != LDAP_SUCCESS) {
243 goto done;
246 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
247 if (num_result != 1) {
248 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
249 goto done;
252 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
253 if (entry == NULL) {
254 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
255 goto done;
258 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
259 if (values == NULL) {
260 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
261 goto done;
264 num_values = ldap_count_values(values);
265 if (num_values == 0) {
266 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
267 goto done;
270 p = values[0];
271 if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
272 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
273 goto done;
276 p = tok;
277 if (!strncmp(p, "csn=", strlen("csn=")))
278 p += strlen("csn=");
280 DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
282 *seq_num = generalized_to_unix_time(p);
284 /* very basic sanity check */
285 if (*seq_num <= 0) {
286 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n",
287 (int)*seq_num));
288 goto done;
291 ntstatus = NT_STATUS_OK;
293 done:
294 if (values != NULL)
295 ldap_value_free(values);
296 if (msg != NULL)
297 ldap_msgfree(msg);
298 if (mem_ctx)
299 talloc_destroy(mem_ctx);
301 return ntstatus;
304 /*******************************************************************
305 Run the search by name.
306 ******************************************************************/
308 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
309 const char *user,
310 LDAPMessage ** result,
311 const char **attr)
313 char *filter = NULL;
314 char *escape_user = escape_ldap_string(talloc_tos(), user);
315 int ret = -1;
317 if (!escape_user) {
318 return LDAP_NO_MEMORY;
322 * in the filter expression, replace %u with the real name
323 * so in ldap filter, %u MUST exist :-)
325 filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
326 get_objclass_filter(ldap_state->schema_ver));
327 if (!filter) {
328 TALLOC_FREE(escape_user);
329 return LDAP_NO_MEMORY;
332 * have to use this here because $ is filtered out
333 * in string_sub
336 filter = talloc_all_string_sub(talloc_tos(),
337 filter, "%u", escape_user);
338 TALLOC_FREE(escape_user);
339 if (!filter) {
340 return LDAP_NO_MEMORY;
343 ret = smbldap_search_suffix(ldap_state->smbldap_state,
344 filter, attr, result);
345 TALLOC_FREE(filter);
346 return ret;
349 /*******************************************************************
350 Run the search by rid.
351 ******************************************************************/
353 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
354 uint32_t rid, LDAPMessage ** result,
355 const char **attr)
357 char *filter = NULL;
358 int rc;
360 filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
361 get_objclass_filter(ldap_state->schema_ver));
362 if (!filter) {
363 return LDAP_NO_MEMORY;
366 rc = smbldap_search_suffix(ldap_state->smbldap_state,
367 filter, attr, result);
368 TALLOC_FREE(filter);
369 return rc;
372 /*******************************************************************
373 Run the search by SID.
374 ******************************************************************/
376 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
377 const struct dom_sid *sid, LDAPMessage ** result,
378 const char **attr)
380 char *filter = NULL;
381 int rc;
382 fstring sid_string;
384 filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
385 get_userattr_key2string(ldap_state->schema_ver,
386 LDAP_ATTR_USER_SID),
387 sid_to_fstring(sid_string, sid),
388 get_objclass_filter(ldap_state->schema_ver));
389 if (!filter) {
390 return LDAP_NO_MEMORY;
393 rc = smbldap_search_suffix(ldap_state->smbldap_state,
394 filter, attr, result);
396 TALLOC_FREE(filter);
397 return rc;
400 /*******************************************************************
401 Delete complete object or objectclass and attrs from
402 object found in search_result depending on lp_ldap_delete_dn
403 ******************************************************************/
405 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
406 TALLOC_CTX *mem_ctx,
407 LDAPMessage *entry,
408 const char *objectclass,
409 const char **attrs)
411 LDAPMod **mods = NULL;
412 char *name;
413 const char *dn;
414 BerElement *ptr = NULL;
416 dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
417 if (dn == NULL) {
418 return LDAP_NO_MEMORY;
421 if (lp_ldap_delete_dn()) {
422 return smbldap_delete(priv->smbldap_state, dn);
425 /* Ok, delete only the SAM attributes */
427 for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
428 name != NULL;
429 name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
430 const char **attrib;
432 /* We are only allowed to delete the attributes that
433 really exist. */
435 for (attrib = attrs; *attrib != NULL; attrib++) {
436 if (strequal(*attrib, name)) {
437 DEBUG(10, ("ldapsam_delete_entry: deleting "
438 "attribute %s\n", name));
439 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
440 NULL);
443 ldap_memfree(name);
446 if (ptr != NULL) {
447 ber_free(ptr, 0);
450 smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
451 talloc_autofree_ldapmod(mem_ctx, mods);
453 return smbldap_modify(priv->smbldap_state, dn, mods);
456 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
458 char *temp;
459 struct tm tm;
461 temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
462 get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
463 talloc_tos());
464 if (!temp) {
465 return (time_t) 0;
468 if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
469 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
470 (char*)temp));
471 TALLOC_FREE(temp);
472 return (time_t) 0;
474 TALLOC_FREE(temp);
475 tzset();
476 return timegm(&tm);
479 /**********************************************************************
480 Initialize struct samu from an LDAP query.
481 (Based on init_sam_from_buffer in pdb_tdb.c)
482 *********************************************************************/
484 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
485 struct samu * sampass,
486 LDAPMessage * entry)
488 time_t logon_time,
489 logoff_time,
490 kickoff_time,
491 pass_last_set_time,
492 pass_can_change_time,
493 ldap_entry_time,
494 bad_password_time;
495 char *username = NULL,
496 *domain = NULL,
497 *nt_username = NULL,
498 *fullname = NULL,
499 *homedir = NULL,
500 *dir_drive = NULL,
501 *logon_script = NULL,
502 *profile_path = NULL,
503 *acct_desc = NULL,
504 *workstations = NULL,
505 *munged_dial = NULL;
506 uint32_t user_rid;
507 uint8 smblmpwd[LM_HASH_LEN],
508 smbntpwd[NT_HASH_LEN];
509 bool use_samba_attrs = True;
510 uint32_t acct_ctrl = 0;
511 uint16_t logon_divs;
512 uint16_t bad_password_count = 0,
513 logon_count = 0;
514 uint32_t hours_len;
515 uint8 hours[MAX_HOURS_LEN];
516 char *temp = NULL;
517 struct login_cache cache_entry;
518 uint32_t pwHistLen;
519 bool expand_explicit = lp_passdb_expand_explicit();
520 bool ret = false;
521 TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
523 if (!ctx) {
524 return false;
526 if (sampass == NULL || ldap_state == NULL || entry == NULL) {
527 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
528 goto fn_exit;
531 if (priv2ld(ldap_state) == NULL) {
532 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
533 "ldap_struct is NULL!\n"));
534 goto fn_exit;
537 if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
538 entry,
539 "uid",
540 ctx))) {
541 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
542 "this user!\n"));
543 goto fn_exit;
546 DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
548 nt_username = talloc_strdup(ctx, username);
549 if (!nt_username) {
550 goto fn_exit;
553 domain = talloc_strdup(ctx, ldap_state->domain_name);
554 if (!domain) {
555 goto fn_exit;
558 pdb_set_username(sampass, username, PDB_SET);
560 pdb_set_domain(sampass, domain, PDB_DEFAULT);
561 pdb_set_nt_username(sampass, nt_username, PDB_SET);
563 /* deal with different attributes between the schema first */
565 if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
566 if ((temp = smbldap_talloc_single_attribute(
567 ldap_state->smbldap_state->ldap_struct,
568 entry,
569 get_userattr_key2string(ldap_state->schema_ver,
570 LDAP_ATTR_USER_SID),
571 ctx))!=NULL) {
572 pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
574 } else {
575 if ((temp = smbldap_talloc_single_attribute(
576 ldap_state->smbldap_state->ldap_struct,
577 entry,
578 get_userattr_key2string(ldap_state->schema_ver,
579 LDAP_ATTR_USER_RID),
580 ctx))!=NULL) {
581 user_rid = (uint32_t)atol(temp);
582 pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
586 if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
587 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n",
588 get_userattr_key2string(ldap_state->schema_ver,
589 LDAP_ATTR_USER_SID),
590 get_userattr_key2string(ldap_state->schema_ver,
591 LDAP_ATTR_USER_RID),
592 username));
593 return False;
596 temp = smbldap_talloc_single_attribute(
597 ldap_state->smbldap_state->ldap_struct,
598 entry,
599 get_userattr_key2string(ldap_state->schema_ver,
600 LDAP_ATTR_PWD_LAST_SET),
601 ctx);
602 if (temp) {
603 pass_last_set_time = (time_t) atol(temp);
604 pdb_set_pass_last_set_time(sampass,
605 pass_last_set_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_LOGON_TIME),
613 ctx);
614 if (temp) {
615 logon_time = (time_t) atol(temp);
616 pdb_set_logon_time(sampass, logon_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_LOGOFF_TIME),
624 ctx);
625 if (temp) {
626 logoff_time = (time_t) atol(temp);
627 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
630 temp = smbldap_talloc_single_attribute(
631 ldap_state->smbldap_state->ldap_struct,
632 entry,
633 get_userattr_key2string(ldap_state->schema_ver,
634 LDAP_ATTR_KICKOFF_TIME),
635 ctx);
636 if (temp) {
637 kickoff_time = (time_t) atol(temp);
638 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
641 temp = smbldap_talloc_single_attribute(
642 ldap_state->smbldap_state->ldap_struct,
643 entry,
644 get_userattr_key2string(ldap_state->schema_ver,
645 LDAP_ATTR_PWD_CAN_CHANGE),
646 ctx);
647 if (temp) {
648 pass_can_change_time = (time_t) atol(temp);
649 pdb_set_pass_can_change_time(sampass,
650 pass_can_change_time, PDB_SET);
653 /* recommend that 'gecos' and 'displayName' should refer to the same
654 * attribute OID. userFullName depreciated, only used by Samba
655 * primary rules of LDAP: don't make a new attribute when one is already defined
656 * that fits your needs; using cn then displayName rather than 'userFullName'
659 fullname = smbldap_talloc_single_attribute(
660 ldap_state->smbldap_state->ldap_struct,
661 entry,
662 get_userattr_key2string(ldap_state->schema_ver,
663 LDAP_ATTR_DISPLAY_NAME),
664 ctx);
665 if (fullname) {
666 pdb_set_fullname(sampass, fullname, PDB_SET);
667 } else {
668 fullname = smbldap_talloc_single_attribute(
669 ldap_state->smbldap_state->ldap_struct,
670 entry,
671 get_userattr_key2string(ldap_state->schema_ver,
672 LDAP_ATTR_CN),
673 ctx);
674 if (fullname) {
675 pdb_set_fullname(sampass, fullname, PDB_SET);
679 dir_drive = smbldap_talloc_single_attribute(
680 ldap_state->smbldap_state->ldap_struct,
681 entry,
682 get_userattr_key2string(ldap_state->schema_ver,
683 LDAP_ATTR_HOME_DRIVE),
684 ctx);
685 if (dir_drive) {
686 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
687 } else {
688 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
691 homedir = smbldap_talloc_single_attribute(
692 ldap_state->smbldap_state->ldap_struct,
693 entry,
694 get_userattr_key2string(ldap_state->schema_ver,
695 LDAP_ATTR_HOME_PATH),
696 ctx);
697 if (homedir) {
698 if (expand_explicit) {
699 homedir = talloc_sub_basic(ctx,
700 username,
701 domain,
702 homedir);
703 if (!homedir) {
704 goto fn_exit;
707 pdb_set_homedir(sampass, homedir, PDB_SET);
708 } else {
709 pdb_set_homedir(sampass,
710 talloc_sub_basic(ctx, username, domain,
711 lp_logon_home()),
712 PDB_DEFAULT);
715 logon_script = smbldap_talloc_single_attribute(
716 ldap_state->smbldap_state->ldap_struct,
717 entry,
718 get_userattr_key2string(ldap_state->schema_ver,
719 LDAP_ATTR_LOGON_SCRIPT),
720 ctx);
721 if (logon_script) {
722 if (expand_explicit) {
723 logon_script = talloc_sub_basic(ctx,
724 username,
725 domain,
726 logon_script);
727 if (!logon_script) {
728 goto fn_exit;
731 pdb_set_logon_script(sampass, logon_script, PDB_SET);
732 } else {
733 pdb_set_logon_script(sampass,
734 talloc_sub_basic(ctx, username, domain,
735 lp_logon_script()),
736 PDB_DEFAULT );
739 profile_path = smbldap_talloc_single_attribute(
740 ldap_state->smbldap_state->ldap_struct,
741 entry,
742 get_userattr_key2string(ldap_state->schema_ver,
743 LDAP_ATTR_PROFILE_PATH),
744 ctx);
745 if (profile_path) {
746 if (expand_explicit) {
747 profile_path = talloc_sub_basic(ctx,
748 username,
749 domain,
750 profile_path);
751 if (!profile_path) {
752 goto fn_exit;
755 pdb_set_profile_path(sampass, profile_path, PDB_SET);
756 } else {
757 pdb_set_profile_path(sampass,
758 talloc_sub_basic(ctx, username, domain,
759 lp_logon_path()),
760 PDB_DEFAULT );
763 acct_desc = smbldap_talloc_single_attribute(
764 ldap_state->smbldap_state->ldap_struct,
765 entry,
766 get_userattr_key2string(ldap_state->schema_ver,
767 LDAP_ATTR_DESC),
768 ctx);
769 if (acct_desc) {
770 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
773 workstations = smbldap_talloc_single_attribute(
774 ldap_state->smbldap_state->ldap_struct,
775 entry,
776 get_userattr_key2string(ldap_state->schema_ver,
777 LDAP_ATTR_USER_WKS),
778 ctx);
779 if (workstations) {
780 pdb_set_workstations(sampass, workstations, PDB_SET);
783 munged_dial = smbldap_talloc_single_attribute(
784 ldap_state->smbldap_state->ldap_struct,
785 entry,
786 get_userattr_key2string(ldap_state->schema_ver,
787 LDAP_ATTR_MUNGED_DIAL),
788 ctx);
789 if (munged_dial) {
790 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
793 /* FIXME: hours stuff should be cleaner */
795 logon_divs = 168;
796 hours_len = 21;
797 memset(hours, 0xff, hours_len);
799 if (ldap_state->is_nds_ldap) {
800 char *user_dn;
801 size_t pwd_len;
802 char clear_text_pw[512];
804 /* Make call to Novell eDirectory ldap extension to get clear text password.
805 NOTE: This will only work if we have an SSL connection to eDirectory. */
806 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
807 if (user_dn != NULL) {
808 DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
810 pwd_len = sizeof(clear_text_pw);
811 if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
812 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
813 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
814 TALLOC_FREE(user_dn);
815 return False;
817 ZERO_STRUCT(smblmpwd);
818 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
819 TALLOC_FREE(user_dn);
820 return False;
822 ZERO_STRUCT(smbntpwd);
823 use_samba_attrs = False;
826 TALLOC_FREE(user_dn);
828 } else {
829 DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
833 if (use_samba_attrs) {
834 temp = smbldap_talloc_single_attribute(
835 ldap_state->smbldap_state->ldap_struct,
836 entry,
837 get_userattr_key2string(ldap_state->schema_ver,
838 LDAP_ATTR_LMPW),
839 ctx);
840 if (temp) {
841 pdb_gethexpwd(temp, smblmpwd);
842 memset((char *)temp, '\0', strlen(temp)+1);
843 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
844 goto fn_exit;
846 ZERO_STRUCT(smblmpwd);
849 temp = smbldap_talloc_single_attribute(
850 ldap_state->smbldap_state->ldap_struct,
851 entry,
852 get_userattr_key2string(ldap_state->schema_ver,
853 LDAP_ATTR_NTPW),
854 ctx);
855 if (temp) {
856 pdb_gethexpwd(temp, smbntpwd);
857 memset((char *)temp, '\0', strlen(temp)+1);
858 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
859 goto fn_exit;
861 ZERO_STRUCT(smbntpwd);
865 pwHistLen = 0;
867 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
868 if (pwHistLen > 0){
869 uint8 *pwhist = NULL;
870 int i;
871 char *history_string = talloc_array(ctx, char,
872 MAX_PW_HISTORY_LEN*64);
874 if (!history_string) {
875 goto fn_exit;
878 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
880 pwhist = talloc_array(ctx, uint8,
881 pwHistLen * PW_HISTORY_ENTRY_LEN);
882 if (pwhist == NULL) {
883 DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
884 goto fn_exit;
886 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
888 if (smbldap_get_single_attribute(
889 ldap_state->smbldap_state->ldap_struct,
890 entry,
891 get_userattr_key2string(ldap_state->schema_ver,
892 LDAP_ATTR_PWD_HISTORY),
893 history_string,
894 MAX_PW_HISTORY_LEN*64)) {
895 bool hex_failed = false;
896 for (i = 0; i < pwHistLen; i++){
897 /* Get the 16 byte salt. */
898 if (!pdb_gethexpwd(&history_string[i*64],
899 &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
900 hex_failed = true;
901 break;
903 /* Get the 16 byte MD5 hash of salt+passwd. */
904 if (!pdb_gethexpwd(&history_string[(i*64)+32],
905 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
906 PW_HISTORY_SALT_LEN])) {
907 hex_failed = True;
908 break;
911 if (hex_failed) {
912 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
913 username));
914 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
917 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
918 goto fn_exit;
922 temp = smbldap_talloc_single_attribute(
923 ldap_state->smbldap_state->ldap_struct,
924 entry,
925 get_userattr_key2string(ldap_state->schema_ver,
926 LDAP_ATTR_ACB_INFO),
927 ctx);
928 if (temp) {
929 acct_ctrl = pdb_decode_acct_ctrl(temp);
931 if (acct_ctrl == 0) {
932 acct_ctrl |= ACB_NORMAL;
935 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
936 } else {
937 acct_ctrl |= ACB_NORMAL;
940 pdb_set_hours_len(sampass, hours_len, PDB_SET);
941 pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
943 temp = smbldap_talloc_single_attribute(
944 ldap_state->smbldap_state->ldap_struct,
945 entry,
946 get_userattr_key2string(ldap_state->schema_ver,
947 LDAP_ATTR_BAD_PASSWORD_COUNT),
948 ctx);
949 if (temp) {
950 bad_password_count = (uint32_t) atol(temp);
951 pdb_set_bad_password_count(sampass,
952 bad_password_count, PDB_SET);
955 temp = smbldap_talloc_single_attribute(
956 ldap_state->smbldap_state->ldap_struct,
957 entry,
958 get_userattr_key2string(ldap_state->schema_ver,
959 LDAP_ATTR_BAD_PASSWORD_TIME),
960 ctx);
961 if (temp) {
962 bad_password_time = (time_t) atol(temp);
963 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
967 temp = smbldap_talloc_single_attribute(
968 ldap_state->smbldap_state->ldap_struct,
969 entry,
970 get_userattr_key2string(ldap_state->schema_ver,
971 LDAP_ATTR_LOGON_COUNT),
972 ctx);
973 if (temp) {
974 logon_count = (uint32_t) atol(temp);
975 pdb_set_logon_count(sampass, logon_count, PDB_SET);
978 /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
980 temp = smbldap_talloc_single_attribute(
981 ldap_state->smbldap_state->ldap_struct,
982 entry,
983 get_userattr_key2string(ldap_state->schema_ver,
984 LDAP_ATTR_LOGON_HOURS),
985 ctx);
986 if (temp) {
987 pdb_gethexhours(temp, hours);
988 memset((char *)temp, '\0', strlen(temp) +1);
989 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
990 ZERO_STRUCT(hours);
993 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
994 struct passwd unix_pw;
995 bool have_uid = false;
996 bool have_gid = false;
997 struct dom_sid mapped_gsid;
998 const struct dom_sid *primary_gsid;
999 struct unixid id;
1001 ZERO_STRUCT(unix_pw);
1003 unix_pw.pw_name = username;
1004 unix_pw.pw_passwd = discard_const_p(char, "x");
1006 temp = smbldap_talloc_single_attribute(
1007 priv2ld(ldap_state),
1008 entry,
1009 "uidNumber",
1010 ctx);
1011 if (temp) {
1012 /* We've got a uid, feed the cache */
1013 unix_pw.pw_uid = strtoul(temp, NULL, 10);
1014 have_uid = true;
1016 temp = smbldap_talloc_single_attribute(
1017 priv2ld(ldap_state),
1018 entry,
1019 "gidNumber",
1020 ctx);
1021 if (temp) {
1022 /* We've got a uid, feed the cache */
1023 unix_pw.pw_gid = strtoul(temp, NULL, 10);
1024 have_gid = true;
1026 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1027 priv2ld(ldap_state),
1028 entry,
1029 "gecos",
1030 ctx);
1031 if (unix_pw.pw_gecos) {
1032 unix_pw.pw_gecos = fullname;
1034 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1035 priv2ld(ldap_state),
1036 entry,
1037 "homeDirectory",
1038 ctx);
1039 if (unix_pw.pw_dir) {
1040 unix_pw.pw_dir = discard_const_p(char, "");
1042 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1043 priv2ld(ldap_state),
1044 entry,
1045 "loginShell",
1046 ctx);
1047 if (unix_pw.pw_shell) {
1048 unix_pw.pw_shell = discard_const_p(char, "");
1051 if (have_uid && have_gid) {
1052 sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1053 } else {
1054 sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1057 if (sampass->unix_pw == NULL) {
1058 DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1059 pdb_get_username(sampass)));
1060 goto fn_exit;
1063 id.id = sampass->unix_pw->pw_uid;
1064 id.type = ID_TYPE_UID;
1066 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1068 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1069 primary_gsid = pdb_get_group_sid(sampass);
1070 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1071 id.id = sampass->unix_pw->pw_gid;
1072 id.type = ID_TYPE_GID;
1074 idmap_cache_set_sid2unixid(primary_gsid, &id);
1078 /* check the timestamp of the cache vs ldap entry */
1079 if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1080 entry))) {
1081 ret = true;
1082 goto fn_exit;
1085 /* see if we have newer updates */
1086 if (!login_cache_read(sampass, &cache_entry)) {
1087 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1088 (unsigned int)pdb_get_bad_password_count(sampass),
1089 (unsigned int)pdb_get_bad_password_time(sampass)));
1090 ret = true;
1091 goto fn_exit;
1094 DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1095 (unsigned int)ldap_entry_time,
1096 (unsigned int)cache_entry.entry_timestamp,
1097 (unsigned int)cache_entry.bad_password_time));
1099 if (ldap_entry_time > cache_entry.entry_timestamp) {
1100 /* cache is older than directory , so
1101 we need to delete the entry but allow the
1102 fields to be written out */
1103 login_cache_delentry(sampass);
1104 } else {
1105 /* read cache in */
1106 pdb_set_acct_ctrl(sampass,
1107 pdb_get_acct_ctrl(sampass) |
1108 (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1109 PDB_SET);
1110 pdb_set_bad_password_count(sampass,
1111 cache_entry.bad_password_count,
1112 PDB_SET);
1113 pdb_set_bad_password_time(sampass,
1114 cache_entry.bad_password_time,
1115 PDB_SET);
1118 ret = true;
1120 fn_exit:
1122 TALLOC_FREE(ctx);
1123 return ret;
1126 /**********************************************************************
1127 Initialize the ldap db from a struct samu. Called on update.
1128 (Based on init_buffer_from_sam in pdb_tdb.c)
1129 *********************************************************************/
1131 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1132 LDAPMessage *existing,
1133 LDAPMod *** mods, struct samu * sampass,
1134 bool (*need_update)(const struct samu *,
1135 enum pdb_elements))
1137 char *temp = NULL;
1139 if (mods == NULL || sampass == NULL) {
1140 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1141 return False;
1144 *mods = NULL;
1147 * took out adding "objectclass: sambaAccount"
1148 * do this on a per-mod basis
1150 if (need_update(sampass, PDB_USERNAME)) {
1151 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1152 "uid", pdb_get_username(sampass));
1153 if (ldap_state->is_nds_ldap) {
1154 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1155 "cn", pdb_get_username(sampass));
1156 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1157 "sn", pdb_get_username(sampass));
1161 DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1163 /* only update the RID if we actually need to */
1164 if (need_update(sampass, PDB_USERSID)) {
1165 fstring sid_string;
1166 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1168 switch ( ldap_state->schema_ver ) {
1169 case SCHEMAVER_SAMBASAMACCOUNT:
1170 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1171 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1172 sid_to_fstring(sid_string, user_sid));
1173 break;
1175 default:
1176 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1177 break;
1181 /* we don't need to store the primary group RID - so leaving it
1182 'free' to hang off the unix primary group makes life easier */
1184 if (need_update(sampass, PDB_GROUPSID)) {
1185 fstring sid_string;
1186 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1188 switch ( ldap_state->schema_ver ) {
1189 case SCHEMAVER_SAMBASAMACCOUNT:
1190 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1191 get_userattr_key2string(ldap_state->schema_ver,
1192 LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1193 break;
1195 default:
1196 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1197 break;
1202 /* displayName, cn, and gecos should all be the same
1203 * most easily accomplished by giving them the same OID
1204 * gecos isn't set here b/c it should be handled by the
1205 * add-user script
1206 * We change displayName only and fall back to cn if
1207 * it does not exist.
1210 if (need_update(sampass, PDB_FULLNAME))
1211 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1212 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME),
1213 pdb_get_fullname(sampass));
1215 if (need_update(sampass, PDB_ACCTDESC))
1216 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1217 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC),
1218 pdb_get_acct_desc(sampass));
1220 if (need_update(sampass, PDB_WORKSTATIONS))
1221 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1222 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS),
1223 pdb_get_workstations(sampass));
1225 if (need_update(sampass, PDB_MUNGEDDIAL))
1226 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1227 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL),
1228 pdb_get_munged_dial(sampass));
1230 if (need_update(sampass, PDB_SMBHOME))
1231 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1232 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH),
1233 pdb_get_homedir(sampass));
1235 if (need_update(sampass, PDB_DRIVE))
1236 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1237 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE),
1238 pdb_get_dir_drive(sampass));
1240 if (need_update(sampass, PDB_LOGONSCRIPT))
1241 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1242 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT),
1243 pdb_get_logon_script(sampass));
1245 if (need_update(sampass, PDB_PROFILE))
1246 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1247 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH),
1248 pdb_get_profile_path(sampass));
1250 if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1251 return false;
1253 if (need_update(sampass, PDB_LOGONTIME))
1254 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1255 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1256 SAFE_FREE(temp);
1258 if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1259 return false;
1261 if (need_update(sampass, PDB_LOGOFFTIME))
1262 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1263 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1264 SAFE_FREE(temp);
1266 if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1267 return false;
1269 if (need_update(sampass, PDB_KICKOFFTIME))
1270 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1271 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1272 SAFE_FREE(temp);
1274 if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1275 return false;
1277 if (need_update(sampass, PDB_CANCHANGETIME))
1278 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1279 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1280 SAFE_FREE(temp);
1282 if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1283 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1285 if (need_update(sampass, PDB_LMPASSWD)) {
1286 const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1287 if (lm_pw) {
1288 char pwstr[34];
1289 pdb_sethexpwd(pwstr, lm_pw,
1290 pdb_get_acct_ctrl(sampass));
1291 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1292 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1293 pwstr);
1294 } else {
1295 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1296 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW),
1297 NULL);
1300 if (need_update(sampass, PDB_NTPASSWD)) {
1301 const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1302 if (nt_pw) {
1303 char pwstr[34];
1304 pdb_sethexpwd(pwstr, nt_pw,
1305 pdb_get_acct_ctrl(sampass));
1306 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1307 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1308 pwstr);
1309 } else {
1310 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1311 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW),
1312 NULL);
1316 if (need_update(sampass, PDB_PWHISTORY)) {
1317 char *pwstr = NULL;
1318 uint32_t pwHistLen = 0;
1319 pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1321 pwstr = SMB_MALLOC_ARRAY(char, 1024);
1322 if (!pwstr) {
1323 return false;
1325 if (pwHistLen == 0) {
1326 /* Remove any password history from the LDAP store. */
1327 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1328 pwstr[64] = '\0';
1329 } else {
1330 int i;
1331 uint32_t currHistLen = 0;
1332 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1333 if (pwhist != NULL) {
1334 /* We can only store (1024-1/64 password history entries. */
1335 pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1336 for (i=0; i< pwHistLen && i < currHistLen; i++) {
1337 /* Store the salt. */
1338 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1339 /* Followed by the md5 hash of salt + md4 hash */
1340 pdb_sethexpwd(&pwstr[(i*64)+32],
1341 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1342 DEBUG(100, ("pwstr=%s\n", pwstr));
1346 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1347 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
1348 pwstr);
1349 SAFE_FREE(pwstr);
1352 if (need_update(sampass, PDB_PASSLASTSET)) {
1353 if (asprintf(&temp, "%li",
1354 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1355 return false;
1357 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1358 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET),
1359 temp);
1360 SAFE_FREE(temp);
1364 if (need_update(sampass, PDB_HOURS)) {
1365 const uint8 *hours = pdb_get_hours(sampass);
1366 if (hours) {
1367 char hourstr[44];
1368 pdb_sethexhours(hourstr, hours);
1369 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1370 existing,
1371 mods,
1372 get_userattr_key2string(ldap_state->schema_ver,
1373 LDAP_ATTR_LOGON_HOURS),
1374 hourstr);
1378 if (need_update(sampass, PDB_ACCTCTRL))
1379 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1380 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO),
1381 pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1383 /* password lockout cache:
1384 - If we are now autolocking or clearing, we write to ldap
1385 - If we are clearing, we delete the cache entry
1386 - If the count is > 0, we update the cache
1388 This even means when autolocking, we cache, just in case the
1389 update doesn't work, and we have to cache the autolock flag */
1391 if (need_update(sampass, PDB_BAD_PASSWORD_COUNT)) /* &&
1392 need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1393 uint16_t badcount = pdb_get_bad_password_count(sampass);
1394 time_t badtime = pdb_get_bad_password_time(sampass);
1395 uint32_t pol;
1396 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1398 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1399 (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1401 if ((badcount >= pol) || (badcount == 0)) {
1402 DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1403 (unsigned int)badcount, (unsigned int)badtime));
1404 if (asprintf(&temp, "%li", (long)badcount) < 0) {
1405 return false;
1407 smbldap_make_mod(
1408 ldap_state->smbldap_state->ldap_struct,
1409 existing, mods,
1410 get_userattr_key2string(
1411 ldap_state->schema_ver,
1412 LDAP_ATTR_BAD_PASSWORD_COUNT),
1413 temp);
1414 SAFE_FREE(temp);
1416 if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1417 return false;
1419 smbldap_make_mod(
1420 ldap_state->smbldap_state->ldap_struct,
1421 existing, mods,
1422 get_userattr_key2string(
1423 ldap_state->schema_ver,
1424 LDAP_ATTR_BAD_PASSWORD_TIME),
1425 temp);
1426 SAFE_FREE(temp);
1428 if (badcount == 0) {
1429 DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1430 login_cache_delentry(sampass);
1431 } else {
1432 struct login_cache cache_entry;
1434 cache_entry.entry_timestamp = time(NULL);
1435 cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1436 cache_entry.bad_password_count = badcount;
1437 cache_entry.bad_password_time = badtime;
1439 DEBUG(7, ("Updating bad password count and time in login cache\n"));
1440 login_cache_write(sampass, &cache_entry);
1444 return True;
1447 /**********************************************************************
1448 End enumeration of the LDAP password list.
1449 *********************************************************************/
1451 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1453 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1454 if (ldap_state->result) {
1455 ldap_msgfree(ldap_state->result);
1456 ldap_state->result = NULL;
1460 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1461 const char *new_attr)
1463 int i;
1465 if (new_attr == NULL) {
1466 return;
1469 for (i=0; (*attr_list)[i] != NULL; i++) {
1473 (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1474 const char *, i+2);
1475 SMB_ASSERT((*attr_list) != NULL);
1476 (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1477 (*attr_list)[i+1] = NULL;
1480 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1481 const char ***attr_list)
1483 append_attr(mem_ctx, attr_list, "uidNumber");
1484 append_attr(mem_ctx, attr_list, "gidNumber");
1485 append_attr(mem_ctx, attr_list, "homeDirectory");
1486 append_attr(mem_ctx, attr_list, "loginShell");
1487 append_attr(mem_ctx, attr_list, "gecos");
1490 /**********************************************************************
1491 Get struct samu entry from LDAP by username.
1492 *********************************************************************/
1494 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1496 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1497 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1498 LDAPMessage *result = NULL;
1499 LDAPMessage *entry = NULL;
1500 int count;
1501 const char ** attr_list;
1502 int rc;
1504 attr_list = get_userattr_list( user, ldap_state->schema_ver );
1505 append_attr(user, &attr_list,
1506 get_userattr_key2string(ldap_state->schema_ver,
1507 LDAP_ATTR_MOD_TIMESTAMP));
1508 ldapsam_add_unix_attributes(user, &attr_list);
1509 rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1510 attr_list);
1511 TALLOC_FREE( attr_list );
1513 if ( rc != LDAP_SUCCESS )
1514 return NT_STATUS_NO_SUCH_USER;
1516 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1518 if (count < 1) {
1519 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1520 ldap_msgfree(result);
1521 return NT_STATUS_NO_SUCH_USER;
1522 } else if (count > 1) {
1523 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1524 ldap_msgfree(result);
1525 return NT_STATUS_NO_SUCH_USER;
1528 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1529 if (entry) {
1530 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1531 DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1532 ldap_msgfree(result);
1533 return NT_STATUS_NO_SUCH_USER;
1535 pdb_set_backend_private_data(user, result, NULL,
1536 my_methods, PDB_CHANGED);
1537 talloc_autofree_ldapmsg(user, result);
1538 ret = NT_STATUS_OK;
1539 } else {
1540 ldap_msgfree(result);
1542 return ret;
1545 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state,
1546 const struct dom_sid *sid, LDAPMessage **result)
1548 int rc = -1;
1549 const char ** attr_list;
1551 switch ( ldap_state->schema_ver ) {
1552 case SCHEMAVER_SAMBASAMACCOUNT: {
1553 TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1554 if (tmp_ctx == NULL) {
1555 return LDAP_NO_MEMORY;
1558 attr_list = get_userattr_list(tmp_ctx,
1559 ldap_state->schema_ver);
1560 append_attr(tmp_ctx, &attr_list,
1561 get_userattr_key2string(
1562 ldap_state->schema_ver,
1563 LDAP_ATTR_MOD_TIMESTAMP));
1564 ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1565 rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1566 result, attr_list);
1567 TALLOC_FREE(tmp_ctx);
1569 if ( rc != LDAP_SUCCESS )
1570 return rc;
1571 break;
1574 default:
1575 DEBUG(0,("Invalid schema version specified\n"));
1576 break;
1578 return rc;
1581 /**********************************************************************
1582 Get struct samu entry from LDAP by SID.
1583 *********************************************************************/
1585 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1587 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1588 LDAPMessage *result = NULL;
1589 LDAPMessage *entry = NULL;
1590 int count;
1591 int rc;
1593 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
1594 sid, &result);
1595 if (rc != LDAP_SUCCESS)
1596 return NT_STATUS_NO_SUCH_USER;
1598 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1600 if (count < 1) {
1601 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1602 "count=%d\n", sid_string_dbg(sid), count));
1603 ldap_msgfree(result);
1604 return NT_STATUS_NO_SUCH_USER;
1605 } else if (count > 1) {
1606 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1607 "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1608 count));
1609 ldap_msgfree(result);
1610 return NT_STATUS_NO_SUCH_USER;
1613 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1614 if (!entry) {
1615 ldap_msgfree(result);
1616 return NT_STATUS_NO_SUCH_USER;
1619 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1620 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1621 ldap_msgfree(result);
1622 return NT_STATUS_NO_SUCH_USER;
1625 pdb_set_backend_private_data(user, result, NULL,
1626 my_methods, PDB_CHANGED);
1627 talloc_autofree_ldapmsg(user, result);
1628 return NT_STATUS_OK;
1631 /********************************************************************
1632 Do the actual modification - also change a plaintext passord if
1633 it it set.
1634 **********************************************************************/
1636 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods,
1637 struct samu *newpwd, char *dn,
1638 LDAPMod **mods, int ldap_op,
1639 bool (*need_update)(const struct samu *, enum pdb_elements))
1641 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1642 int rc;
1644 if (!newpwd || !dn) {
1645 return NT_STATUS_INVALID_PARAMETER;
1648 if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1649 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1650 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1651 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1652 BerElement *ber;
1653 struct berval *bv;
1654 char *retoid = NULL;
1655 struct berval *retdata = NULL;
1656 char *utf8_password;
1657 char *utf8_dn;
1658 size_t converted_size;
1659 int ret;
1661 if (!ldap_state->is_nds_ldap) {
1663 if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct,
1664 LDAP_EXOP_MODIFY_PASSWD)) {
1665 DEBUG(2, ("ldap password change requested, but LDAP "
1666 "server does not support it -- ignoring\n"));
1667 return NT_STATUS_OK;
1671 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1672 pdb_get_plaintext_passwd(newpwd),
1673 &converted_size))
1675 return NT_STATUS_NO_MEMORY;
1678 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1679 TALLOC_FREE(utf8_password);
1680 return NT_STATUS_NO_MEMORY;
1683 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1684 DEBUG(0,("ber_alloc_t returns NULL\n"));
1685 TALLOC_FREE(utf8_password);
1686 TALLOC_FREE(utf8_dn);
1687 return NT_STATUS_UNSUCCESSFUL;
1690 if ((ber_printf (ber, "{") < 0) ||
1691 (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1692 utf8_dn) < 0)) {
1693 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1694 "value <0\n"));
1695 ber_free(ber,1);
1696 TALLOC_FREE(utf8_dn);
1697 TALLOC_FREE(utf8_password);
1698 return NT_STATUS_UNSUCCESSFUL;
1701 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1702 ret = ber_printf(ber, "ts}",
1703 LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1704 utf8_password);
1705 } else {
1706 ret = ber_printf(ber, "}");
1709 if (ret < 0) {
1710 DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1711 "value <0\n"));
1712 ber_free(ber,1);
1713 TALLOC_FREE(utf8_dn);
1714 TALLOC_FREE(utf8_password);
1715 return NT_STATUS_UNSUCCESSFUL;
1718 if ((rc = ber_flatten (ber, &bv))<0) {
1719 DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1720 ber_free(ber,1);
1721 TALLOC_FREE(utf8_dn);
1722 TALLOC_FREE(utf8_password);
1723 return NT_STATUS_UNSUCCESSFUL;
1726 TALLOC_FREE(utf8_dn);
1727 TALLOC_FREE(utf8_password);
1728 ber_free(ber, 1);
1730 if (!ldap_state->is_nds_ldap) {
1731 rc = smbldap_extended_operation(ldap_state->smbldap_state,
1732 LDAP_EXOP_MODIFY_PASSWD,
1733 bv, NULL, NULL, &retoid,
1734 &retdata);
1735 } else {
1736 rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1737 pdb_get_plaintext_passwd(newpwd));
1739 if (rc != LDAP_SUCCESS) {
1740 char *ld_error = NULL;
1742 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1743 DEBUG(3, ("Could not set userPassword "
1744 "attribute due to an objectClass "
1745 "violation -- ignoring\n"));
1746 ber_bvfree(bv);
1747 return NT_STATUS_OK;
1750 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1751 &ld_error);
1752 DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1753 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1754 SAFE_FREE(ld_error);
1755 ber_bvfree(bv);
1756 #if defined(LDAP_CONSTRAINT_VIOLATION)
1757 if (rc == LDAP_CONSTRAINT_VIOLATION)
1758 return NT_STATUS_PASSWORD_RESTRICTION;
1759 #endif
1760 return NT_STATUS_UNSUCCESSFUL;
1761 } else {
1762 DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1763 #ifdef DEBUG_PASSWORD
1764 DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1765 #endif
1766 if (retdata)
1767 ber_bvfree(retdata);
1768 if (retoid)
1769 ldap_memfree(retoid);
1771 ber_bvfree(bv);
1774 if (!mods) {
1775 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1776 /* may be password change below however */
1777 } else {
1778 switch(ldap_op) {
1779 case LDAP_MOD_ADD:
1780 if (ldap_state->is_nds_ldap) {
1781 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1782 "objectclass",
1783 "inetOrgPerson");
1784 } else {
1785 smbldap_set_mod(&mods, LDAP_MOD_ADD,
1786 "objectclass",
1787 LDAP_OBJ_ACCOUNT);
1789 rc = smbldap_add(ldap_state->smbldap_state,
1790 dn, mods);
1791 break;
1792 case LDAP_MOD_REPLACE:
1793 rc = smbldap_modify(ldap_state->smbldap_state,
1794 dn ,mods);
1795 break;
1796 default:
1797 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1798 ldap_op));
1799 return NT_STATUS_INVALID_PARAMETER;
1802 if (rc!=LDAP_SUCCESS) {
1803 return NT_STATUS_UNSUCCESSFUL;
1807 return NT_STATUS_OK;
1810 /**********************************************************************
1811 Delete entry from LDAP for username.
1812 *********************************************************************/
1814 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1815 struct samu * sam_acct)
1817 struct ldapsam_privates *priv =
1818 (struct ldapsam_privates *)my_methods->private_data;
1819 const char *sname;
1820 int rc;
1821 LDAPMessage *msg, *entry;
1822 NTSTATUS result = NT_STATUS_NO_MEMORY;
1823 const char **attr_list;
1824 TALLOC_CTX *mem_ctx;
1826 if (!sam_acct) {
1827 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1828 return NT_STATUS_INVALID_PARAMETER;
1831 sname = pdb_get_username(sam_acct);
1833 DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1834 "LDAP.\n", sname));
1836 mem_ctx = talloc_new(NULL);
1837 if (mem_ctx == NULL) {
1838 DEBUG(0, ("talloc_new failed\n"));
1839 goto done;
1842 attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1843 if (attr_list == NULL) {
1844 goto done;
1847 rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1849 if ((rc != LDAP_SUCCESS) ||
1850 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1851 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1852 DEBUG(5, ("Could not find user %s\n", sname));
1853 result = NT_STATUS_NO_SUCH_USER;
1854 goto done;
1857 rc = ldapsam_delete_entry(
1858 priv, mem_ctx, entry,
1859 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1860 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1861 attr_list);
1863 result = (rc == LDAP_SUCCESS) ?
1864 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1866 done:
1867 TALLOC_FREE(mem_ctx);
1868 return result;
1871 /**********************************************************************
1872 Update struct samu.
1873 *********************************************************************/
1875 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1877 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1878 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1879 int rc = 0;
1880 char *dn;
1881 LDAPMessage *result = NULL;
1882 LDAPMessage *entry = NULL;
1883 LDAPMod **mods = NULL;
1884 const char **attr_list;
1886 result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1887 if (!result) {
1888 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1889 if (pdb_get_username(newpwd) == NULL) {
1890 return NT_STATUS_INVALID_PARAMETER;
1892 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1893 TALLOC_FREE( attr_list );
1894 if (rc != LDAP_SUCCESS) {
1895 return NT_STATUS_UNSUCCESSFUL;
1897 pdb_set_backend_private_data(newpwd, result, NULL,
1898 my_methods, PDB_CHANGED);
1899 talloc_autofree_ldapmsg(newpwd, result);
1902 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1903 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1904 return NT_STATUS_UNSUCCESSFUL;
1907 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1908 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1909 if (!dn) {
1910 return NT_STATUS_UNSUCCESSFUL;
1913 DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1915 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1916 pdb_element_is_changed)) {
1917 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1918 TALLOC_FREE(dn);
1919 if (mods != NULL)
1920 ldap_mods_free(mods,True);
1921 return NT_STATUS_UNSUCCESSFUL;
1924 if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1925 && (mods == NULL)) {
1926 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1927 pdb_get_username(newpwd)));
1928 TALLOC_FREE(dn);
1929 return NT_STATUS_OK;
1932 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1934 if (mods != NULL) {
1935 ldap_mods_free(mods,True);
1938 TALLOC_FREE(dn);
1941 * We need to set the backend private data to NULL here. For example
1942 * setuserinfo level 25 does a pdb_update_sam_account twice on the
1943 * same one, and with the explicit delete / add logic for attribute
1944 * values the second time we would use the wrong "old" value which
1945 * does not exist in LDAP anymore. Thus the LDAP server would refuse
1946 * the update.
1947 * The existing LDAPMessage is still being auto-freed by the
1948 * destructor.
1950 pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1951 PDB_CHANGED);
1953 if (!NT_STATUS_IS_OK(ret)) {
1954 return ret;
1957 DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1958 pdb_get_username(newpwd)));
1959 return NT_STATUS_OK;
1962 /***************************************************************************
1963 Renames a struct samu
1964 - The "rename user script" has full responsibility for changing everything
1965 ***************************************************************************/
1967 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1968 TALLOC_CTX *tmp_ctx,
1969 uint32_t group_rid,
1970 uint32_t member_rid);
1972 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1973 TALLOC_CTX *mem_ctx,
1974 struct samu *user,
1975 struct dom_sid **pp_sids,
1976 gid_t **pp_gids,
1977 uint32_t *p_num_groups);
1979 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1980 struct samu *old_acct,
1981 const char *newname)
1983 const char *oldname;
1984 int rc;
1985 char *rename_script = NULL;
1986 fstring oldname_lower, newname_lower;
1988 if (!old_acct) {
1989 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1990 return NT_STATUS_INVALID_PARAMETER;
1992 if (!newname) {
1993 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1994 return NT_STATUS_INVALID_PARAMETER;
1997 oldname = pdb_get_username(old_acct);
1999 /* rename the posix user */
2000 rename_script = lp_renameuser_script(talloc_tos());
2001 if (rename_script == NULL) {
2002 return NT_STATUS_NO_MEMORY;
2005 if (!(*rename_script)) {
2006 TALLOC_FREE(rename_script);
2007 return NT_STATUS_ACCESS_DENIED;
2010 DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2011 oldname, newname));
2013 /* We have to allow the account name to end with a '$'.
2014 Also, follow the semantics in _samr_create_user() and lower case the
2015 posix name but preserve the case in passdb */
2017 fstrcpy( oldname_lower, oldname );
2018 strlower_m( oldname_lower );
2019 fstrcpy( newname_lower, newname );
2020 strlower_m( newname_lower );
2021 rename_script = realloc_string_sub2(rename_script,
2022 "%unew",
2023 newname_lower,
2024 true,
2025 true);
2026 if (!rename_script) {
2027 return NT_STATUS_NO_MEMORY;
2029 rename_script = realloc_string_sub2(rename_script,
2030 "%uold",
2031 oldname_lower,
2032 true,
2033 true);
2034 rc = smbrun(rename_script, NULL);
2036 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2037 rename_script, rc));
2039 TALLOC_FREE(rename_script);
2041 if (rc == 0) {
2042 smb_nscd_flush_user_cache();
2045 if (rc)
2046 return NT_STATUS_UNSUCCESSFUL;
2048 return NT_STATUS_OK;
2051 /**********************************************************************
2052 Add struct samu to LDAP.
2053 *********************************************************************/
2055 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2057 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2058 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2059 int rc;
2060 LDAPMessage *result = NULL;
2061 LDAPMessage *entry = NULL;
2062 LDAPMod **mods = NULL;
2063 int ldap_op = LDAP_MOD_REPLACE;
2064 uint32_t num_result;
2065 const char **attr_list;
2066 char *escape_user = NULL;
2067 const char *username = pdb_get_username(newpwd);
2068 const struct dom_sid *sid = pdb_get_user_sid(newpwd);
2069 char *filter = NULL;
2070 char *dn = NULL;
2071 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2072 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2074 if (!ctx) {
2075 return NT_STATUS_NO_MEMORY;
2078 if (!username || !*username) {
2079 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2080 status = NT_STATUS_INVALID_PARAMETER;
2081 goto fn_exit;
2084 /* free this list after the second search or in case we exit on failure */
2085 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2087 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2089 if (rc != LDAP_SUCCESS) {
2090 goto fn_exit;
2093 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2094 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2095 username));
2096 goto fn_exit;
2098 ldap_msgfree(result);
2099 result = NULL;
2101 if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2102 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2103 sid, &result);
2104 if (rc == LDAP_SUCCESS) {
2105 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2106 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2107 "already in the base, with samba "
2108 "attributes\n", sid_string_dbg(sid)));
2109 goto fn_exit;
2111 ldap_msgfree(result);
2112 result = NULL;
2116 /* does the entry already exist but without a samba attributes?
2117 we need to return the samba attributes here */
2119 escape_user = escape_ldap_string(talloc_tos(), username);
2120 filter = talloc_strdup(attr_list, "(uid=%u)");
2121 if (!filter) {
2122 status = NT_STATUS_NO_MEMORY;
2123 goto fn_exit;
2125 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2126 TALLOC_FREE(escape_user);
2127 if (!filter) {
2128 status = NT_STATUS_NO_MEMORY;
2129 goto fn_exit;
2132 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2133 filter, attr_list, &result);
2134 if ( rc != LDAP_SUCCESS ) {
2135 goto fn_exit;
2138 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2140 if (num_result > 1) {
2141 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2142 goto fn_exit;
2145 /* Check if we need to update an existing entry */
2146 if (num_result == 1) {
2147 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2148 ldap_op = LDAP_MOD_REPLACE;
2149 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2150 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2151 if (!dn) {
2152 status = NT_STATUS_NO_MEMORY;
2153 goto fn_exit;
2156 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2158 /* There might be a SID for this account already - say an idmap entry */
2160 filter = talloc_asprintf(ctx,
2161 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2162 get_userattr_key2string(ldap_state->schema_ver,
2163 LDAP_ATTR_USER_SID),
2164 sid_string_talloc(ctx, sid),
2165 LDAP_OBJ_IDMAP_ENTRY,
2166 LDAP_OBJ_SID_ENTRY);
2167 if (!filter) {
2168 status = NT_STATUS_NO_MEMORY;
2169 goto fn_exit;
2172 /* free old result before doing a new search */
2173 if (result != NULL) {
2174 ldap_msgfree(result);
2175 result = NULL;
2177 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2178 filter, attr_list, &result);
2180 if ( rc != LDAP_SUCCESS ) {
2181 goto fn_exit;
2184 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2186 if (num_result > 1) {
2187 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2188 goto fn_exit;
2191 /* Check if we need to update an existing entry */
2192 if (num_result == 1) {
2194 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2195 ldap_op = LDAP_MOD_REPLACE;
2196 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2197 dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2198 if (!dn) {
2199 status = NT_STATUS_NO_MEMORY;
2200 goto fn_exit;
2205 if (num_result == 0) {
2206 char *escape_username;
2207 /* Check if we need to add an entry */
2208 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2209 ldap_op = LDAP_MOD_ADD;
2211 escape_username = escape_rdn_val_string_alloc(username);
2212 if (!escape_username) {
2213 status = NT_STATUS_NO_MEMORY;
2214 goto fn_exit;
2217 if (username[strlen(username)-1] == '$') {
2218 dn = talloc_asprintf(ctx,
2219 "uid=%s,%s",
2220 escape_username,
2221 lp_ldap_machine_suffix(talloc_tos()));
2222 } else {
2223 dn = talloc_asprintf(ctx,
2224 "uid=%s,%s",
2225 escape_username,
2226 lp_ldap_user_suffix(talloc_tos()));
2229 SAFE_FREE(escape_username);
2230 if (!dn) {
2231 status = NT_STATUS_NO_MEMORY;
2232 goto fn_exit;
2236 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2237 pdb_element_is_set_or_changed)) {
2238 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2239 if (mods != NULL) {
2240 ldap_mods_free(mods, true);
2242 goto fn_exit;
2245 if (mods == NULL) {
2246 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2247 goto fn_exit;
2249 switch ( ldap_state->schema_ver ) {
2250 case SCHEMAVER_SAMBASAMACCOUNT:
2251 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2252 break;
2253 default:
2254 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2255 break;
2258 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2259 if (!NT_STATUS_IS_OK(ret)) {
2260 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2261 pdb_get_username(newpwd),dn));
2262 ldap_mods_free(mods, true);
2263 goto fn_exit;
2266 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2267 ldap_mods_free(mods, true);
2269 status = NT_STATUS_OK;
2271 fn_exit:
2273 TALLOC_FREE(ctx);
2274 if (result) {
2275 ldap_msgfree(result);
2277 return status;
2280 /**********************************************************************
2281 *********************************************************************/
2283 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2284 const char *filter,
2285 LDAPMessage ** result)
2287 int scope = LDAP_SCOPE_SUBTREE;
2288 int rc;
2289 const char **attr_list;
2291 attr_list = get_attr_list(NULL, groupmap_attr_list);
2292 rc = smbldap_search(ldap_state->smbldap_state,
2293 lp_ldap_suffix (talloc_tos()), scope,
2294 filter, attr_list, 0, result);
2295 TALLOC_FREE(attr_list);
2297 return rc;
2300 /**********************************************************************
2301 *********************************************************************/
2303 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2304 GROUP_MAP *map, LDAPMessage *entry)
2306 char *temp = NULL;
2307 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2309 if (ldap_state == NULL || map == NULL || entry == NULL ||
2310 ldap_state->smbldap_state->ldap_struct == NULL) {
2311 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2312 TALLOC_FREE(ctx);
2313 return false;
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_GIDNUMBER),
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_GIDNUMBER)));
2325 TALLOC_FREE(ctx);
2326 return false;
2328 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2330 map->gid = (gid_t)atol(temp);
2332 TALLOC_FREE(temp);
2333 temp = smbldap_talloc_single_attribute(
2334 ldap_state->smbldap_state->ldap_struct,
2335 entry,
2336 get_attr_key2string(groupmap_attr_list,
2337 LDAP_ATTR_GROUP_SID),
2338 ctx);
2339 if (!temp) {
2340 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2341 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2342 TALLOC_FREE(ctx);
2343 return false;
2346 if (!string_to_sid(&map->sid, temp)) {
2347 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2348 TALLOC_FREE(ctx);
2349 return false;
2352 TALLOC_FREE(temp);
2353 temp = smbldap_talloc_single_attribute(
2354 ldap_state->smbldap_state->ldap_struct,
2355 entry,
2356 get_attr_key2string(groupmap_attr_list,
2357 LDAP_ATTR_GROUP_TYPE),
2358 ctx);
2359 if (!temp) {
2360 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2361 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2362 TALLOC_FREE(ctx);
2363 return false;
2365 map->sid_name_use = (enum lsa_SidType)atol(temp);
2367 if ((map->sid_name_use < SID_NAME_USER) ||
2368 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2369 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2370 TALLOC_FREE(ctx);
2371 return false;
2374 TALLOC_FREE(temp);
2375 temp = smbldap_talloc_single_attribute(
2376 ldap_state->smbldap_state->ldap_struct,
2377 entry,
2378 get_attr_key2string(groupmap_attr_list,
2379 LDAP_ATTR_DISPLAY_NAME),
2380 ctx);
2381 if (!temp) {
2382 temp = smbldap_talloc_single_attribute(
2383 ldap_state->smbldap_state->ldap_struct,
2384 entry,
2385 get_attr_key2string(groupmap_attr_list,
2386 LDAP_ATTR_CN),
2387 ctx);
2388 if (!temp) {
2389 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2390 for gidNumber(%lu)\n",(unsigned long)map->gid));
2391 TALLOC_FREE(ctx);
2392 return false;
2395 map->nt_name = talloc_strdup(map, temp);
2396 if (!map->nt_name) {
2397 TALLOC_FREE(ctx);
2398 return false;
2401 TALLOC_FREE(temp);
2402 temp = smbldap_talloc_single_attribute(
2403 ldap_state->smbldap_state->ldap_struct,
2404 entry,
2405 get_attr_key2string(groupmap_attr_list,
2406 LDAP_ATTR_DESC),
2407 ctx);
2408 if (!temp) {
2409 temp = talloc_strdup(ctx, "");
2410 if (!temp) {
2411 TALLOC_FREE(ctx);
2412 return false;
2415 map->comment = talloc_strdup(map, temp);
2416 if (!map->comment) {
2417 TALLOC_FREE(ctx);
2418 return false;
2421 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2422 struct unixid id;
2423 id.id = map->gid;
2424 id.type = ID_TYPE_GID;
2426 idmap_cache_set_sid2unixid(&map->sid, &id);
2429 TALLOC_FREE(ctx);
2430 return true;
2433 /**********************************************************************
2434 *********************************************************************/
2436 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2437 const char *filter,
2438 GROUP_MAP *map)
2440 struct ldapsam_privates *ldap_state =
2441 (struct ldapsam_privates *)methods->private_data;
2442 LDAPMessage *result = NULL;
2443 LDAPMessage *entry = NULL;
2444 int count;
2446 if (ldapsam_search_one_group(ldap_state, filter, &result)
2447 != LDAP_SUCCESS) {
2448 return NT_STATUS_NO_SUCH_GROUP;
2451 count = ldap_count_entries(priv2ld(ldap_state), result);
2453 if (count < 1) {
2454 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2455 "%s\n", filter));
2456 ldap_msgfree(result);
2457 return NT_STATUS_NO_SUCH_GROUP;
2460 if (count > 1) {
2461 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2462 "count=%d\n", filter, count));
2463 ldap_msgfree(result);
2464 return NT_STATUS_NO_SUCH_GROUP;
2467 entry = ldap_first_entry(priv2ld(ldap_state), result);
2469 if (!entry) {
2470 ldap_msgfree(result);
2471 return NT_STATUS_UNSUCCESSFUL;
2474 if (!init_group_from_ldap(ldap_state, map, entry)) {
2475 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2476 "group filter %s\n", filter));
2477 ldap_msgfree(result);
2478 return NT_STATUS_NO_SUCH_GROUP;
2481 ldap_msgfree(result);
2482 return NT_STATUS_OK;
2485 /**********************************************************************
2486 *********************************************************************/
2488 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2489 struct dom_sid sid)
2491 char *filter = NULL;
2492 NTSTATUS status;
2493 fstring tmp;
2495 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2496 LDAP_OBJ_GROUPMAP,
2497 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2498 sid_to_fstring(tmp, &sid)) < 0) {
2499 return NT_STATUS_NO_MEMORY;
2502 status = ldapsam_getgroup(methods, filter, map);
2503 SAFE_FREE(filter);
2504 return status;
2507 /**********************************************************************
2508 *********************************************************************/
2510 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2511 gid_t gid)
2513 char *filter = NULL;
2514 NTSTATUS status;
2516 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2517 LDAP_OBJ_GROUPMAP,
2518 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2519 (unsigned long)gid) < 0) {
2520 return NT_STATUS_NO_MEMORY;
2523 status = ldapsam_getgroup(methods, filter, map);
2524 SAFE_FREE(filter);
2525 return status;
2528 /**********************************************************************
2529 *********************************************************************/
2531 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2532 const char *name)
2534 char *filter = NULL;
2535 char *escape_name = escape_ldap_string(talloc_tos(), name);
2536 NTSTATUS status;
2538 if (!escape_name) {
2539 return NT_STATUS_NO_MEMORY;
2542 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2543 LDAP_OBJ_GROUPMAP,
2544 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2545 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2546 escape_name) < 0) {
2547 TALLOC_FREE(escape_name);
2548 return NT_STATUS_NO_MEMORY;
2551 TALLOC_FREE(escape_name);
2552 status = ldapsam_getgroup(methods, filter, map);
2553 SAFE_FREE(filter);
2554 return status;
2557 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2558 LDAPMessage *entry,
2559 const struct dom_sid *domain_sid,
2560 uint32_t *rid)
2562 fstring str;
2563 struct dom_sid sid;
2565 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2566 str, sizeof(str)-1)) {
2567 DEBUG(10, ("Could not find sambaSID attribute\n"));
2568 return False;
2571 if (!string_to_sid(&sid, str)) {
2572 DEBUG(10, ("Could not convert string %s to sid\n", str));
2573 return False;
2576 if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2577 DEBUG(10, ("SID %s is not in expected domain %s\n",
2578 str, sid_string_dbg(domain_sid)));
2579 return False;
2582 if (!sid_peek_rid(&sid, rid)) {
2583 DEBUG(10, ("Could not peek into RID\n"));
2584 return False;
2587 return True;
2590 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2591 TALLOC_CTX *mem_ctx,
2592 const struct dom_sid *group,
2593 uint32_t **pp_member_rids,
2594 size_t *p_num_members)
2596 struct ldapsam_privates *ldap_state =
2597 (struct ldapsam_privates *)methods->private_data;
2598 struct smbldap_state *conn = ldap_state->smbldap_state;
2599 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2600 const char *sid_attrs[] = { "sambaSID", NULL };
2601 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2602 LDAPMessage *result = NULL;
2603 LDAPMessage *entry;
2604 char *filter;
2605 char **values = NULL;
2606 char **memberuid;
2607 char *gidstr;
2608 int rc, count;
2610 *pp_member_rids = NULL;
2611 *p_num_members = 0;
2613 filter = talloc_asprintf(mem_ctx,
2614 "(&(objectClass=%s)"
2615 "(objectClass=%s)"
2616 "(sambaSID=%s))",
2617 LDAP_OBJ_POSIXGROUP,
2618 LDAP_OBJ_GROUPMAP,
2619 sid_string_talloc(mem_ctx, group));
2620 if (filter == NULL) {
2621 ret = NT_STATUS_NO_MEMORY;
2622 goto done;
2625 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2626 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2627 &result);
2629 if (rc != LDAP_SUCCESS)
2630 goto done;
2632 talloc_autofree_ldapmsg(mem_ctx, result);
2634 count = ldap_count_entries(conn->ldap_struct, result);
2636 if (count > 1) {
2637 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2638 sid_string_dbg(group)));
2639 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2640 goto done;
2643 if (count == 0) {
2644 ret = NT_STATUS_NO_SUCH_GROUP;
2645 goto done;
2648 entry = ldap_first_entry(conn->ldap_struct, result);
2649 if (entry == NULL)
2650 goto done;
2652 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2653 if (!gidstr) {
2654 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2655 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2656 goto done;
2659 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2661 if ((values != NULL) && (values[0] != NULL)) {
2663 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2664 if (filter == NULL) {
2665 ret = NT_STATUS_NO_MEMORY;
2666 goto done;
2669 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2670 char *escape_memberuid;
2672 escape_memberuid = escape_ldap_string(talloc_tos(),
2673 *memberuid);
2674 if (escape_memberuid == NULL) {
2675 ret = NT_STATUS_NO_MEMORY;
2676 goto done;
2679 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2680 TALLOC_FREE(escape_memberuid);
2681 if (filter == NULL) {
2682 ret = NT_STATUS_NO_MEMORY;
2683 goto done;
2687 filter = talloc_asprintf_append_buffer(filter, "))");
2688 if (filter == NULL) {
2689 ret = NT_STATUS_NO_MEMORY;
2690 goto done;
2693 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2694 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2695 &result);
2697 if (rc != LDAP_SUCCESS)
2698 goto done;
2700 count = ldap_count_entries(conn->ldap_struct, result);
2701 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2703 talloc_autofree_ldapmsg(mem_ctx, result);
2705 for (entry = ldap_first_entry(conn->ldap_struct, result);
2706 entry != NULL;
2707 entry = ldap_next_entry(conn->ldap_struct, entry))
2709 char *sidstr;
2710 struct dom_sid sid;
2711 uint32_t rid;
2713 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2714 entry, "sambaSID",
2715 mem_ctx);
2716 if (!sidstr) {
2717 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2718 "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2719 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2720 goto done;
2723 if (!string_to_sid(&sid, sidstr))
2724 goto done;
2726 if (!sid_check_is_in_our_sam(&sid)) {
2727 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2728 "in our domain\n"));
2729 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2730 goto done;
2733 sid_peek_rid(&sid, &rid);
2735 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2736 p_num_members)) {
2737 ret = NT_STATUS_NO_MEMORY;
2738 goto done;
2743 filter = talloc_asprintf(mem_ctx,
2744 "(&(objectClass=%s)"
2745 "(gidNumber=%s))",
2746 LDAP_OBJ_SAMBASAMACCOUNT,
2747 gidstr);
2749 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2750 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2751 &result);
2753 if (rc != LDAP_SUCCESS)
2754 goto done;
2756 talloc_autofree_ldapmsg(mem_ctx, result);
2758 for (entry = ldap_first_entry(conn->ldap_struct, result);
2759 entry != NULL;
2760 entry = ldap_next_entry(conn->ldap_struct, entry))
2762 uint32_t rid;
2764 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2765 entry,
2766 get_global_sam_sid(),
2767 &rid)) {
2768 DEBUG(0, ("Severe DB error, %s can't miss the samba SID" "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2769 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2770 goto done;
2773 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2774 p_num_members)) {
2775 ret = NT_STATUS_NO_MEMORY;
2776 goto done;
2780 ret = NT_STATUS_OK;
2782 done:
2784 if (values)
2785 ldap_value_free(values);
2787 return ret;
2790 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2791 TALLOC_CTX *mem_ctx,
2792 struct samu *user,
2793 struct dom_sid **pp_sids,
2794 gid_t **pp_gids,
2795 uint32_t *p_num_groups)
2797 struct ldapsam_privates *ldap_state =
2798 (struct ldapsam_privates *)methods->private_data;
2799 struct smbldap_state *conn = ldap_state->smbldap_state;
2800 char *filter;
2801 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2802 char *escape_name;
2803 int rc, count;
2804 LDAPMessage *result = NULL;
2805 LDAPMessage *entry;
2806 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2807 uint32_t num_sids;
2808 uint32_t num_gids;
2809 char *gidstr;
2810 gid_t primary_gid = -1;
2812 *pp_sids = NULL;
2813 num_sids = 0;
2815 if (pdb_get_username(user) == NULL) {
2816 return NT_STATUS_INVALID_PARAMETER;
2819 escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2820 if (escape_name == NULL)
2821 return NT_STATUS_NO_MEMORY;
2823 if (user->unix_pw) {
2824 primary_gid = user->unix_pw->pw_gid;
2825 } else {
2826 /* retrieve the users primary gid */
2827 filter = talloc_asprintf(mem_ctx,
2828 "(&(objectClass=%s)(uid=%s))",
2829 LDAP_OBJ_SAMBASAMACCOUNT,
2830 escape_name);
2831 if (filter == NULL) {
2832 ret = NT_STATUS_NO_MEMORY;
2833 goto done;
2836 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2837 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2839 if (rc != LDAP_SUCCESS)
2840 goto done;
2842 talloc_autofree_ldapmsg(mem_ctx, result);
2844 count = ldap_count_entries(priv2ld(ldap_state), result);
2846 switch (count) {
2847 case 0:
2848 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2849 ret = NT_STATUS_NO_SUCH_USER;
2850 goto done;
2851 case 1:
2852 entry = ldap_first_entry(priv2ld(ldap_state), result);
2854 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2855 if (!gidstr) {
2856 DEBUG (1, ("Unable to find the member's gid!\n"));
2857 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2858 goto done;
2860 primary_gid = strtoul(gidstr, NULL, 10);
2861 break;
2862 default:
2863 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2864 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2865 goto done;
2869 filter = talloc_asprintf(mem_ctx,
2870 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2871 LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2872 if (filter == NULL) {
2873 ret = NT_STATUS_NO_MEMORY;
2874 goto done;
2877 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2878 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2880 if (rc != LDAP_SUCCESS)
2881 goto done;
2883 talloc_autofree_ldapmsg(mem_ctx, result);
2885 num_gids = 0;
2886 *pp_gids = NULL;
2888 num_sids = 0;
2889 *pp_sids = NULL;
2891 /* We need to add the primary group as the first gid/sid */
2893 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2894 ret = NT_STATUS_NO_MEMORY;
2895 goto done;
2898 /* This sid will be replaced later */
2900 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2901 &num_sids);
2902 if (!NT_STATUS_IS_OK(ret)) {
2903 goto done;
2906 for (entry = ldap_first_entry(conn->ldap_struct, result);
2907 entry != NULL;
2908 entry = ldap_next_entry(conn->ldap_struct, entry))
2910 fstring str;
2911 struct dom_sid sid;
2912 gid_t gid;
2913 char *end;
2915 if (!smbldap_get_single_attribute(conn->ldap_struct,
2916 entry, "sambaSID",
2917 str, sizeof(str)-1))
2918 continue;
2920 if (!string_to_sid(&sid, str))
2921 goto done;
2923 if (!smbldap_get_single_attribute(conn->ldap_struct,
2924 entry, "gidNumber",
2925 str, sizeof(str)-1))
2926 continue;
2928 gid = strtoul(str, &end, 10);
2930 if (PTR_DIFF(end, str) != strlen(str))
2931 goto done;
2933 if (gid == primary_gid) {
2934 sid_copy(&(*pp_sids)[0], &sid);
2935 } else {
2936 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2937 &num_gids)) {
2938 ret = NT_STATUS_NO_MEMORY;
2939 goto done;
2941 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2942 &num_sids);
2943 if (!NT_STATUS_IS_OK(ret)) {
2944 goto done;
2949 if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2950 DEBUG(3, ("primary group of [%s] not found\n",
2951 pdb_get_username(user)));
2952 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2953 goto done;
2956 *p_num_groups = num_sids;
2958 ret = NT_STATUS_OK;
2960 done:
2962 TALLOC_FREE(escape_name);
2963 return ret;
2966 /**********************************************************************
2967 * Augment a posixGroup object with a sambaGroupMapping domgroup
2968 *********************************************************************/
2970 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2971 struct ldapsam_privates *ldap_state,
2972 GROUP_MAP *map)
2974 const char *filter, *dn;
2975 LDAPMessage *msg, *entry;
2976 LDAPMod **mods;
2977 int rc;
2979 filter = talloc_asprintf(mem_ctx,
2980 "(&(objectClass=%s)(gidNumber=%u))",
2981 LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2982 if (filter == NULL) {
2983 return NT_STATUS_NO_MEMORY;
2986 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2987 get_attr_list(mem_ctx, groupmap_attr_list),
2988 &msg);
2989 talloc_autofree_ldapmsg(mem_ctx, msg);
2991 if ((rc != LDAP_SUCCESS) ||
2992 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2993 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2994 return NT_STATUS_NO_SUCH_GROUP;
2997 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2998 if (dn == NULL) {
2999 return NT_STATUS_NO_MEMORY;
3002 mods = NULL;
3003 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3004 LDAP_OBJ_GROUPMAP);
3005 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3006 sid_string_talloc(mem_ctx, &map->sid));
3007 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3008 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3009 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3010 map->nt_name);
3011 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3012 map->comment);
3013 talloc_autofree_ldapmod(mem_ctx, mods);
3015 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3016 if (rc != LDAP_SUCCESS) {
3017 return NT_STATUS_ACCESS_DENIED;
3020 return NT_STATUS_OK;
3023 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3024 GROUP_MAP *map)
3026 struct ldapsam_privates *ldap_state =
3027 (struct ldapsam_privates *)methods->private_data;
3028 LDAPMessage *msg = NULL;
3029 LDAPMod **mods = NULL;
3030 const char *attrs[] = { NULL };
3031 char *filter;
3033 char *dn;
3034 TALLOC_CTX *mem_ctx;
3035 NTSTATUS result;
3037 struct dom_sid sid;
3039 int rc;
3041 mem_ctx = talloc_new(NULL);
3042 if (mem_ctx == NULL) {
3043 DEBUG(0, ("talloc_new failed\n"));
3044 return NT_STATUS_NO_MEMORY;
3047 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3048 sid_string_talloc(mem_ctx, &map->sid));
3049 if (filter == NULL) {
3050 result = NT_STATUS_NO_MEMORY;
3051 goto done;
3054 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3055 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3056 talloc_autofree_ldapmsg(mem_ctx, msg);
3058 if ((rc == LDAP_SUCCESS) &&
3059 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3061 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3062 "group mapping entry\n", sid_string_dbg(&map->sid)));
3063 result = NT_STATUS_GROUP_EXISTS;
3064 goto done;
3067 switch (map->sid_name_use) {
3069 case SID_NAME_DOM_GRP:
3070 /* To map a domain group we need to have a posix group
3071 to attach to. */
3072 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3073 goto done;
3074 break;
3076 case SID_NAME_ALIAS:
3077 if (!sid_check_is_in_our_sam(&map->sid)
3078 && !sid_check_is_in_builtin(&map->sid) )
3080 DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3081 sid_string_dbg(&map->sid)));
3082 result = NT_STATUS_INVALID_PARAMETER;
3083 goto done;
3085 break;
3087 default:
3088 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3089 sid_type_lookup(map->sid_name_use)));
3090 result = NT_STATUS_INVALID_PARAMETER;
3091 goto done;
3094 /* Domain groups have been mapped in a separate routine, we have to
3095 * create an alias now */
3097 if (map->gid == -1) {
3098 DEBUG(10, ("Refusing to map gid==-1\n"));
3099 result = NT_STATUS_INVALID_PARAMETER;
3100 goto done;
3103 if (pdb_gid_to_sid(map->gid, &sid)) {
3104 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3105 "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3106 result = NT_STATUS_GROUP_EXISTS;
3107 goto done;
3110 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3111 * the best we can get out of LDAP. */
3113 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3114 sid_string_talloc(mem_ctx, &map->sid),
3115 lp_ldap_group_suffix(talloc_tos()));
3116 if (dn == NULL) {
3117 result = NT_STATUS_NO_MEMORY;
3118 goto done;
3121 mods = NULL;
3123 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3124 LDAP_OBJ_SID_ENTRY);
3125 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3126 LDAP_OBJ_GROUPMAP);
3127 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3128 sid_string_talloc(mem_ctx, &map->sid));
3129 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3130 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3131 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3132 map->nt_name);
3133 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3134 map->comment);
3135 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3136 talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3137 talloc_autofree_ldapmod(mem_ctx, mods);
3139 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3141 result = (rc == LDAP_SUCCESS) ?
3142 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3144 done:
3145 TALLOC_FREE(mem_ctx);
3146 return result;
3149 /**********************************************************************
3150 * Update a group mapping entry. We're quite strict about what can be changed:
3151 * Only the description and displayname may be changed. It simply does not
3152 * make any sense to change the SID, gid or the type in a mapping.
3153 *********************************************************************/
3155 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3156 GROUP_MAP *map)
3158 struct ldapsam_privates *ldap_state =
3159 (struct ldapsam_privates *)methods->private_data;
3160 int rc;
3161 const char *filter, *dn;
3162 LDAPMessage *msg = NULL;
3163 LDAPMessage *entry = NULL;
3164 LDAPMod **mods = NULL;
3165 TALLOC_CTX *mem_ctx;
3166 NTSTATUS result;
3168 mem_ctx = talloc_new(NULL);
3169 if (mem_ctx == NULL) {
3170 DEBUG(0, ("talloc_new failed\n"));
3171 return NT_STATUS_NO_MEMORY;
3174 /* Make 100% sure that sid, gid and type are not changed by looking up
3175 * exactly the values we're given in LDAP. */
3177 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3178 "(sambaSid=%s)(gidNumber=%u)"
3179 "(sambaGroupType=%d))",
3180 LDAP_OBJ_GROUPMAP,
3181 sid_string_talloc(mem_ctx, &map->sid),
3182 (unsigned int)map->gid, map->sid_name_use);
3183 if (filter == NULL) {
3184 result = NT_STATUS_NO_MEMORY;
3185 goto done;
3188 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3189 get_attr_list(mem_ctx, groupmap_attr_list),
3190 &msg);
3191 talloc_autofree_ldapmsg(mem_ctx, msg);
3193 if ((rc != LDAP_SUCCESS) ||
3194 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3195 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3196 result = NT_STATUS_NO_SUCH_GROUP;
3197 goto done;
3200 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3202 if (dn == NULL) {
3203 result = NT_STATUS_NO_MEMORY;
3204 goto done;
3207 mods = NULL;
3208 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3209 map->nt_name);
3210 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3211 map->comment);
3212 talloc_autofree_ldapmod(mem_ctx, mods);
3214 if (mods == NULL) {
3215 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3216 "nothing to do\n"));
3217 result = NT_STATUS_OK;
3218 goto done;
3221 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3223 if (rc != LDAP_SUCCESS) {
3224 result = NT_STATUS_ACCESS_DENIED;
3225 goto done;
3228 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3229 "group %lu in LDAP\n", (unsigned long)map->gid));
3231 result = NT_STATUS_OK;
3233 done:
3234 TALLOC_FREE(mem_ctx);
3235 return result;
3238 /**********************************************************************
3239 *********************************************************************/
3241 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3242 struct dom_sid sid)
3244 struct ldapsam_privates *priv =
3245 (struct ldapsam_privates *)methods->private_data;
3246 LDAPMessage *msg, *entry;
3247 int rc;
3248 NTSTATUS result;
3249 TALLOC_CTX *mem_ctx;
3250 char *filter;
3252 mem_ctx = talloc_new(NULL);
3253 if (mem_ctx == NULL) {
3254 DEBUG(0, ("talloc_new failed\n"));
3255 return NT_STATUS_NO_MEMORY;
3258 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3259 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3260 sid_string_talloc(mem_ctx, &sid));
3261 if (filter == NULL) {
3262 result = NT_STATUS_NO_MEMORY;
3263 goto done;
3265 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3266 get_attr_list(mem_ctx, groupmap_attr_list),
3267 &msg);
3268 talloc_autofree_ldapmsg(mem_ctx, msg);
3270 if ((rc != LDAP_SUCCESS) ||
3271 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3272 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3273 result = NT_STATUS_NO_SUCH_GROUP;
3274 goto done;
3277 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3278 get_attr_list(mem_ctx,
3279 groupmap_attr_list_to_delete));
3281 if ((rc == LDAP_NAMING_VIOLATION) ||
3282 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3283 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3284 const char *attrs[] = { "sambaGroupType", "description",
3285 "displayName", "sambaSIDList",
3286 NULL };
3288 /* Second try. Don't delete the sambaSID attribute, this is
3289 for "old" entries that are tacked on a winbind
3290 sambaIdmapEntry. */
3292 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3293 LDAP_OBJ_GROUPMAP, attrs);
3296 if ((rc == LDAP_NAMING_VIOLATION) ||
3297 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3298 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3299 const char *attrs[] = { "sambaGroupType", "description",
3300 "displayName", "sambaSIDList",
3301 "gidNumber", NULL };
3303 /* Third try. This is a post-3.0.21 alias (containing only
3304 * sambaSidEntry and sambaGroupMapping classes), we also have
3305 * to delete the gidNumber attribute, only the sambaSidEntry
3306 * remains */
3308 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3309 LDAP_OBJ_GROUPMAP, attrs);
3312 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3314 done:
3315 TALLOC_FREE(mem_ctx);
3316 return result;
3319 /**********************************************************************
3320 *********************************************************************/
3322 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3323 bool update)
3325 struct ldapsam_privates *ldap_state =
3326 (struct ldapsam_privates *)my_methods->private_data;
3327 char *filter = NULL;
3328 int rc;
3329 const char **attr_list;
3331 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3332 if (!filter) {
3333 return NT_STATUS_NO_MEMORY;
3335 attr_list = get_attr_list( NULL, groupmap_attr_list );
3336 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3337 LDAP_SCOPE_SUBTREE, filter,
3338 attr_list, 0, &ldap_state->result);
3339 TALLOC_FREE(attr_list);
3341 if (rc != LDAP_SUCCESS) {
3342 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3343 ldap_err2string(rc)));
3344 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3345 lp_ldap_suffix(talloc_tos()), filter));
3346 ldap_msgfree(ldap_state->result);
3347 ldap_state->result = NULL;
3348 TALLOC_FREE(filter);
3349 return NT_STATUS_UNSUCCESSFUL;
3352 TALLOC_FREE(filter);
3354 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3355 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3356 ldap_state->result)));
3358 ldap_state->entry =
3359 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3360 ldap_state->result);
3361 ldap_state->index = 0;
3363 return NT_STATUS_OK;
3366 /**********************************************************************
3367 *********************************************************************/
3369 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3371 ldapsam_endsampwent(my_methods);
3374 /**********************************************************************
3375 *********************************************************************/
3377 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3378 GROUP_MAP *map)
3380 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3381 struct ldapsam_privates *ldap_state =
3382 (struct ldapsam_privates *)my_methods->private_data;
3383 bool bret = False;
3385 while (!bret) {
3386 if (!ldap_state->entry)
3387 return ret;
3389 ldap_state->index++;
3390 bret = init_group_from_ldap(ldap_state, map,
3391 ldap_state->entry);
3393 ldap_state->entry =
3394 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3395 ldap_state->entry);
3398 return NT_STATUS_OK;
3401 /**********************************************************************
3402 *********************************************************************/
3404 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3405 const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3406 GROUP_MAP ***pp_rmap,
3407 size_t *p_num_entries,
3408 bool unix_only)
3410 GROUP_MAP *map = NULL;
3411 size_t entries = 0;
3413 *p_num_entries = 0;
3414 *pp_rmap = NULL;
3416 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3417 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3418 "passdb\n"));
3419 return NT_STATUS_ACCESS_DENIED;
3422 while (true) {
3424 map = talloc_zero(NULL, GROUP_MAP);
3425 if (!map) {
3426 return NT_STATUS_NO_MEMORY;
3429 if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
3430 TALLOC_FREE(map);
3431 break;
3434 if (sid_name_use != SID_NAME_UNKNOWN &&
3435 sid_name_use != map->sid_name_use) {
3436 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3437 "not of the requested type\n",
3438 map->nt_name));
3439 continue;
3441 if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
3442 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3443 "non mapped\n", map->nt_name));
3444 continue;
3447 *pp_rmap = talloc_realloc(NULL, *pp_rmap,
3448 GROUP_MAP *, entries + 1);
3449 if (!(*pp_rmap)) {
3450 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3451 "enlarge group map!\n"));
3452 return NT_STATUS_UNSUCCESSFUL;
3455 (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
3457 entries += 1;
3460 ldapsam_endsamgrent(methods);
3462 *p_num_entries = entries;
3464 return NT_STATUS_OK;
3467 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3468 const struct dom_sid *alias,
3469 const struct dom_sid *member,
3470 int modop)
3472 struct ldapsam_privates *ldap_state =
3473 (struct ldapsam_privates *)methods->private_data;
3474 char *dn = NULL;
3475 LDAPMessage *result = NULL;
3476 LDAPMessage *entry = NULL;
3477 int count;
3478 LDAPMod **mods = NULL;
3479 int rc;
3480 enum lsa_SidType type = SID_NAME_USE_NONE;
3481 fstring tmp;
3483 char *filter = NULL;
3485 if (sid_check_is_in_builtin(alias)) {
3486 type = SID_NAME_ALIAS;
3489 if (sid_check_is_in_our_sam(alias)) {
3490 type = SID_NAME_ALIAS;
3493 if (type == SID_NAME_USE_NONE) {
3494 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3495 sid_string_dbg(alias)));
3496 return NT_STATUS_NO_SUCH_ALIAS;
3499 if (asprintf(&filter,
3500 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3501 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3502 type) < 0) {
3503 return NT_STATUS_NO_MEMORY;
3506 if (ldapsam_search_one_group(ldap_state, filter,
3507 &result) != LDAP_SUCCESS) {
3508 SAFE_FREE(filter);
3509 return NT_STATUS_NO_SUCH_ALIAS;
3512 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3513 result);
3515 if (count < 1) {
3516 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3517 ldap_msgfree(result);
3518 SAFE_FREE(filter);
3519 return NT_STATUS_NO_SUCH_ALIAS;
3522 if (count > 1) {
3523 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3524 "filter %s: count=%d\n", filter, count));
3525 ldap_msgfree(result);
3526 SAFE_FREE(filter);
3527 return NT_STATUS_NO_SUCH_ALIAS;
3530 SAFE_FREE(filter);
3532 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3533 result);
3535 if (!entry) {
3536 ldap_msgfree(result);
3537 return NT_STATUS_UNSUCCESSFUL;
3540 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3541 if (!dn) {
3542 ldap_msgfree(result);
3543 return NT_STATUS_UNSUCCESSFUL;
3546 smbldap_set_mod(&mods, modop,
3547 get_attr_key2string(groupmap_attr_list,
3548 LDAP_ATTR_SID_LIST),
3549 sid_to_fstring(tmp, member));
3551 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3553 ldap_mods_free(mods, True);
3554 ldap_msgfree(result);
3555 TALLOC_FREE(dn);
3557 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3558 return NT_STATUS_MEMBER_IN_ALIAS;
3561 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3562 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3565 if (rc != LDAP_SUCCESS) {
3566 return NT_STATUS_UNSUCCESSFUL;
3569 return NT_STATUS_OK;
3572 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3573 const struct dom_sid *alias,
3574 const struct dom_sid *member)
3576 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3579 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3580 const struct dom_sid *alias,
3581 const struct dom_sid *member)
3583 return ldapsam_modify_aliasmem(methods, alias, member,
3584 LDAP_MOD_DELETE);
3587 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3588 const struct dom_sid *alias,
3589 TALLOC_CTX *mem_ctx,
3590 struct dom_sid **pp_members,
3591 size_t *p_num_members)
3593 struct ldapsam_privates *ldap_state =
3594 (struct ldapsam_privates *)methods->private_data;
3595 LDAPMessage *result = NULL;
3596 LDAPMessage *entry = NULL;
3597 int count;
3598 char **values = NULL;
3599 int i;
3600 char *filter = NULL;
3601 uint32_t num_members = 0;
3602 enum lsa_SidType type = SID_NAME_USE_NONE;
3603 fstring tmp;
3605 *pp_members = NULL;
3606 *p_num_members = 0;
3608 if (sid_check_is_in_builtin(alias)) {
3609 type = SID_NAME_ALIAS;
3612 if (sid_check_is_in_our_sam(alias)) {
3613 type = SID_NAME_ALIAS;
3616 if (type == SID_NAME_USE_NONE) {
3617 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3618 sid_string_dbg(alias)));
3619 return NT_STATUS_NO_SUCH_ALIAS;
3622 if (asprintf(&filter,
3623 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3624 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3625 type) < 0) {
3626 return NT_STATUS_NO_MEMORY;
3629 if (ldapsam_search_one_group(ldap_state, filter,
3630 &result) != LDAP_SUCCESS) {
3631 SAFE_FREE(filter);
3632 return NT_STATUS_NO_SUCH_ALIAS;
3635 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3636 result);
3638 if (count < 1) {
3639 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3640 ldap_msgfree(result);
3641 SAFE_FREE(filter);
3642 return NT_STATUS_NO_SUCH_ALIAS;
3645 if (count > 1) {
3646 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3647 "filter %s: count=%d\n", filter, count));
3648 ldap_msgfree(result);
3649 SAFE_FREE(filter);
3650 return NT_STATUS_NO_SUCH_ALIAS;
3653 SAFE_FREE(filter);
3655 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3656 result);
3658 if (!entry) {
3659 ldap_msgfree(result);
3660 return NT_STATUS_UNSUCCESSFUL;
3663 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3664 entry,
3665 get_attr_key2string(groupmap_attr_list,
3666 LDAP_ATTR_SID_LIST));
3668 if (values == NULL) {
3669 ldap_msgfree(result);
3670 return NT_STATUS_OK;
3673 count = ldap_count_values(values);
3675 for (i=0; i<count; i++) {
3676 struct dom_sid member;
3677 NTSTATUS status;
3679 if (!string_to_sid(&member, values[i]))
3680 continue;
3682 status = add_sid_to_array(mem_ctx, &member, pp_members,
3683 &num_members);
3684 if (!NT_STATUS_IS_OK(status)) {
3685 ldap_value_free(values);
3686 ldap_msgfree(result);
3687 return status;
3691 *p_num_members = num_members;
3692 ldap_value_free(values);
3693 ldap_msgfree(result);
3695 return NT_STATUS_OK;
3698 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3699 TALLOC_CTX *mem_ctx,
3700 const struct dom_sid *domain_sid,
3701 const struct dom_sid *members,
3702 size_t num_members,
3703 uint32_t **pp_alias_rids,
3704 size_t *p_num_alias_rids)
3706 struct ldapsam_privates *ldap_state =
3707 (struct ldapsam_privates *)methods->private_data;
3708 LDAP *ldap_struct;
3710 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3712 LDAPMessage *result = NULL;
3713 LDAPMessage *entry = NULL;
3714 int i;
3715 int rc;
3716 char *filter;
3717 enum lsa_SidType type = SID_NAME_USE_NONE;
3718 bool is_builtin = false;
3719 bool sid_added = false;
3721 *pp_alias_rids = NULL;
3722 *p_num_alias_rids = 0;
3724 if (sid_check_is_builtin(domain_sid)) {
3725 is_builtin = true;
3726 type = SID_NAME_ALIAS;
3729 if (sid_check_is_our_sam(domain_sid)) {
3730 type = SID_NAME_ALIAS;
3733 if (type == SID_NAME_USE_NONE) {
3734 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3735 sid_string_dbg(domain_sid)));
3736 return NT_STATUS_UNSUCCESSFUL;
3739 if (num_members == 0) {
3740 return NT_STATUS_OK;
3743 filter = talloc_asprintf(mem_ctx,
3744 "(&(objectclass=%s)(sambaGroupType=%d)(|",
3745 LDAP_OBJ_GROUPMAP, type);
3747 for (i=0; i<num_members; i++)
3748 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3749 filter,
3750 sid_string_talloc(mem_ctx,
3751 &members[i]));
3753 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3755 if (filter == NULL) {
3756 return NT_STATUS_NO_MEMORY;
3759 if (is_builtin &&
3760 ldap_state->search_cache.filter &&
3761 strcmp(ldap_state->search_cache.filter, filter) == 0) {
3762 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3763 result = ldap_state->search_cache.result;
3764 ldap_state->search_cache.result = NULL;
3765 } else {
3766 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3767 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3768 if (rc != LDAP_SUCCESS) {
3769 return NT_STATUS_UNSUCCESSFUL;
3771 talloc_autofree_ldapmsg(filter, result);
3774 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3776 for (entry = ldap_first_entry(ldap_struct, result);
3777 entry != NULL;
3778 entry = ldap_next_entry(ldap_struct, entry))
3780 fstring sid_str;
3781 struct dom_sid sid;
3782 uint32_t rid;
3784 if (!smbldap_get_single_attribute(ldap_struct, entry,
3785 LDAP_ATTRIBUTE_SID,
3786 sid_str,
3787 sizeof(sid_str)-1))
3788 continue;
3790 if (!string_to_sid(&sid, sid_str))
3791 continue;
3793 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3794 continue;
3796 sid_added = true;
3798 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3799 p_num_alias_rids)) {
3800 return NT_STATUS_NO_MEMORY;
3804 if (!is_builtin && !sid_added) {
3805 TALLOC_FREE(ldap_state->search_cache.filter);
3807 * Note: result is a talloc child of filter because of the
3808 * talloc_autofree_ldapmsg() usage
3810 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3811 ldap_state->search_cache.result = result;
3814 return NT_STATUS_OK;
3817 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3818 enum pdb_policy_type type,
3819 uint32_t value)
3821 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3822 int rc;
3823 LDAPMod **mods = NULL;
3824 fstring value_string;
3825 const char *policy_attr = NULL;
3827 struct ldapsam_privates *ldap_state =
3828 (struct ldapsam_privates *)methods->private_data;
3830 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3832 if (!ldap_state->domain_dn) {
3833 return NT_STATUS_INVALID_PARAMETER;
3836 policy_attr = get_account_policy_attr(type);
3837 if (policy_attr == NULL) {
3838 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3839 "policy\n"));
3840 return ntstatus;
3843 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3845 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3847 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3848 mods);
3850 ldap_mods_free(mods, True);
3852 if (rc != LDAP_SUCCESS) {
3853 return ntstatus;
3856 if (!cache_account_policy_set(type, value)) {
3857 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3858 "update local tdb cache\n"));
3859 return ntstatus;
3862 return NT_STATUS_OK;
3865 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3866 enum pdb_policy_type type,
3867 uint32_t value)
3869 return ldapsam_set_account_policy_in_ldap(methods, type,
3870 value);
3873 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3874 enum pdb_policy_type type,
3875 uint32_t *value)
3877 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3878 LDAPMessage *result = NULL;
3879 LDAPMessage *entry = NULL;
3880 int count;
3881 int rc;
3882 char **vals = NULL;
3883 char *filter;
3884 const char *policy_attr = NULL;
3886 struct ldapsam_privates *ldap_state =
3887 (struct ldapsam_privates *)methods->private_data;
3889 const char *attrs[2];
3891 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3893 if (!ldap_state->domain_dn) {
3894 return NT_STATUS_INVALID_PARAMETER;
3897 policy_attr = get_account_policy_attr(type);
3898 if (!policy_attr) {
3899 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3900 "policy index: %d\n", type));
3901 return ntstatus;
3904 attrs[0] = policy_attr;
3905 attrs[1] = NULL;
3907 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3908 if (filter == NULL) {
3909 return NT_STATUS_NO_MEMORY;
3911 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3912 LDAP_SCOPE_BASE, filter, attrs, 0,
3913 &result);
3914 TALLOC_FREE(filter);
3915 if (rc != LDAP_SUCCESS) {
3916 return ntstatus;
3919 count = ldap_count_entries(priv2ld(ldap_state), result);
3920 if (count < 1) {
3921 goto out;
3924 entry = ldap_first_entry(priv2ld(ldap_state), result);
3925 if (entry == NULL) {
3926 goto out;
3929 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3930 if (vals == NULL) {
3931 goto out;
3934 *value = (uint32_t)atol(vals[0]);
3936 ntstatus = NT_STATUS_OK;
3938 out:
3939 if (vals)
3940 ldap_value_free(vals);
3941 ldap_msgfree(result);
3943 return ntstatus;
3946 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3948 - if user hasn't decided to use account policies inside LDAP just reuse the
3949 old tdb values
3951 - if there is a valid cache entry, return that
3952 - if there is an LDAP entry, update cache and return
3953 - otherwise set to default, update cache and return
3955 Guenther
3957 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3958 enum pdb_policy_type type,
3959 uint32_t *value)
3961 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3963 if (cache_account_policy_get(type, value)) {
3964 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3965 "cache\n"));
3966 return NT_STATUS_OK;
3969 ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3970 value);
3971 if (NT_STATUS_IS_OK(ntstatus)) {
3972 goto update_cache;
3975 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3976 "ldap\n"));
3978 #if 0
3979 /* should we automagically migrate old tdb value here ? */
3980 if (account_policy_get(type, value))
3981 goto update_ldap;
3983 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3984 "default\n", type));
3985 #endif
3987 if (!account_policy_get_default(type, value)) {
3988 return ntstatus;
3991 /* update_ldap: */
3993 ntstatus = ldapsam_set_account_policy(methods, type, *value);
3994 if (!NT_STATUS_IS_OK(ntstatus)) {
3995 return ntstatus;
3998 update_cache:
4000 if (!cache_account_policy_set(type, *value)) {
4001 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
4002 "tdb as a cache\n"));
4003 return NT_STATUS_UNSUCCESSFUL;
4006 return NT_STATUS_OK;
4009 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
4010 const struct dom_sid *domain_sid,
4011 int num_rids,
4012 uint32_t *rids,
4013 const char **names,
4014 enum lsa_SidType *attrs)
4016 struct ldapsam_privates *ldap_state =
4017 (struct ldapsam_privates *)methods->private_data;
4018 LDAPMessage *msg = NULL;
4019 LDAPMessage *entry;
4020 char *allsids = NULL;
4021 int i, rc, num_mapped;
4022 NTSTATUS result = NT_STATUS_NO_MEMORY;
4023 TALLOC_CTX *mem_ctx;
4024 LDAP *ld;
4025 bool is_builtin;
4027 mem_ctx = talloc_new(NULL);
4028 if (mem_ctx == NULL) {
4029 DEBUG(0, ("talloc_new failed\n"));
4030 goto done;
4033 if (!sid_check_is_builtin(domain_sid) &&
4034 !sid_check_is_our_sam(domain_sid)) {
4035 result = NT_STATUS_INVALID_PARAMETER;
4036 goto done;
4039 if (num_rids == 0) {
4040 result = NT_STATUS_NONE_MAPPED;
4041 goto done;
4044 for (i=0; i<num_rids; i++)
4045 attrs[i] = SID_NAME_UNKNOWN;
4047 allsids = talloc_strdup(mem_ctx, "");
4048 if (allsids == NULL) {
4049 goto done;
4052 for (i=0; i<num_rids; i++) {
4053 struct dom_sid sid;
4054 sid_compose(&sid, domain_sid, rids[i]);
4055 allsids = talloc_asprintf_append_buffer(
4056 allsids, "(sambaSid=%s)",
4057 sid_string_talloc(mem_ctx, &sid));
4058 if (allsids == NULL) {
4059 goto done;
4063 /* First look for users */
4066 char *filter;
4067 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4069 filter = talloc_asprintf(
4070 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4071 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4073 if (filter == NULL) {
4074 goto done;
4077 rc = smbldap_search(ldap_state->smbldap_state,
4078 lp_ldap_user_suffix(talloc_tos()),
4079 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4080 &msg);
4081 talloc_autofree_ldapmsg(mem_ctx, msg);
4084 if (rc != LDAP_SUCCESS)
4085 goto done;
4087 ld = ldap_state->smbldap_state->ldap_struct;
4088 num_mapped = 0;
4090 for (entry = ldap_first_entry(ld, msg);
4091 entry != NULL;
4092 entry = ldap_next_entry(ld, entry)) {
4093 uint32_t rid;
4094 int rid_index;
4095 const char *name;
4097 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4098 &rid)) {
4099 DEBUG(2, ("Could not find sid from ldap entry\n"));
4100 continue;
4103 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4104 names);
4105 if (name == NULL) {
4106 DEBUG(2, ("Could not retrieve uid attribute\n"));
4107 continue;
4110 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4111 if (rid == rids[rid_index])
4112 break;
4115 if (rid_index == num_rids) {
4116 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4117 continue;
4120 attrs[rid_index] = SID_NAME_USER;
4121 names[rid_index] = name;
4122 num_mapped += 1;
4125 if (num_mapped == num_rids) {
4126 /* No need to look for groups anymore -- we're done */
4127 result = NT_STATUS_OK;
4128 goto done;
4131 /* Same game for groups */
4134 char *filter;
4135 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4136 "sambaGroupType", NULL };
4138 filter = talloc_asprintf(
4139 mem_ctx, "(&(objectClass=%s)(|%s))",
4140 LDAP_OBJ_GROUPMAP, allsids);
4141 if (filter == NULL) {
4142 goto done;
4145 rc = smbldap_search(ldap_state->smbldap_state,
4146 lp_ldap_suffix(talloc_tos()),
4147 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4148 &msg);
4149 talloc_autofree_ldapmsg(mem_ctx, msg);
4152 if (rc != LDAP_SUCCESS)
4153 goto done;
4155 /* ldap_struct might have changed due to a reconnect */
4157 ld = ldap_state->smbldap_state->ldap_struct;
4159 /* For consistency checks, we already checked we're only domain or builtin */
4161 is_builtin = sid_check_is_builtin(domain_sid);
4163 for (entry = ldap_first_entry(ld, msg);
4164 entry != NULL;
4165 entry = ldap_next_entry(ld, entry))
4167 uint32_t rid;
4168 int rid_index;
4169 const char *attr;
4170 enum lsa_SidType type;
4171 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4173 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4174 mem_ctx);
4175 if (attr == NULL) {
4176 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4177 dn));
4178 continue;
4181 type = (enum lsa_SidType)atol(attr);
4183 /* Consistency checks */
4184 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4185 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4186 (type != SID_NAME_DOM_GRP)))) {
4187 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4190 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4191 &rid)) {
4192 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4193 continue;
4196 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4198 if (attr == NULL) {
4199 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4200 dn));
4201 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4204 if (attr == NULL) {
4205 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4206 dn));
4207 continue;
4210 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4211 if (rid == rids[rid_index])
4212 break;
4215 if (rid_index == num_rids) {
4216 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4217 continue;
4220 attrs[rid_index] = type;
4221 names[rid_index] = attr;
4222 num_mapped += 1;
4225 result = NT_STATUS_NONE_MAPPED;
4227 if (num_mapped > 0)
4228 result = (num_mapped == num_rids) ?
4229 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4230 done:
4231 TALLOC_FREE(mem_ctx);
4232 return result;
4235 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4237 char *filter = NULL;
4238 char *escaped = NULL;
4239 char *result = NULL;
4241 if (asprintf(&filter, "(&%s(objectclass=%s))",
4242 "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4243 goto done;
4246 escaped = escape_ldap_string(talloc_tos(), username);
4247 if (escaped == NULL) goto done;
4249 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4251 done:
4252 SAFE_FREE(filter);
4253 TALLOC_FREE(escaped);
4255 return result;
4258 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4260 int i, num = 0;
4261 va_list ap;
4262 const char **result;
4264 va_start(ap, mem_ctx);
4265 while (va_arg(ap, const char *) != NULL)
4266 num += 1;
4267 va_end(ap);
4269 if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4270 return NULL;
4273 va_start(ap, mem_ctx);
4274 for (i=0; i<num; i++) {
4275 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4276 if (result[i] == NULL) {
4277 talloc_free(result);
4278 va_end(ap);
4279 return NULL;
4282 va_end(ap);
4284 result[num] = NULL;
4285 return result;
4288 struct ldap_search_state {
4289 struct smbldap_state *connection;
4291 uint32_t acct_flags;
4292 uint16_t group_type;
4294 const char *base;
4295 int scope;
4296 const char *filter;
4297 const char **attrs;
4298 int attrsonly;
4299 void *pagedresults_cookie;
4301 LDAPMessage *entries, *current_entry;
4302 bool (*ldap2displayentry)(struct ldap_search_state *state,
4303 TALLOC_CTX *mem_ctx,
4304 LDAP *ld, LDAPMessage *entry,
4305 struct samr_displayentry *result);
4308 static bool ldapsam_search_firstpage(struct pdb_search *search)
4310 struct ldap_search_state *state =
4311 (struct ldap_search_state *)search->private_data;
4312 LDAP *ld;
4313 int rc = LDAP_OPERATIONS_ERROR;
4315 state->entries = NULL;
4317 if (state->connection->paged_results) {
4318 rc = smbldap_search_paged(state->connection, state->base,
4319 state->scope, state->filter,
4320 state->attrs, state->attrsonly,
4321 lp_ldap_page_size(), &state->entries,
4322 &state->pagedresults_cookie);
4325 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4327 if (state->entries != NULL) {
4328 /* Left over from unsuccessful paged attempt */
4329 ldap_msgfree(state->entries);
4330 state->entries = NULL;
4333 rc = smbldap_search(state->connection, state->base,
4334 state->scope, state->filter, state->attrs,
4335 state->attrsonly, &state->entries);
4337 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4338 return False;
4340 /* Ok, the server was lying. It told us it could do paged
4341 * searches when it could not. */
4342 state->connection->paged_results = False;
4345 ld = state->connection->ldap_struct;
4346 if ( ld == NULL) {
4347 DEBUG(5, ("Don't have an LDAP connection right after a "
4348 "search\n"));
4349 return False;
4351 state->current_entry = ldap_first_entry(ld, state->entries);
4353 return True;
4356 static bool ldapsam_search_nextpage(struct pdb_search *search)
4358 struct ldap_search_state *state =
4359 (struct ldap_search_state *)search->private_data;
4360 int rc;
4362 if (!state->connection->paged_results) {
4363 /* There is no next page when there are no paged results */
4364 return False;
4367 rc = smbldap_search_paged(state->connection, state->base,
4368 state->scope, state->filter, state->attrs,
4369 state->attrsonly, lp_ldap_page_size(),
4370 &state->entries,
4371 &state->pagedresults_cookie);
4373 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4374 return False;
4376 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4378 if (state->current_entry == NULL) {
4379 ldap_msgfree(state->entries);
4380 state->entries = NULL;
4381 return false;
4384 return True;
4387 static bool ldapsam_search_next_entry(struct pdb_search *search,
4388 struct samr_displayentry *entry)
4390 struct ldap_search_state *state =
4391 (struct ldap_search_state *)search->private_data;
4392 bool result;
4394 retry:
4395 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4396 return False;
4398 if ((state->entries == NULL) &&
4399 !ldapsam_search_nextpage(search))
4400 return False;
4402 if (state->current_entry == NULL) {
4403 return false;
4406 result = state->ldap2displayentry(state, search,
4407 state->connection->ldap_struct,
4408 state->current_entry, entry);
4410 if (!result) {
4411 char *dn;
4412 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4413 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4414 if (dn != NULL) ldap_memfree(dn);
4417 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4419 if (state->current_entry == NULL) {
4420 ldap_msgfree(state->entries);
4421 state->entries = NULL;
4424 if (!result) goto retry;
4426 return True;
4429 static void ldapsam_search_end(struct pdb_search *search)
4431 struct ldap_search_state *state =
4432 (struct ldap_search_state *)search->private_data;
4433 int rc;
4435 if (state->pagedresults_cookie == NULL)
4436 return;
4438 if (state->entries != NULL)
4439 ldap_msgfree(state->entries);
4441 state->entries = NULL;
4442 state->current_entry = NULL;
4444 if (!state->connection->paged_results)
4445 return;
4447 /* Tell the LDAP server we're not interested in the rest anymore. */
4449 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4450 state->filter, state->attrs,
4451 state->attrsonly, 0, &state->entries,
4452 &state->pagedresults_cookie);
4454 if (rc != LDAP_SUCCESS)
4455 DEBUG(5, ("Could not end search properly\n"));
4457 return;
4460 static bool ldapuser2displayentry(struct ldap_search_state *state,
4461 TALLOC_CTX *mem_ctx,
4462 LDAP *ld, LDAPMessage *entry,
4463 struct samr_displayentry *result)
4465 char **vals;
4466 size_t converted_size;
4467 struct dom_sid sid;
4468 uint32_t acct_flags;
4470 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4471 if ((vals == NULL) || (vals[0] == NULL)) {
4472 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4473 return False;
4475 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4476 ldap_value_free(vals);
4478 if ((state->acct_flags != 0) &&
4479 ((state->acct_flags & acct_flags) == 0))
4480 return False;
4482 result->acct_flags = acct_flags;
4483 result->account_name = "";
4484 result->fullname = "";
4485 result->description = "";
4487 vals = ldap_get_values(ld, entry, "uid");
4488 if ((vals == NULL) || (vals[0] == NULL)) {
4489 DEBUG(5, ("\"uid\" not found\n"));
4490 return False;
4492 if (!pull_utf8_talloc(mem_ctx,
4493 discard_const_p(char *, &result->account_name),
4494 vals[0], &converted_size))
4496 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4497 strerror(errno)));
4500 ldap_value_free(vals);
4502 vals = ldap_get_values(ld, entry, "displayName");
4503 if ((vals == NULL) || (vals[0] == NULL))
4504 DEBUG(8, ("\"displayName\" not found\n"));
4505 else if (!pull_utf8_talloc(mem_ctx,
4506 discard_const_p(char *, &result->fullname),
4507 vals[0], &converted_size))
4509 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4510 strerror(errno)));
4513 ldap_value_free(vals);
4515 vals = ldap_get_values(ld, entry, "description");
4516 if ((vals == NULL) || (vals[0] == NULL))
4517 DEBUG(8, ("\"description\" not found\n"));
4518 else if (!pull_utf8_talloc(mem_ctx,
4519 discard_const_p(char *, &result->description),
4520 vals[0], &converted_size))
4522 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4523 strerror(errno)));
4526 ldap_value_free(vals);
4528 if ((result->account_name == NULL) ||
4529 (result->fullname == NULL) ||
4530 (result->description == NULL)) {
4531 DEBUG(0, ("talloc failed\n"));
4532 return False;
4535 vals = ldap_get_values(ld, entry, "sambaSid");
4536 if ((vals == NULL) || (vals[0] == NULL)) {
4537 DEBUG(0, ("\"objectSid\" not found\n"));
4538 return False;
4541 if (!string_to_sid(&sid, vals[0])) {
4542 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4543 ldap_value_free(vals);
4544 return False;
4546 ldap_value_free(vals);
4548 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4549 DEBUG(0, ("sid %s does not belong to our domain\n",
4550 sid_string_dbg(&sid)));
4551 return False;
4554 return True;
4558 static bool ldapsam_search_users(struct pdb_methods *methods,
4559 struct pdb_search *search,
4560 uint32_t acct_flags)
4562 struct ldapsam_privates *ldap_state =
4563 (struct ldapsam_privates *)methods->private_data;
4564 struct ldap_search_state *state;
4566 state = talloc(search, struct ldap_search_state);
4567 if (state == NULL) {
4568 DEBUG(0, ("talloc failed\n"));
4569 return False;
4572 state->connection = ldap_state->smbldap_state;
4574 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4575 state->base = lp_ldap_user_suffix(talloc_tos());
4576 else if ((acct_flags != 0) &&
4577 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4578 state->base = lp_ldap_machine_suffix(talloc_tos());
4579 else
4580 state->base = lp_ldap_suffix(talloc_tos());
4582 state->acct_flags = acct_flags;
4583 state->base = talloc_strdup(search, state->base);
4584 state->scope = LDAP_SCOPE_SUBTREE;
4585 state->filter = get_ldap_filter(search, "*");
4586 state->attrs = talloc_attrs(search, "uid", "sambaSid",
4587 "displayName", "description",
4588 "sambaAcctFlags", NULL);
4589 state->attrsonly = 0;
4590 state->pagedresults_cookie = NULL;
4591 state->entries = NULL;
4592 state->ldap2displayentry = ldapuser2displayentry;
4594 if ((state->filter == NULL) || (state->attrs == NULL)) {
4595 DEBUG(0, ("talloc failed\n"));
4596 return False;
4599 search->private_data = state;
4600 search->next_entry = ldapsam_search_next_entry;
4601 search->search_end = ldapsam_search_end;
4603 return ldapsam_search_firstpage(search);
4606 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4607 TALLOC_CTX *mem_ctx,
4608 LDAP *ld, LDAPMessage *entry,
4609 struct samr_displayentry *result)
4611 char **vals;
4612 size_t converted_size;
4613 struct dom_sid sid;
4614 uint16_t group_type;
4616 result->account_name = "";
4617 result->fullname = "";
4618 result->description = "";
4621 vals = ldap_get_values(ld, entry, "sambaGroupType");
4622 if ((vals == NULL) || (vals[0] == NULL)) {
4623 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4624 if (vals != NULL) {
4625 ldap_value_free(vals);
4627 return False;
4630 group_type = atoi(vals[0]);
4632 if ((state->group_type != 0) &&
4633 ((state->group_type != group_type))) {
4634 ldap_value_free(vals);
4635 return False;
4638 ldap_value_free(vals);
4640 /* display name is the NT group name */
4642 vals = ldap_get_values(ld, entry, "displayName");
4643 if ((vals == NULL) || (vals[0] == NULL)) {
4644 DEBUG(8, ("\"displayName\" not found\n"));
4646 /* fallback to the 'cn' attribute */
4647 vals = ldap_get_values(ld, entry, "cn");
4648 if ((vals == NULL) || (vals[0] == NULL)) {
4649 DEBUG(5, ("\"cn\" not found\n"));
4650 return False;
4652 if (!pull_utf8_talloc(mem_ctx,
4653 discard_const_p(char *,
4654 &result->account_name),
4655 vals[0], &converted_size))
4657 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4658 "failed: %s", strerror(errno)));
4661 else if (!pull_utf8_talloc(mem_ctx,
4662 discard_const_p(char *,
4663 &result->account_name),
4664 vals[0], &converted_size))
4666 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4667 strerror(errno)));
4670 ldap_value_free(vals);
4672 vals = ldap_get_values(ld, entry, "description");
4673 if ((vals == NULL) || (vals[0] == NULL))
4674 DEBUG(8, ("\"description\" not found\n"));
4675 else if (!pull_utf8_talloc(mem_ctx,
4676 discard_const_p(char *, &result->description),
4677 vals[0], &converted_size))
4679 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4680 strerror(errno)));
4682 ldap_value_free(vals);
4684 if ((result->account_name == NULL) ||
4685 (result->fullname == NULL) ||
4686 (result->description == NULL)) {
4687 DEBUG(0, ("talloc failed\n"));
4688 return False;
4691 vals = ldap_get_values(ld, entry, "sambaSid");
4692 if ((vals == NULL) || (vals[0] == NULL)) {
4693 DEBUG(0, ("\"objectSid\" not found\n"));
4694 if (vals != NULL) {
4695 ldap_value_free(vals);
4697 return False;
4700 if (!string_to_sid(&sid, vals[0])) {
4701 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4702 return False;
4705 ldap_value_free(vals);
4707 switch (group_type) {
4708 case SID_NAME_DOM_GRP:
4709 case SID_NAME_ALIAS:
4711 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4712 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4714 DEBUG(0, ("%s is not in our domain\n",
4715 sid_string_dbg(&sid)));
4716 return False;
4718 break;
4720 default:
4721 DEBUG(0,("unknown group type: %d\n", group_type));
4722 return False;
4725 result->acct_flags = 0;
4727 return True;
4730 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4731 struct pdb_search *search,
4732 const struct dom_sid *sid,
4733 enum lsa_SidType type)
4735 struct ldapsam_privates *ldap_state =
4736 (struct ldapsam_privates *)methods->private_data;
4737 struct ldap_search_state *state;
4738 fstring tmp;
4740 state = talloc(search, struct ldap_search_state);
4741 if (state == NULL) {
4742 DEBUG(0, ("talloc failed\n"));
4743 return False;
4746 state->connection = ldap_state->smbldap_state;
4748 state->base = lp_ldap_suffix(search);
4749 state->connection = ldap_state->smbldap_state;
4750 state->scope = LDAP_SCOPE_SUBTREE;
4751 state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4752 "(sambaGroupType=%d)(sambaSID=%s*))",
4753 LDAP_OBJ_GROUPMAP,
4754 type, sid_to_fstring(tmp, sid));
4755 state->attrs = talloc_attrs(search, "cn", "sambaSid",
4756 "displayName", "description",
4757 "sambaGroupType", NULL);
4758 state->attrsonly = 0;
4759 state->pagedresults_cookie = NULL;
4760 state->entries = NULL;
4761 state->group_type = type;
4762 state->ldap2displayentry = ldapgroup2displayentry;
4764 if ((state->filter == NULL) || (state->attrs == NULL)) {
4765 DEBUG(0, ("talloc failed\n"));
4766 return False;
4769 search->private_data = state;
4770 search->next_entry = ldapsam_search_next_entry;
4771 search->search_end = ldapsam_search_end;
4773 return ldapsam_search_firstpage(search);
4776 static bool ldapsam_search_groups(struct pdb_methods *methods,
4777 struct pdb_search *search)
4779 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4782 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4783 struct pdb_search *search,
4784 const struct dom_sid *sid)
4786 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4789 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4791 return PDB_CAP_STORE_RIDS;
4794 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4795 uint32_t *rid)
4797 struct smbldap_state *smbldap_state = priv->smbldap_state;
4799 LDAPMessage *result = NULL;
4800 LDAPMessage *entry = NULL;
4801 LDAPMod **mods = NULL;
4802 NTSTATUS status;
4803 char *value;
4804 int rc;
4805 uint32_t nextRid = 0;
4806 const char *dn;
4808 TALLOC_CTX *mem_ctx;
4810 mem_ctx = talloc_new(NULL);
4811 if (mem_ctx == NULL) {
4812 DEBUG(0, ("talloc_new failed\n"));
4813 return NT_STATUS_NO_MEMORY;
4816 status = smbldap_search_domain_info(smbldap_state, &result,
4817 get_global_sam_name(), False);
4818 if (!NT_STATUS_IS_OK(status)) {
4819 DEBUG(3, ("Could not get domain info: %s\n",
4820 nt_errstr(status)));
4821 goto done;
4824 talloc_autofree_ldapmsg(mem_ctx, result);
4826 entry = ldap_first_entry(priv2ld(priv), result);
4827 if (entry == NULL) {
4828 DEBUG(0, ("Could not get domain info entry\n"));
4829 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4830 goto done;
4833 /* Find the largest of the three attributes "sambaNextRid",
4834 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4835 concept of differentiating between user and group rids, and will
4836 use only "sambaNextRid" in the future. But for compatibility
4837 reasons I look if others have chosen different strategies -- VL */
4839 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4840 "sambaNextRid", mem_ctx);
4841 if (value != NULL) {
4842 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4843 nextRid = MAX(nextRid, tmp);
4846 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4847 "sambaNextUserRid", mem_ctx);
4848 if (value != NULL) {
4849 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4850 nextRid = MAX(nextRid, tmp);
4853 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4854 "sambaNextGroupRid", mem_ctx);
4855 if (value != NULL) {
4856 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4857 nextRid = MAX(nextRid, tmp);
4860 if (nextRid == 0) {
4861 nextRid = BASE_RID-1;
4864 nextRid += 1;
4866 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4867 talloc_asprintf(mem_ctx, "%d", nextRid));
4868 talloc_autofree_ldapmod(mem_ctx, mods);
4870 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4871 status = NT_STATUS_NO_MEMORY;
4872 goto done;
4875 rc = smbldap_modify(smbldap_state, dn, mods);
4877 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4878 * please retry" */
4880 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4882 done:
4883 if (NT_STATUS_IS_OK(status)) {
4884 *rid = nextRid;
4887 TALLOC_FREE(mem_ctx);
4888 return status;
4891 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4893 int i;
4895 for (i=0; i<10; i++) {
4896 NTSTATUS result = ldapsam_get_new_rid(
4897 (struct ldapsam_privates *)methods->private_data, rid);
4898 if (NT_STATUS_IS_OK(result)) {
4899 return result;
4902 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4903 return result;
4906 /* The ldap update failed (maybe a race condition), retry */
4909 /* Tried 10 times, fail. */
4910 return NT_STATUS_ACCESS_DENIED;
4913 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4915 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4916 return NT_STATUS_IS_OK(result) ? True : False;
4919 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4920 const struct dom_sid *sid,
4921 struct unixid *id)
4923 struct ldapsam_privates *priv =
4924 (struct ldapsam_privates *)methods->private_data;
4925 char *filter;
4926 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4927 NULL };
4928 LDAPMessage *result = NULL;
4929 LDAPMessage *entry = NULL;
4930 bool ret = False;
4931 char *value;
4932 int rc;
4934 TALLOC_CTX *mem_ctx;
4936 mem_ctx = talloc_new(NULL);
4937 if (mem_ctx == NULL) {
4938 DEBUG(0, ("talloc_new failed\n"));
4939 return False;
4942 filter = talloc_asprintf(mem_ctx,
4943 "(&(sambaSid=%s)"
4944 "(|(objectClass=%s)(objectClass=%s)))",
4945 sid_string_talloc(mem_ctx, sid),
4946 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4947 if (filter == NULL) {
4948 DEBUG(5, ("talloc_asprintf failed\n"));
4949 goto done;
4952 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4953 attrs, &result);
4954 if (rc != LDAP_SUCCESS) {
4955 goto done;
4957 talloc_autofree_ldapmsg(mem_ctx, result);
4959 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4960 DEBUG(10, ("Got %d entries, expected one\n",
4961 ldap_count_entries(priv2ld(priv), result)));
4962 goto done;
4965 entry = ldap_first_entry(priv2ld(priv), result);
4967 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4968 "sambaGroupType", mem_ctx);
4970 if (value != NULL) {
4971 const char *gid_str;
4972 /* It's a group */
4974 gid_str = smbldap_talloc_single_attribute(
4975 priv2ld(priv), entry, "gidNumber", mem_ctx);
4976 if (gid_str == NULL) {
4977 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4978 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4979 entry)));
4980 goto done;
4983 id->id = strtoul(gid_str, NULL, 10);
4984 id->type = ID_TYPE_GID;
4985 idmap_cache_set_sid2unixid(sid, id);
4986 ret = True;
4987 goto done;
4990 /* It must be a user */
4992 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4993 "uidNumber", mem_ctx);
4994 if (value == NULL) {
4995 DEBUG(1, ("Could not find uidNumber in %s\n",
4996 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4997 goto done;
5000 id->id = strtoul(value, NULL, 10);
5001 id->type = ID_TYPE_UID;
5002 idmap_cache_set_sid2unixid(sid, id);
5004 ret = True;
5005 done:
5006 TALLOC_FREE(mem_ctx);
5007 return ret;
5011 * Find the SID for a uid.
5012 * This is shortcut is only used if ldapsam:trusted is set to true.
5014 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5015 struct dom_sid *sid)
5017 struct ldapsam_privates *priv =
5018 (struct ldapsam_privates *)methods->private_data;
5019 char *filter;
5020 const char *attrs[] = { "sambaSID", NULL };
5021 LDAPMessage *result = NULL;
5022 LDAPMessage *entry = NULL;
5023 bool ret = false;
5024 char *user_sid_string;
5025 struct dom_sid user_sid;
5026 int rc;
5027 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5028 struct unixid id;
5030 filter = talloc_asprintf(tmp_ctx,
5031 "(&(uidNumber=%u)"
5032 "(objectClass=%s)"
5033 "(objectClass=%s))",
5034 (unsigned int)uid,
5035 LDAP_OBJ_POSIXACCOUNT,
5036 LDAP_OBJ_SAMBASAMACCOUNT);
5037 if (filter == NULL) {
5038 DEBUG(3, ("talloc_asprintf failed\n"));
5039 goto done;
5042 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5043 if (rc != LDAP_SUCCESS) {
5044 goto done;
5046 talloc_autofree_ldapmsg(tmp_ctx, result);
5048 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5049 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5050 ldap_count_entries(priv2ld(priv), result),
5051 (unsigned int)uid));
5052 goto done;
5055 entry = ldap_first_entry(priv2ld(priv), result);
5057 user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5058 "sambaSID", tmp_ctx);
5059 if (user_sid_string == NULL) {
5060 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5061 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5062 goto done;
5065 if (!string_to_sid(&user_sid, user_sid_string)) {
5066 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5067 user_sid_string));
5068 goto done;
5071 sid_copy(sid, &user_sid);
5073 id.id = uid;
5074 id.type = ID_TYPE_UID;
5076 idmap_cache_set_sid2unixid(sid, &id);
5078 ret = true;
5080 done:
5081 TALLOC_FREE(tmp_ctx);
5082 return ret;
5086 * Find the SID for a gid.
5087 * This is shortcut is only used if ldapsam:trusted is set to true.
5089 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5090 struct dom_sid *sid)
5092 struct ldapsam_privates *priv =
5093 (struct ldapsam_privates *)methods->private_data;
5094 char *filter;
5095 const char *attrs[] = { "sambaSID", NULL };
5096 LDAPMessage *result = NULL;
5097 LDAPMessage *entry = NULL;
5098 bool ret = false;
5099 char *group_sid_string;
5100 struct dom_sid group_sid;
5101 int rc;
5102 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5103 struct unixid id;
5105 filter = talloc_asprintf(tmp_ctx,
5106 "(&(gidNumber=%u)"
5107 "(objectClass=%s))",
5108 (unsigned int)gid,
5109 LDAP_OBJ_GROUPMAP);
5110 if (filter == NULL) {
5111 DEBUG(3, ("talloc_asprintf failed\n"));
5112 goto done;
5115 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5116 if (rc != LDAP_SUCCESS) {
5117 goto done;
5119 talloc_autofree_ldapmsg(tmp_ctx, result);
5121 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5122 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5123 ldap_count_entries(priv2ld(priv), result),
5124 (unsigned int)gid));
5125 goto done;
5128 entry = ldap_first_entry(priv2ld(priv), result);
5130 group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5131 "sambaSID", tmp_ctx);
5132 if (group_sid_string == NULL) {
5133 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5134 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5135 goto done;
5138 if (!string_to_sid(&group_sid, group_sid_string)) {
5139 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5140 group_sid_string));
5141 goto done;
5144 sid_copy(sid, &group_sid);
5146 id.id = gid;
5147 id.type = ID_TYPE_GID;
5149 idmap_cache_set_sid2unixid(sid, &id);
5151 ret = true;
5153 done:
5154 TALLOC_FREE(tmp_ctx);
5155 return ret;
5160 * The following functions are called only if
5161 * ldapsam:trusted and ldapsam:editposix are
5162 * set to true
5166 * ldapsam_create_user creates a new
5167 * posixAccount and sambaSamAccount object
5168 * in the ldap users subtree
5170 * The uid is allocated by winbindd.
5173 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5174 TALLOC_CTX *tmp_ctx, const char *name,
5175 uint32_t acb_info, uint32_t *rid)
5177 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5178 LDAPMessage *entry = NULL;
5179 LDAPMessage *result = NULL;
5180 uint32_t num_result;
5181 bool is_machine = False;
5182 bool add_posix = False;
5183 LDAPMod **mods = NULL;
5184 struct samu *user;
5185 char *filter;
5186 char *username;
5187 char *homedir;
5188 char *gidstr;
5189 char *uidstr;
5190 char *shell;
5191 const char *dn = NULL;
5192 struct dom_sid group_sid;
5193 struct dom_sid user_sid;
5194 gid_t gid = -1;
5195 uid_t uid = -1;
5196 NTSTATUS ret;
5197 int rc;
5199 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5200 acb_info & ACB_WSTRUST ||
5201 acb_info & ACB_SVRTRUST ||
5202 acb_info & ACB_DOMTRUST) {
5203 is_machine = True;
5206 username = escape_ldap_string(talloc_tos(), name);
5207 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5208 username, LDAP_OBJ_POSIXACCOUNT);
5209 TALLOC_FREE(username);
5211 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5212 if (rc != LDAP_SUCCESS) {
5213 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5214 return NT_STATUS_ACCESS_DENIED;
5216 talloc_autofree_ldapmsg(tmp_ctx, result);
5218 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5220 if (num_result > 1) {
5221 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5222 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5225 if (num_result == 1) {
5226 char *tmp;
5227 /* check if it is just a posix account.
5228 * or if there is a sid attached to this entry
5231 entry = ldap_first_entry(priv2ld(ldap_state), result);
5232 if (!entry) {
5233 return NT_STATUS_UNSUCCESSFUL;
5236 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5237 if (tmp) {
5238 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5239 return NT_STATUS_USER_EXISTS;
5242 /* it is just a posix account, retrieve the dn for later use */
5243 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5244 if (!dn) {
5245 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5246 return NT_STATUS_NO_MEMORY;
5250 if (num_result == 0) {
5251 add_posix = True;
5254 /* Create the basic samu structure and generate the mods for the ldap commit */
5255 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5256 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5257 return ret;
5260 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5262 user = samu_new(tmp_ctx);
5263 if (!user) {
5264 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5265 return NT_STATUS_NO_MEMORY;
5268 if (!pdb_set_username(user, name, PDB_SET)) {
5269 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5270 return NT_STATUS_UNSUCCESSFUL;
5272 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5273 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5274 return NT_STATUS_UNSUCCESSFUL;
5276 if (is_machine) {
5277 if (acb_info & ACB_NORMAL) {
5278 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5279 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5280 return NT_STATUS_UNSUCCESSFUL;
5282 } else {
5283 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5284 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5285 return NT_STATUS_UNSUCCESSFUL;
5288 } else {
5289 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5290 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5291 return NT_STATUS_UNSUCCESSFUL;
5295 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5296 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5297 return NT_STATUS_UNSUCCESSFUL;
5300 if (!init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed)) {
5301 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5302 return NT_STATUS_UNSUCCESSFUL;
5305 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5306 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5308 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5310 if (add_posix) {
5311 char *escape_name;
5313 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5315 /* retrieve the Domain Users group gid */
5316 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5317 !sid_to_gid(&group_sid, &gid)) {
5318 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5319 return NT_STATUS_INVALID_PRIMARY_GROUP;
5322 /* lets allocate a new userid for this user */
5323 if (!winbind_allocate_uid(&uid)) {
5324 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5325 return NT_STATUS_UNSUCCESSFUL;
5329 if (is_machine) {
5330 /* TODO: choose a more appropriate default for machines */
5331 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5332 shell = talloc_strdup(tmp_ctx, "/bin/false");
5333 } else {
5334 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5335 shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5337 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5338 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5340 escape_name = escape_rdn_val_string_alloc(name);
5341 if (!escape_name) {
5342 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5343 return NT_STATUS_NO_MEMORY;
5346 if (is_machine) {
5347 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
5348 } else {
5349 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
5352 SAFE_FREE(escape_name);
5354 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5355 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5356 return NT_STATUS_NO_MEMORY;
5359 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5360 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5361 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5362 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5363 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5364 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5365 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5368 talloc_autofree_ldapmod(tmp_ctx, mods);
5370 if (add_posix) {
5371 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5372 } else {
5373 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5376 if (rc != LDAP_SUCCESS) {
5377 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5378 return NT_STATUS_UNSUCCESSFUL;
5381 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5383 flush_pwnam_cache();
5385 return NT_STATUS_OK;
5388 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5390 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5391 LDAPMessage *result = NULL;
5392 LDAPMessage *entry = NULL;
5393 int num_result;
5394 const char *dn;
5395 char *filter;
5396 int rc;
5398 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5400 filter = talloc_asprintf(tmp_ctx,
5401 "(&(uid=%s)"
5402 "(objectClass=%s)"
5403 "(objectClass=%s))",
5404 pdb_get_username(sam_acct),
5405 LDAP_OBJ_POSIXACCOUNT,
5406 LDAP_OBJ_SAMBASAMACCOUNT);
5407 if (filter == NULL) {
5408 return NT_STATUS_NO_MEMORY;
5411 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5412 if (rc != LDAP_SUCCESS) {
5413 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5414 return NT_STATUS_UNSUCCESSFUL;
5416 talloc_autofree_ldapmsg(tmp_ctx, result);
5418 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5420 if (num_result == 0) {
5421 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5422 return NT_STATUS_NO_SUCH_USER;
5425 if (num_result > 1) {
5426 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5427 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5430 entry = ldap_first_entry(priv2ld(ldap_state), result);
5431 if (!entry) {
5432 return NT_STATUS_UNSUCCESSFUL;
5435 /* it is just a posix account, retrieve the dn for later use */
5436 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5437 if (!dn) {
5438 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5439 return NT_STATUS_NO_MEMORY;
5442 /* try to remove memberships first */
5444 NTSTATUS status;
5445 struct dom_sid *sids = NULL;
5446 gid_t *gids = NULL;
5447 uint32_t num_groups = 0;
5448 int i;
5449 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5451 status = ldapsam_enum_group_memberships(my_methods,
5452 tmp_ctx,
5453 sam_acct,
5454 &sids,
5455 &gids,
5456 &num_groups);
5457 if (!NT_STATUS_IS_OK(status)) {
5458 goto delete_dn;
5461 for (i=0; i < num_groups; i++) {
5463 uint32_t group_rid;
5465 sid_peek_rid(&sids[i], &group_rid);
5467 ldapsam_del_groupmem(my_methods,
5468 tmp_ctx,
5469 group_rid,
5470 user_rid);
5474 delete_dn:
5476 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5477 if (rc != LDAP_SUCCESS) {
5478 return NT_STATUS_UNSUCCESSFUL;
5481 flush_pwnam_cache();
5483 return NT_STATUS_OK;
5487 * ldapsam_create_group creates a new
5488 * posixGroup and sambaGroupMapping object
5489 * in the ldap groups subtree
5491 * The gid is allocated by winbindd.
5494 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5495 TALLOC_CTX *tmp_ctx,
5496 const char *name,
5497 uint32_t *rid)
5499 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5500 NTSTATUS ret;
5501 LDAPMessage *entry = NULL;
5502 LDAPMessage *result = NULL;
5503 uint32_t num_result;
5504 bool is_new_entry = False;
5505 LDAPMod **mods = NULL;
5506 char *filter;
5507 char *groupsidstr;
5508 char *groupname;
5509 char *grouptype;
5510 char *gidstr;
5511 const char *dn = NULL;
5512 struct dom_sid group_sid;
5513 gid_t gid = -1;
5514 int rc;
5516 groupname = escape_ldap_string(talloc_tos(), name);
5517 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5518 groupname, LDAP_OBJ_POSIXGROUP);
5519 TALLOC_FREE(groupname);
5521 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5522 if (rc != LDAP_SUCCESS) {
5523 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5524 return NT_STATUS_UNSUCCESSFUL;
5526 talloc_autofree_ldapmsg(tmp_ctx, result);
5528 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5530 if (num_result > 1) {
5531 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5532 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5535 if (num_result == 1) {
5536 char *tmp;
5537 /* check if it is just a posix group.
5538 * or if there is a sid attached to this entry
5541 entry = ldap_first_entry(priv2ld(ldap_state), result);
5542 if (!entry) {
5543 return NT_STATUS_UNSUCCESSFUL;
5546 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5547 if (tmp) {
5548 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5549 return NT_STATUS_GROUP_EXISTS;
5552 /* it is just a posix group, retrieve the gid and the dn for later use */
5553 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5554 if (!tmp) {
5555 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5556 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5559 gid = strtoul(tmp, NULL, 10);
5561 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5562 if (!dn) {
5563 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5564 return NT_STATUS_NO_MEMORY;
5568 if (num_result == 0) {
5569 is_new_entry = true;
5572 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5573 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5574 return ret;
5577 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5579 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5580 &group_sid));
5581 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5583 if (!groupsidstr || !grouptype) {
5584 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5585 return NT_STATUS_NO_MEMORY;
5588 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5589 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5590 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5591 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5593 if (is_new_entry) {
5594 char *escape_name;
5596 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5598 /* lets allocate a new groupid for this group */
5599 if (!winbind_allocate_gid(&gid)) {
5600 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5601 return NT_STATUS_UNSUCCESSFUL;
5604 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5606 escape_name = escape_rdn_val_string_alloc(name);
5607 if (!escape_name) {
5608 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5609 return NT_STATUS_NO_MEMORY;
5612 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
5614 SAFE_FREE(escape_name);
5616 if (!gidstr || !dn) {
5617 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5618 return NT_STATUS_NO_MEMORY;
5621 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5622 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5623 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5626 talloc_autofree_ldapmod(tmp_ctx, mods);
5628 if (is_new_entry) {
5629 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5630 #if 0
5631 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5632 /* This call may fail with rfc2307bis schema */
5633 /* Retry adding a structural class */
5634 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5635 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5637 #endif
5638 } else {
5639 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5642 if (rc != LDAP_SUCCESS) {
5643 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5644 return NT_STATUS_UNSUCCESSFUL;
5647 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5649 return NT_STATUS_OK;
5652 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5654 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5655 LDAPMessage *result = NULL;
5656 LDAPMessage *entry = NULL;
5657 int num_result;
5658 const char *dn;
5659 char *gidstr;
5660 char *filter;
5661 struct dom_sid group_sid;
5662 int rc;
5664 /* get the group sid */
5665 sid_compose(&group_sid, get_global_sam_sid(), rid);
5667 filter = talloc_asprintf(tmp_ctx,
5668 "(&(sambaSID=%s)"
5669 "(objectClass=%s)"
5670 "(objectClass=%s))",
5671 sid_string_talloc(tmp_ctx, &group_sid),
5672 LDAP_OBJ_POSIXGROUP,
5673 LDAP_OBJ_GROUPMAP);
5674 if (filter == NULL) {
5675 return NT_STATUS_NO_MEMORY;
5678 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5679 if (rc != LDAP_SUCCESS) {
5680 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5681 return NT_STATUS_UNSUCCESSFUL;
5683 talloc_autofree_ldapmsg(tmp_ctx, result);
5685 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5687 if (num_result == 0) {
5688 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5689 return NT_STATUS_NO_SUCH_GROUP;
5692 if (num_result > 1) {
5693 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5694 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5697 entry = ldap_first_entry(priv2ld(ldap_state), result);
5698 if (!entry) {
5699 return NT_STATUS_UNSUCCESSFUL;
5702 /* here it is, retrieve the dn for later use */
5703 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5704 if (!dn) {
5705 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5706 return NT_STATUS_NO_MEMORY;
5709 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5710 if (!gidstr) {
5711 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5712 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5715 /* check no user have this group marked as primary group */
5716 filter = talloc_asprintf(tmp_ctx,
5717 "(&(gidNumber=%s)"
5718 "(objectClass=%s)"
5719 "(objectClass=%s))",
5720 gidstr,
5721 LDAP_OBJ_POSIXACCOUNT,
5722 LDAP_OBJ_SAMBASAMACCOUNT);
5724 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5725 if (rc != LDAP_SUCCESS) {
5726 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5727 return NT_STATUS_UNSUCCESSFUL;
5729 talloc_autofree_ldapmsg(tmp_ctx, result);
5731 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5733 if (num_result != 0) {
5734 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5735 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5738 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5739 if (rc != LDAP_SUCCESS) {
5740 return NT_STATUS_UNSUCCESSFUL;
5743 return NT_STATUS_OK;
5746 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5747 TALLOC_CTX *tmp_ctx,
5748 uint32_t group_rid,
5749 uint32_t member_rid,
5750 int modop)
5752 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5753 LDAPMessage *entry = NULL;
5754 LDAPMessage *result = NULL;
5755 uint32_t num_result;
5756 LDAPMod **mods = NULL;
5757 char *filter;
5758 char *uidstr;
5759 const char *dn = NULL;
5760 struct dom_sid group_sid;
5761 struct dom_sid member_sid;
5762 int rc;
5764 switch (modop) {
5765 case LDAP_MOD_ADD:
5766 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5767 break;
5768 case LDAP_MOD_DELETE:
5769 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5770 break;
5771 default:
5772 return NT_STATUS_UNSUCCESSFUL;
5775 /* get member sid */
5776 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5778 /* get the group sid */
5779 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5781 filter = talloc_asprintf(tmp_ctx,
5782 "(&(sambaSID=%s)"
5783 "(objectClass=%s)"
5784 "(objectClass=%s))",
5785 sid_string_talloc(tmp_ctx, &member_sid),
5786 LDAP_OBJ_POSIXACCOUNT,
5787 LDAP_OBJ_SAMBASAMACCOUNT);
5788 if (filter == NULL) {
5789 return NT_STATUS_NO_MEMORY;
5792 /* get the member uid */
5793 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5794 if (rc != LDAP_SUCCESS) {
5795 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5796 return NT_STATUS_UNSUCCESSFUL;
5798 talloc_autofree_ldapmsg(tmp_ctx, result);
5800 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5802 if (num_result == 0) {
5803 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5804 return NT_STATUS_NO_SUCH_MEMBER;
5807 if (num_result > 1) {
5808 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5809 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5812 entry = ldap_first_entry(priv2ld(ldap_state), result);
5813 if (!entry) {
5814 return NT_STATUS_UNSUCCESSFUL;
5817 if (modop == LDAP_MOD_DELETE) {
5818 /* check if we are trying to remove the member from his primary group */
5819 char *gidstr;
5820 gid_t user_gid, group_gid;
5822 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5823 if (!gidstr) {
5824 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5825 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5828 user_gid = strtoul(gidstr, NULL, 10);
5830 if (!sid_to_gid(&group_sid, &group_gid)) {
5831 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5832 return NT_STATUS_UNSUCCESSFUL;
5835 if (user_gid == group_gid) {
5836 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5837 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5841 /* here it is, retrieve the uid for later use */
5842 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5843 if (!uidstr) {
5844 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5845 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5848 filter = talloc_asprintf(tmp_ctx,
5849 "(&(sambaSID=%s)"
5850 "(objectClass=%s)"
5851 "(objectClass=%s))",
5852 sid_string_talloc(tmp_ctx, &group_sid),
5853 LDAP_OBJ_POSIXGROUP,
5854 LDAP_OBJ_GROUPMAP);
5856 /* get the group */
5857 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5858 if (rc != LDAP_SUCCESS) {
5859 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5860 return NT_STATUS_UNSUCCESSFUL;
5862 talloc_autofree_ldapmsg(tmp_ctx, result);
5864 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5866 if (num_result == 0) {
5867 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5868 return NT_STATUS_NO_SUCH_GROUP;
5871 if (num_result > 1) {
5872 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5873 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5876 entry = ldap_first_entry(priv2ld(ldap_state), result);
5877 if (!entry) {
5878 return NT_STATUS_UNSUCCESSFUL;
5881 /* here it is, retrieve the dn for later use */
5882 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5883 if (!dn) {
5884 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5885 return NT_STATUS_NO_MEMORY;
5888 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5890 talloc_autofree_ldapmod(tmp_ctx, mods);
5892 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5893 if (rc != LDAP_SUCCESS) {
5894 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5895 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5896 return NT_STATUS_MEMBER_IN_GROUP;
5898 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5899 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5900 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5902 return NT_STATUS_UNSUCCESSFUL;
5905 return NT_STATUS_OK;
5908 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5909 TALLOC_CTX *tmp_ctx,
5910 uint32_t group_rid,
5911 uint32_t member_rid)
5913 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5915 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5916 TALLOC_CTX *tmp_ctx,
5917 uint32_t group_rid,
5918 uint32_t member_rid)
5920 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5923 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5924 TALLOC_CTX *mem_ctx,
5925 struct samu *sampass)
5927 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5928 LDAPMessage *entry = NULL;
5929 LDAPMessage *result = NULL;
5930 uint32_t num_result;
5931 LDAPMod **mods = NULL;
5932 char *filter;
5933 char *escape_username;
5934 char *gidstr;
5935 const char *dn = NULL;
5936 gid_t gid;
5937 int rc;
5939 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5941 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5942 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5943 return NT_STATUS_UNSUCCESSFUL;
5945 gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5946 if (!gidstr) {
5947 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5948 return NT_STATUS_NO_MEMORY;
5951 escape_username = escape_ldap_string(talloc_tos(),
5952 pdb_get_username(sampass));
5953 if (escape_username== NULL) {
5954 return NT_STATUS_NO_MEMORY;
5957 filter = talloc_asprintf(mem_ctx,
5958 "(&(uid=%s)"
5959 "(objectClass=%s)"
5960 "(objectClass=%s))",
5961 escape_username,
5962 LDAP_OBJ_POSIXACCOUNT,
5963 LDAP_OBJ_SAMBASAMACCOUNT);
5965 TALLOC_FREE(escape_username);
5967 if (filter == NULL) {
5968 return NT_STATUS_NO_MEMORY;
5971 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5972 if (rc != LDAP_SUCCESS) {
5973 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5974 return NT_STATUS_UNSUCCESSFUL;
5976 talloc_autofree_ldapmsg(mem_ctx, result);
5978 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5980 if (num_result == 0) {
5981 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5982 return NT_STATUS_NO_SUCH_USER;
5985 if (num_result > 1) {
5986 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5987 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5990 entry = ldap_first_entry(priv2ld(ldap_state), result);
5991 if (!entry) {
5992 return NT_STATUS_UNSUCCESSFUL;
5995 /* retrieve the dn for later use */
5996 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5997 if (!dn) {
5998 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5999 return NT_STATUS_NO_MEMORY;
6002 /* remove the old one, and add the new one, this way we do not risk races */
6003 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
6005 if (mods == NULL) {
6006 return NT_STATUS_OK;
6009 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6011 if (rc != LDAP_SUCCESS) {
6012 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6013 pdb_get_username(sampass), gidstr));
6014 return NT_STATUS_UNSUCCESSFUL;
6017 flush_pwnam_cache();
6019 return NT_STATUS_OK;
6023 /**********************************************************************
6024 trusted domains functions
6025 *********************************************************************/
6027 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6028 const char *domain)
6030 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6031 ldap_state->domain_dn);
6034 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6035 TALLOC_CTX *mem_ctx,
6036 const char *domain, LDAPMessage **entry)
6038 int rc;
6039 char *filter;
6040 int scope = LDAP_SCOPE_SUBTREE;
6041 const char **attrs = NULL; /* NULL: get all attrs */
6042 int attrsonly = 0; /* 0: return values too */
6043 LDAPMessage *result = NULL;
6044 char *trusted_dn;
6045 uint32_t num_result;
6047 filter = talloc_asprintf(talloc_tos(),
6048 "(&(objectClass=%s)(sambaDomainName=%s))",
6049 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6051 trusted_dn = trusteddom_dn(ldap_state, domain);
6052 if (trusted_dn == NULL) {
6053 return False;
6055 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6056 filter, attrs, attrsonly, &result);
6058 if (result != NULL) {
6059 talloc_autofree_ldapmsg(mem_ctx, result);
6062 if (rc == LDAP_NO_SUCH_OBJECT) {
6063 *entry = NULL;
6064 return True;
6067 if (rc != LDAP_SUCCESS) {
6068 return False;
6071 num_result = ldap_count_entries(priv2ld(ldap_state), result);
6073 if (num_result > 1) {
6074 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6075 "%s object for domain '%s'?!\n",
6076 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6077 return False;
6080 if (num_result == 0) {
6081 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6082 "%s object for domain %s.\n",
6083 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6084 *entry = NULL;
6085 } else {
6086 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6089 return True;
6092 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6093 const char *domain,
6094 char** pwd,
6095 struct dom_sid *sid,
6096 time_t *pass_last_set_time)
6098 struct ldapsam_privates *ldap_state =
6099 (struct ldapsam_privates *)methods->private_data;
6100 LDAPMessage *entry = NULL;
6102 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6104 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6105 (entry == NULL))
6107 return False;
6110 /* password */
6111 if (pwd != NULL) {
6112 char *pwd_str;
6113 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6114 entry, "sambaClearTextPassword", talloc_tos());
6115 if (pwd_str == NULL) {
6116 return False;
6118 /* trusteddom_pw routines do not use talloc yet... */
6119 *pwd = SMB_STRDUP(pwd_str);
6120 if (*pwd == NULL) {
6121 return False;
6125 /* last change time */
6126 if (pass_last_set_time != NULL) {
6127 char *time_str;
6128 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6129 entry, "sambaPwdLastSet", talloc_tos());
6130 if (time_str == NULL) {
6131 return False;
6133 *pass_last_set_time = (time_t)atol(time_str);
6136 /* domain sid */
6137 if (sid != NULL) {
6138 char *sid_str;
6139 struct dom_sid dom_sid;
6140 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6141 entry, "sambaSID",
6142 talloc_tos());
6143 if (sid_str == NULL) {
6144 return False;
6146 if (!string_to_sid(&dom_sid, sid_str)) {
6147 return False;
6149 sid_copy(sid, &dom_sid);
6152 return True;
6155 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6156 const char* domain,
6157 const char* pwd,
6158 const struct dom_sid *sid)
6160 struct ldapsam_privates *ldap_state =
6161 (struct ldapsam_privates *)methods->private_data;
6162 LDAPMessage *entry = NULL;
6163 LDAPMod **mods = NULL;
6164 char *prev_pwd = NULL;
6165 char *trusted_dn = NULL;
6166 int rc;
6168 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6171 * get the current entry (if there is one) in order to put the
6172 * current password into the previous password attribute
6174 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6175 return False;
6178 mods = NULL;
6179 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6180 LDAP_OBJ_TRUSTDOM_PASSWORD);
6181 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6182 domain);
6183 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6184 sid_string_tos(sid));
6185 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6186 talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6187 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6188 "sambaClearTextPassword", pwd);
6190 if (entry != NULL) {
6191 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6192 entry, "sambaClearTextPassword", talloc_tos());
6193 if (prev_pwd != NULL) {
6194 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6195 "sambaPreviousClearTextPassword",
6196 prev_pwd);
6200 talloc_autofree_ldapmod(talloc_tos(), mods);
6202 trusted_dn = trusteddom_dn(ldap_state, domain);
6203 if (trusted_dn == NULL) {
6204 return False;
6206 if (entry == NULL) {
6207 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6208 } else {
6209 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6212 if (rc != LDAP_SUCCESS) {
6213 DEBUG(1, ("error writing trusted domain password!\n"));
6214 return False;
6217 return True;
6220 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6221 const char *domain)
6223 int rc;
6224 struct ldapsam_privates *ldap_state =
6225 (struct ldapsam_privates *)methods->private_data;
6226 LDAPMessage *entry = NULL;
6227 const char *trusted_dn;
6229 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6230 return False;
6233 if (entry == NULL) {
6234 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6235 "%s\n", domain));
6236 return True;
6239 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6240 entry);
6241 if (trusted_dn == NULL) {
6242 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6243 return False;
6246 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6247 if (rc != LDAP_SUCCESS) {
6248 return False;
6251 return True;
6254 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6255 TALLOC_CTX *mem_ctx,
6256 uint32_t *num_domains,
6257 struct trustdom_info ***domains)
6259 int rc;
6260 struct ldapsam_privates *ldap_state =
6261 (struct ldapsam_privates *)methods->private_data;
6262 char *filter;
6263 int scope = LDAP_SCOPE_SUBTREE;
6264 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6265 int attrsonly = 0; /* 0: return values too */
6266 LDAPMessage *result = NULL;
6267 LDAPMessage *entry = NULL;
6269 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6270 LDAP_OBJ_TRUSTDOM_PASSWORD);
6272 rc = smbldap_search(ldap_state->smbldap_state,
6273 ldap_state->domain_dn,
6274 scope,
6275 filter,
6276 attrs,
6277 attrsonly,
6278 &result);
6280 if (result != NULL) {
6281 talloc_autofree_ldapmsg(mem_ctx, result);
6284 if (rc != LDAP_SUCCESS) {
6285 return NT_STATUS_UNSUCCESSFUL;
6288 *num_domains = 0;
6289 if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6290 DEBUG(1, ("talloc failed\n"));
6291 return NT_STATUS_NO_MEMORY;
6294 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6295 entry != NULL;
6296 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6298 char *dom_name, *dom_sid_str;
6299 struct trustdom_info *dom_info;
6301 dom_info = talloc(*domains, struct trustdom_info);
6302 if (dom_info == NULL) {
6303 DEBUG(1, ("talloc failed\n"));
6304 return NT_STATUS_NO_MEMORY;
6307 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6308 entry,
6309 "sambaDomainName",
6310 talloc_tos());
6311 if (dom_name == NULL) {
6312 DEBUG(1, ("talloc failed\n"));
6313 return NT_STATUS_NO_MEMORY;
6315 dom_info->name = dom_name;
6317 dom_sid_str = smbldap_talloc_single_attribute(
6318 priv2ld(ldap_state), entry, "sambaSID",
6319 talloc_tos());
6320 if (dom_sid_str == NULL) {
6321 DEBUG(1, ("talloc failed\n"));
6322 return NT_STATUS_NO_MEMORY;
6324 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6325 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6326 dom_sid_str));
6327 return NT_STATUS_UNSUCCESSFUL;
6330 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6331 domains, num_domains);
6333 if (*domains == NULL) {
6334 DEBUG(1, ("talloc failed\n"));
6335 return NT_STATUS_NO_MEMORY;
6339 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6340 return NT_STATUS_OK;
6344 /**********************************************************************
6345 Housekeeping
6346 *********************************************************************/
6348 static void free_private_data(void **vp)
6350 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6352 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6354 if ((*ldap_state)->result != NULL) {
6355 ldap_msgfree((*ldap_state)->result);
6356 (*ldap_state)->result = NULL;
6358 if ((*ldap_state)->domain_dn != NULL) {
6359 SAFE_FREE((*ldap_state)->domain_dn);
6362 *ldap_state = NULL;
6364 /* No need to free any further, as it is talloc()ed */
6367 /*********************************************************************
6368 Intitalise the parts of the pdb_methods structure that are common to
6369 all pdb_ldap modes
6370 *********************************************************************/
6372 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6374 NTSTATUS nt_status;
6375 struct ldapsam_privates *ldap_state;
6376 char *bind_dn = NULL;
6377 char *bind_secret = NULL;
6379 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6380 return nt_status;
6383 (*pdb_method)->name = "ldapsam";
6385 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6386 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6387 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6388 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6389 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6390 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6392 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6393 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6394 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6395 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6396 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6397 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6398 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6400 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6401 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6403 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6405 (*pdb_method)->capabilities = ldapsam_capabilities;
6406 (*pdb_method)->new_rid = ldapsam_new_rid;
6408 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6409 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6410 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6411 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6413 /* TODO: Setup private data and free */
6415 if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6416 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6417 return NT_STATUS_NO_MEMORY;
6420 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
6421 DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
6422 return NT_STATUS_NO_MEMORY;
6425 nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
6426 location, false, bind_dn, bind_secret,
6427 &ldap_state->smbldap_state);
6428 memset(bind_secret, '\0', strlen(bind_secret));
6429 SAFE_FREE(bind_secret);
6430 SAFE_FREE(bind_dn);
6431 if ( !NT_STATUS_IS_OK(nt_status) ) {
6432 return nt_status;
6435 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6436 return NT_STATUS_NO_MEMORY;
6439 (*pdb_method)->private_data = ldap_state;
6441 (*pdb_method)->free_private_data = free_private_data;
6443 return NT_STATUS_OK;
6446 /**********************************************************************
6447 Initialise the normal mode for pdb_ldap
6448 *********************************************************************/
6450 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
6452 NTSTATUS nt_status;
6453 struct ldapsam_privates *ldap_state = NULL;
6454 uint32_t alg_rid_base;
6455 char *alg_rid_base_string = NULL;
6456 LDAPMessage *result = NULL;
6457 LDAPMessage *entry = NULL;
6458 struct dom_sid ldap_domain_sid;
6459 struct dom_sid secrets_domain_sid;
6460 char *domain_sid_string = NULL;
6461 char *dn = NULL;
6462 char *uri = talloc_strdup( NULL, location );
6464 trim_char( uri, '\"', '\"' );
6465 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6467 TALLOC_FREE(uri);
6469 if (!NT_STATUS_IS_OK(nt_status)) {
6470 return nt_status;
6473 (*pdb_method)->name = "ldapsam";
6475 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6476 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6477 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6478 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6479 (*pdb_method)->search_users = ldapsam_search_users;
6480 (*pdb_method)->search_groups = ldapsam_search_groups;
6481 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6483 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6484 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6485 (*pdb_method)->enum_group_memberships =
6486 ldapsam_enum_group_memberships;
6487 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6488 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6489 (*pdb_method)->uid_to_sid = ldapsam_uid_to_sid;
6490 (*pdb_method)->gid_to_sid = ldapsam_gid_to_sid;
6492 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6493 (*pdb_method)->create_user = ldapsam_create_user;
6494 (*pdb_method)->delete_user = ldapsam_delete_user;
6495 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6496 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6497 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6498 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6499 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6503 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6504 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6506 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6508 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6509 &result,
6510 ldap_state->domain_name, True);
6512 if ( !NT_STATUS_IS_OK(nt_status) ) {
6513 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6514 "info, nor add one to the domain. "
6515 "We cannot work reliably without it.\n"));
6516 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6519 /* Given that the above might fail, everything below this must be
6520 * optional */
6522 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6523 result);
6524 if (!entry) {
6525 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6526 "entry\n"));
6527 ldap_msgfree(result);
6528 return NT_STATUS_UNSUCCESSFUL;
6531 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6532 if (!dn) {
6533 ldap_msgfree(result);
6534 return NT_STATUS_UNSUCCESSFUL;
6537 ldap_state->domain_dn = smb_xstrdup(dn);
6538 TALLOC_FREE(dn);
6540 domain_sid_string = smbldap_talloc_single_attribute(
6541 ldap_state->smbldap_state->ldap_struct,
6542 entry,
6543 get_userattr_key2string(ldap_state->schema_ver,
6544 LDAP_ATTR_USER_SID),
6545 talloc_tos());
6547 if (domain_sid_string) {
6548 bool found_sid;
6549 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6550 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6551 "read as a valid SID\n", domain_sid_string));
6552 ldap_msgfree(result);
6553 TALLOC_FREE(domain_sid_string);
6554 return NT_STATUS_INVALID_PARAMETER;
6556 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6557 &secrets_domain_sid);
6558 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6559 &ldap_domain_sid)) {
6560 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6561 "%s based on pdb_ldap results %s -> %s\n",
6562 ldap_state->domain_name,
6563 sid_string_dbg(&secrets_domain_sid),
6564 sid_string_dbg(&ldap_domain_sid)));
6566 /* reset secrets.tdb sid */
6567 secrets_store_domain_sid(ldap_state->domain_name,
6568 &ldap_domain_sid);
6569 DEBUG(1, ("New global sam SID: %s\n",
6570 sid_string_dbg(get_global_sam_sid())));
6572 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6573 TALLOC_FREE(domain_sid_string);
6576 alg_rid_base_string = smbldap_talloc_single_attribute(
6577 ldap_state->smbldap_state->ldap_struct,
6578 entry,
6579 get_attr_key2string( dominfo_attr_list,
6580 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6581 talloc_tos());
6582 if (alg_rid_base_string) {
6583 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6584 if (alg_rid_base != algorithmic_rid_base()) {
6585 DEBUG(0, ("The value of 'algorithmic RID base' has "
6586 "changed since the LDAP\n"
6587 "database was initialised. Aborting. \n"));
6588 ldap_msgfree(result);
6589 TALLOC_FREE(alg_rid_base_string);
6590 return NT_STATUS_UNSUCCESSFUL;
6592 TALLOC_FREE(alg_rid_base_string);
6594 ldap_msgfree(result);
6596 return NT_STATUS_OK;
6599 NTSTATUS pdb_ldap_init(void)
6601 NTSTATUS nt_status;
6602 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6603 return nt_status;
6605 /* Let pdb_nds register backends */
6606 pdb_nds_init();
6608 pdb_ipa_init();
6610 return NT_STATUS_OK;