Rewrite torture_samba3_rpc_sharesec() to use a non-privileged user for share security...
[Samba/bb.git] / source3 / passdb / pdb_ldap.c
blobffd57431cec39d95c74077355198142a6cb01687
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 if (!strlower_m( oldname_lower )) {
2019 return NT_STATUS_INVALID_PARAMETER;
2021 fstrcpy( newname_lower, newname );
2022 if (!strlower_m( newname_lower )) {
2023 return NT_STATUS_INVALID_PARAMETER;
2026 rename_script = realloc_string_sub2(rename_script,
2027 "%unew",
2028 newname_lower,
2029 true,
2030 true);
2031 if (!rename_script) {
2032 return NT_STATUS_NO_MEMORY;
2034 rename_script = realloc_string_sub2(rename_script,
2035 "%uold",
2036 oldname_lower,
2037 true,
2038 true);
2039 rc = smbrun(rename_script, NULL);
2041 DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2042 rename_script, rc));
2044 TALLOC_FREE(rename_script);
2046 if (rc == 0) {
2047 smb_nscd_flush_user_cache();
2050 if (rc)
2051 return NT_STATUS_UNSUCCESSFUL;
2053 return NT_STATUS_OK;
2056 /**********************************************************************
2057 Add struct samu to LDAP.
2058 *********************************************************************/
2060 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2062 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2063 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2064 int rc;
2065 LDAPMessage *result = NULL;
2066 LDAPMessage *entry = NULL;
2067 LDAPMod **mods = NULL;
2068 int ldap_op = LDAP_MOD_REPLACE;
2069 uint32_t num_result;
2070 const char **attr_list;
2071 char *escape_user = NULL;
2072 const char *username = pdb_get_username(newpwd);
2073 const struct dom_sid *sid = pdb_get_user_sid(newpwd);
2074 char *filter = NULL;
2075 char *dn = NULL;
2076 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2077 TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2079 if (!ctx) {
2080 return NT_STATUS_NO_MEMORY;
2083 if (!username || !*username) {
2084 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2085 status = NT_STATUS_INVALID_PARAMETER;
2086 goto fn_exit;
2089 /* free this list after the second search or in case we exit on failure */
2090 attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2092 rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2094 if (rc != LDAP_SUCCESS) {
2095 goto fn_exit;
2098 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2099 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n",
2100 username));
2101 goto fn_exit;
2103 ldap_msgfree(result);
2104 result = NULL;
2106 if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2107 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2108 sid, &result);
2109 if (rc == LDAP_SUCCESS) {
2110 if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2111 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2112 "already in the base, with samba "
2113 "attributes\n", sid_string_dbg(sid)));
2114 goto fn_exit;
2116 ldap_msgfree(result);
2117 result = NULL;
2121 /* does the entry already exist but without a samba attributes?
2122 we need to return the samba attributes here */
2124 escape_user = escape_ldap_string(talloc_tos(), username);
2125 filter = talloc_strdup(attr_list, "(uid=%u)");
2126 if (!filter) {
2127 status = NT_STATUS_NO_MEMORY;
2128 goto fn_exit;
2130 filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2131 TALLOC_FREE(escape_user);
2132 if (!filter) {
2133 status = NT_STATUS_NO_MEMORY;
2134 goto fn_exit;
2137 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2138 filter, attr_list, &result);
2139 if ( rc != LDAP_SUCCESS ) {
2140 goto fn_exit;
2143 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2145 if (num_result > 1) {
2146 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2147 goto fn_exit;
2150 /* Check if we need to update an existing entry */
2151 if (num_result == 1) {
2152 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2153 ldap_op = LDAP_MOD_REPLACE;
2154 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2155 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2156 if (!dn) {
2157 status = NT_STATUS_NO_MEMORY;
2158 goto fn_exit;
2161 } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2163 /* There might be a SID for this account already - say an idmap entry */
2165 filter = talloc_asprintf(ctx,
2166 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2167 get_userattr_key2string(ldap_state->schema_ver,
2168 LDAP_ATTR_USER_SID),
2169 sid_string_talloc(ctx, sid),
2170 LDAP_OBJ_IDMAP_ENTRY,
2171 LDAP_OBJ_SID_ENTRY);
2172 if (!filter) {
2173 status = NT_STATUS_NO_MEMORY;
2174 goto fn_exit;
2177 /* free old result before doing a new search */
2178 if (result != NULL) {
2179 ldap_msgfree(result);
2180 result = NULL;
2182 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2183 filter, attr_list, &result);
2185 if ( rc != LDAP_SUCCESS ) {
2186 goto fn_exit;
2189 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2191 if (num_result > 1) {
2192 DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2193 goto fn_exit;
2196 /* Check if we need to update an existing entry */
2197 if (num_result == 1) {
2199 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2200 ldap_op = LDAP_MOD_REPLACE;
2201 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2202 dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2203 if (!dn) {
2204 status = NT_STATUS_NO_MEMORY;
2205 goto fn_exit;
2210 if (num_result == 0) {
2211 char *escape_username;
2212 /* Check if we need to add an entry */
2213 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2214 ldap_op = LDAP_MOD_ADD;
2216 escape_username = escape_rdn_val_string_alloc(username);
2217 if (!escape_username) {
2218 status = NT_STATUS_NO_MEMORY;
2219 goto fn_exit;
2222 if (username[strlen(username)-1] == '$') {
2223 dn = talloc_asprintf(ctx,
2224 "uid=%s,%s",
2225 escape_username,
2226 lp_ldap_machine_suffix(talloc_tos()));
2227 } else {
2228 dn = talloc_asprintf(ctx,
2229 "uid=%s,%s",
2230 escape_username,
2231 lp_ldap_user_suffix(talloc_tos()));
2234 SAFE_FREE(escape_username);
2235 if (!dn) {
2236 status = NT_STATUS_NO_MEMORY;
2237 goto fn_exit;
2241 if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2242 pdb_element_is_set_or_changed)) {
2243 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2244 if (mods != NULL) {
2245 ldap_mods_free(mods, true);
2247 goto fn_exit;
2250 if (mods == NULL) {
2251 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2252 goto fn_exit;
2254 switch ( ldap_state->schema_ver ) {
2255 case SCHEMAVER_SAMBASAMACCOUNT:
2256 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2257 break;
2258 default:
2259 DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2260 break;
2263 ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2264 if (!NT_STATUS_IS_OK(ret)) {
2265 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2266 pdb_get_username(newpwd),dn));
2267 ldap_mods_free(mods, true);
2268 goto fn_exit;
2271 DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2272 ldap_mods_free(mods, true);
2274 status = NT_STATUS_OK;
2276 fn_exit:
2278 TALLOC_FREE(ctx);
2279 if (result) {
2280 ldap_msgfree(result);
2282 return status;
2285 /**********************************************************************
2286 *********************************************************************/
2288 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2289 const char *filter,
2290 LDAPMessage ** result)
2292 int scope = LDAP_SCOPE_SUBTREE;
2293 int rc;
2294 const char **attr_list;
2296 attr_list = get_attr_list(NULL, groupmap_attr_list);
2297 rc = smbldap_search(ldap_state->smbldap_state,
2298 lp_ldap_suffix (talloc_tos()), scope,
2299 filter, attr_list, 0, result);
2300 TALLOC_FREE(attr_list);
2302 return rc;
2305 /**********************************************************************
2306 *********************************************************************/
2308 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2309 GROUP_MAP *map, LDAPMessage *entry)
2311 char *temp = NULL;
2312 TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2314 if (ldap_state == NULL || map == NULL || entry == NULL ||
2315 ldap_state->smbldap_state->ldap_struct == NULL) {
2316 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2317 TALLOC_FREE(ctx);
2318 return false;
2321 temp = smbldap_talloc_single_attribute(
2322 ldap_state->smbldap_state->ldap_struct,
2323 entry,
2324 get_attr_key2string(groupmap_attr_list,
2325 LDAP_ATTR_GIDNUMBER),
2326 ctx);
2327 if (!temp) {
2328 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2329 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2330 TALLOC_FREE(ctx);
2331 return false;
2333 DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2335 map->gid = (gid_t)atol(temp);
2337 TALLOC_FREE(temp);
2338 temp = smbldap_talloc_single_attribute(
2339 ldap_state->smbldap_state->ldap_struct,
2340 entry,
2341 get_attr_key2string(groupmap_attr_list,
2342 LDAP_ATTR_GROUP_SID),
2343 ctx);
2344 if (!temp) {
2345 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2346 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2347 TALLOC_FREE(ctx);
2348 return false;
2351 if (!string_to_sid(&map->sid, temp)) {
2352 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2353 TALLOC_FREE(ctx);
2354 return false;
2357 TALLOC_FREE(temp);
2358 temp = smbldap_talloc_single_attribute(
2359 ldap_state->smbldap_state->ldap_struct,
2360 entry,
2361 get_attr_key2string(groupmap_attr_list,
2362 LDAP_ATTR_GROUP_TYPE),
2363 ctx);
2364 if (!temp) {
2365 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2366 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2367 TALLOC_FREE(ctx);
2368 return false;
2370 map->sid_name_use = (enum lsa_SidType)atol(temp);
2372 if ((map->sid_name_use < SID_NAME_USER) ||
2373 (map->sid_name_use > SID_NAME_UNKNOWN)) {
2374 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2375 TALLOC_FREE(ctx);
2376 return false;
2379 TALLOC_FREE(temp);
2380 temp = smbldap_talloc_single_attribute(
2381 ldap_state->smbldap_state->ldap_struct,
2382 entry,
2383 get_attr_key2string(groupmap_attr_list,
2384 LDAP_ATTR_DISPLAY_NAME),
2385 ctx);
2386 if (!temp) {
2387 temp = smbldap_talloc_single_attribute(
2388 ldap_state->smbldap_state->ldap_struct,
2389 entry,
2390 get_attr_key2string(groupmap_attr_list,
2391 LDAP_ATTR_CN),
2392 ctx);
2393 if (!temp) {
2394 DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2395 for gidNumber(%lu)\n",(unsigned long)map->gid));
2396 TALLOC_FREE(ctx);
2397 return false;
2400 map->nt_name = talloc_strdup(map, temp);
2401 if (!map->nt_name) {
2402 TALLOC_FREE(ctx);
2403 return false;
2406 TALLOC_FREE(temp);
2407 temp = smbldap_talloc_single_attribute(
2408 ldap_state->smbldap_state->ldap_struct,
2409 entry,
2410 get_attr_key2string(groupmap_attr_list,
2411 LDAP_ATTR_DESC),
2412 ctx);
2413 if (!temp) {
2414 temp = talloc_strdup(ctx, "");
2415 if (!temp) {
2416 TALLOC_FREE(ctx);
2417 return false;
2420 map->comment = talloc_strdup(map, temp);
2421 if (!map->comment) {
2422 TALLOC_FREE(ctx);
2423 return false;
2426 if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2427 struct unixid id;
2428 id.id = map->gid;
2429 id.type = ID_TYPE_GID;
2431 idmap_cache_set_sid2unixid(&map->sid, &id);
2434 TALLOC_FREE(ctx);
2435 return true;
2438 /**********************************************************************
2439 *********************************************************************/
2441 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2442 const char *filter,
2443 GROUP_MAP *map)
2445 struct ldapsam_privates *ldap_state =
2446 (struct ldapsam_privates *)methods->private_data;
2447 LDAPMessage *result = NULL;
2448 LDAPMessage *entry = NULL;
2449 int count;
2451 if (ldapsam_search_one_group(ldap_state, filter, &result)
2452 != LDAP_SUCCESS) {
2453 return NT_STATUS_NO_SUCH_GROUP;
2456 count = ldap_count_entries(priv2ld(ldap_state), result);
2458 if (count < 1) {
2459 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2460 "%s\n", filter));
2461 ldap_msgfree(result);
2462 return NT_STATUS_NO_SUCH_GROUP;
2465 if (count > 1) {
2466 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2467 "count=%d\n", filter, count));
2468 ldap_msgfree(result);
2469 return NT_STATUS_NO_SUCH_GROUP;
2472 entry = ldap_first_entry(priv2ld(ldap_state), result);
2474 if (!entry) {
2475 ldap_msgfree(result);
2476 return NT_STATUS_UNSUCCESSFUL;
2479 if (!init_group_from_ldap(ldap_state, map, entry)) {
2480 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2481 "group filter %s\n", filter));
2482 ldap_msgfree(result);
2483 return NT_STATUS_NO_SUCH_GROUP;
2486 ldap_msgfree(result);
2487 return NT_STATUS_OK;
2490 /**********************************************************************
2491 *********************************************************************/
2493 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2494 struct dom_sid sid)
2496 char *filter = NULL;
2497 NTSTATUS status;
2498 fstring tmp;
2500 if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2501 LDAP_OBJ_GROUPMAP,
2502 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2503 sid_to_fstring(tmp, &sid)) < 0) {
2504 return NT_STATUS_NO_MEMORY;
2507 status = ldapsam_getgroup(methods, filter, map);
2508 SAFE_FREE(filter);
2509 return status;
2512 /**********************************************************************
2513 *********************************************************************/
2515 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2516 gid_t gid)
2518 char *filter = NULL;
2519 NTSTATUS status;
2521 if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2522 LDAP_OBJ_GROUPMAP,
2523 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2524 (unsigned long)gid) < 0) {
2525 return NT_STATUS_NO_MEMORY;
2528 status = ldapsam_getgroup(methods, filter, map);
2529 SAFE_FREE(filter);
2530 return status;
2533 /**********************************************************************
2534 *********************************************************************/
2536 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2537 const char *name)
2539 char *filter = NULL;
2540 char *escape_name = escape_ldap_string(talloc_tos(), name);
2541 NTSTATUS status;
2543 if (!escape_name) {
2544 return NT_STATUS_NO_MEMORY;
2547 if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2548 LDAP_OBJ_GROUPMAP,
2549 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2550 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2551 escape_name) < 0) {
2552 TALLOC_FREE(escape_name);
2553 return NT_STATUS_NO_MEMORY;
2556 TALLOC_FREE(escape_name);
2557 status = ldapsam_getgroup(methods, filter, map);
2558 SAFE_FREE(filter);
2559 return status;
2562 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2563 LDAPMessage *entry,
2564 const struct dom_sid *domain_sid,
2565 uint32_t *rid)
2567 fstring str;
2568 struct dom_sid sid;
2570 if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2571 str, sizeof(str)-1)) {
2572 DEBUG(10, ("Could not find sambaSID attribute\n"));
2573 return False;
2576 if (!string_to_sid(&sid, str)) {
2577 DEBUG(10, ("Could not convert string %s to sid\n", str));
2578 return False;
2581 if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2582 DEBUG(10, ("SID %s is not in expected domain %s\n",
2583 str, sid_string_dbg(domain_sid)));
2584 return False;
2587 if (!sid_peek_rid(&sid, rid)) {
2588 DEBUG(10, ("Could not peek into RID\n"));
2589 return False;
2592 return True;
2595 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2596 TALLOC_CTX *mem_ctx,
2597 const struct dom_sid *group,
2598 uint32_t **pp_member_rids,
2599 size_t *p_num_members)
2601 struct ldapsam_privates *ldap_state =
2602 (struct ldapsam_privates *)methods->private_data;
2603 struct smbldap_state *conn = ldap_state->smbldap_state;
2604 const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2605 const char *sid_attrs[] = { "sambaSID", NULL };
2606 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2607 LDAPMessage *result = NULL;
2608 LDAPMessage *entry;
2609 char *filter;
2610 char **values = NULL;
2611 char **memberuid;
2612 char *gidstr;
2613 int rc, count;
2615 *pp_member_rids = NULL;
2616 *p_num_members = 0;
2618 filter = talloc_asprintf(mem_ctx,
2619 "(&(objectClass=%s)"
2620 "(objectClass=%s)"
2621 "(sambaSID=%s))",
2622 LDAP_OBJ_POSIXGROUP,
2623 LDAP_OBJ_GROUPMAP,
2624 sid_string_talloc(mem_ctx, group));
2625 if (filter == NULL) {
2626 ret = NT_STATUS_NO_MEMORY;
2627 goto done;
2630 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2631 LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2632 &result);
2634 if (rc != LDAP_SUCCESS)
2635 goto done;
2637 talloc_autofree_ldapmsg(mem_ctx, result);
2639 count = ldap_count_entries(conn->ldap_struct, result);
2641 if (count > 1) {
2642 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2643 sid_string_dbg(group)));
2644 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2645 goto done;
2648 if (count == 0) {
2649 ret = NT_STATUS_NO_SUCH_GROUP;
2650 goto done;
2653 entry = ldap_first_entry(conn->ldap_struct, result);
2654 if (entry == NULL)
2655 goto done;
2657 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2658 if (!gidstr) {
2659 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2660 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2661 goto done;
2664 values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2666 if ((values != NULL) && (values[0] != NULL)) {
2668 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2669 if (filter == NULL) {
2670 ret = NT_STATUS_NO_MEMORY;
2671 goto done;
2674 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2675 char *escape_memberuid;
2677 escape_memberuid = escape_ldap_string(talloc_tos(),
2678 *memberuid);
2679 if (escape_memberuid == NULL) {
2680 ret = NT_STATUS_NO_MEMORY;
2681 goto done;
2684 filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2685 TALLOC_FREE(escape_memberuid);
2686 if (filter == NULL) {
2687 ret = NT_STATUS_NO_MEMORY;
2688 goto done;
2692 filter = talloc_asprintf_append_buffer(filter, "))");
2693 if (filter == NULL) {
2694 ret = NT_STATUS_NO_MEMORY;
2695 goto done;
2698 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2699 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2700 &result);
2702 if (rc != LDAP_SUCCESS)
2703 goto done;
2705 count = ldap_count_entries(conn->ldap_struct, result);
2706 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2708 talloc_autofree_ldapmsg(mem_ctx, result);
2710 for (entry = ldap_first_entry(conn->ldap_struct, result);
2711 entry != NULL;
2712 entry = ldap_next_entry(conn->ldap_struct, entry))
2714 char *sidstr;
2715 struct dom_sid sid;
2716 uint32_t rid;
2718 sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2719 entry, "sambaSID",
2720 mem_ctx);
2721 if (!sidstr) {
2722 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2723 "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2724 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2725 goto done;
2728 if (!string_to_sid(&sid, sidstr))
2729 goto done;
2731 if (!sid_check_is_in_our_sam(&sid)) {
2732 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2733 "in our domain\n"));
2734 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2735 goto done;
2738 sid_peek_rid(&sid, &rid);
2740 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2741 p_num_members)) {
2742 ret = NT_STATUS_NO_MEMORY;
2743 goto done;
2748 filter = talloc_asprintf(mem_ctx,
2749 "(&(objectClass=%s)"
2750 "(gidNumber=%s))",
2751 LDAP_OBJ_SAMBASAMACCOUNT,
2752 gidstr);
2754 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2755 LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2756 &result);
2758 if (rc != LDAP_SUCCESS)
2759 goto done;
2761 talloc_autofree_ldapmsg(mem_ctx, result);
2763 for (entry = ldap_first_entry(conn->ldap_struct, result);
2764 entry != NULL;
2765 entry = ldap_next_entry(conn->ldap_struct, entry))
2767 uint32_t rid;
2769 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2770 entry,
2771 get_global_sam_sid(),
2772 &rid)) {
2773 DEBUG(0, ("Severe DB error, %s can't miss the samba SID" "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2774 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2775 goto done;
2778 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2779 p_num_members)) {
2780 ret = NT_STATUS_NO_MEMORY;
2781 goto done;
2785 ret = NT_STATUS_OK;
2787 done:
2789 if (values)
2790 ldap_value_free(values);
2792 return ret;
2795 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2796 TALLOC_CTX *mem_ctx,
2797 struct samu *user,
2798 struct dom_sid **pp_sids,
2799 gid_t **pp_gids,
2800 uint32_t *p_num_groups)
2802 struct ldapsam_privates *ldap_state =
2803 (struct ldapsam_privates *)methods->private_data;
2804 struct smbldap_state *conn = ldap_state->smbldap_state;
2805 char *filter;
2806 const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2807 char *escape_name;
2808 int rc, count;
2809 LDAPMessage *result = NULL;
2810 LDAPMessage *entry;
2811 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2812 uint32_t num_sids;
2813 uint32_t num_gids;
2814 char *gidstr;
2815 gid_t primary_gid = -1;
2817 *pp_sids = NULL;
2818 num_sids = 0;
2820 if (pdb_get_username(user) == NULL) {
2821 return NT_STATUS_INVALID_PARAMETER;
2824 escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2825 if (escape_name == NULL)
2826 return NT_STATUS_NO_MEMORY;
2828 if (user->unix_pw) {
2829 primary_gid = user->unix_pw->pw_gid;
2830 } else {
2831 /* retrieve the users primary gid */
2832 filter = talloc_asprintf(mem_ctx,
2833 "(&(objectClass=%s)(uid=%s))",
2834 LDAP_OBJ_SAMBASAMACCOUNT,
2835 escape_name);
2836 if (filter == NULL) {
2837 ret = NT_STATUS_NO_MEMORY;
2838 goto done;
2841 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2842 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2844 if (rc != LDAP_SUCCESS)
2845 goto done;
2847 talloc_autofree_ldapmsg(mem_ctx, result);
2849 count = ldap_count_entries(priv2ld(ldap_state), result);
2851 switch (count) {
2852 case 0:
2853 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2854 ret = NT_STATUS_NO_SUCH_USER;
2855 goto done;
2856 case 1:
2857 entry = ldap_first_entry(priv2ld(ldap_state), result);
2859 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2860 if (!gidstr) {
2861 DEBUG (1, ("Unable to find the member's gid!\n"));
2862 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2863 goto done;
2865 primary_gid = strtoul(gidstr, NULL, 10);
2866 break;
2867 default:
2868 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2869 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2870 goto done;
2874 filter = talloc_asprintf(mem_ctx,
2875 "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2876 LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2877 if (filter == NULL) {
2878 ret = NT_STATUS_NO_MEMORY;
2879 goto done;
2882 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2883 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2885 if (rc != LDAP_SUCCESS)
2886 goto done;
2888 talloc_autofree_ldapmsg(mem_ctx, result);
2890 num_gids = 0;
2891 *pp_gids = NULL;
2893 num_sids = 0;
2894 *pp_sids = NULL;
2896 /* We need to add the primary group as the first gid/sid */
2898 if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2899 ret = NT_STATUS_NO_MEMORY;
2900 goto done;
2903 /* This sid will be replaced later */
2905 ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2906 &num_sids);
2907 if (!NT_STATUS_IS_OK(ret)) {
2908 goto done;
2911 for (entry = ldap_first_entry(conn->ldap_struct, result);
2912 entry != NULL;
2913 entry = ldap_next_entry(conn->ldap_struct, entry))
2915 fstring str;
2916 struct dom_sid sid;
2917 gid_t gid;
2918 char *end;
2920 if (!smbldap_get_single_attribute(conn->ldap_struct,
2921 entry, "sambaSID",
2922 str, sizeof(str)-1))
2923 continue;
2925 if (!string_to_sid(&sid, str))
2926 goto done;
2928 if (!smbldap_get_single_attribute(conn->ldap_struct,
2929 entry, "gidNumber",
2930 str, sizeof(str)-1))
2931 continue;
2933 gid = strtoul(str, &end, 10);
2935 if (PTR_DIFF(end, str) != strlen(str))
2936 goto done;
2938 if (gid == primary_gid) {
2939 sid_copy(&(*pp_sids)[0], &sid);
2940 } else {
2941 if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2942 &num_gids)) {
2943 ret = NT_STATUS_NO_MEMORY;
2944 goto done;
2946 ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2947 &num_sids);
2948 if (!NT_STATUS_IS_OK(ret)) {
2949 goto done;
2954 if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2955 DEBUG(3, ("primary group of [%s] not found\n",
2956 pdb_get_username(user)));
2957 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2958 goto done;
2961 *p_num_groups = num_sids;
2963 ret = NT_STATUS_OK;
2965 done:
2967 TALLOC_FREE(escape_name);
2968 return ret;
2971 /**********************************************************************
2972 * Augment a posixGroup object with a sambaGroupMapping domgroup
2973 *********************************************************************/
2975 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2976 struct ldapsam_privates *ldap_state,
2977 GROUP_MAP *map)
2979 const char *filter, *dn;
2980 LDAPMessage *msg, *entry;
2981 LDAPMod **mods;
2982 int rc;
2984 filter = talloc_asprintf(mem_ctx,
2985 "(&(objectClass=%s)(gidNumber=%u))",
2986 LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2987 if (filter == NULL) {
2988 return NT_STATUS_NO_MEMORY;
2991 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2992 get_attr_list(mem_ctx, groupmap_attr_list),
2993 &msg);
2994 talloc_autofree_ldapmsg(mem_ctx, msg);
2996 if ((rc != LDAP_SUCCESS) ||
2997 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2998 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2999 return NT_STATUS_NO_SUCH_GROUP;
3002 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3003 if (dn == NULL) {
3004 return NT_STATUS_NO_MEMORY;
3007 mods = NULL;
3008 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3009 LDAP_OBJ_GROUPMAP);
3010 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3011 sid_string_talloc(mem_ctx, &map->sid));
3012 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3013 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3014 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3015 map->nt_name);
3016 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3017 map->comment);
3018 talloc_autofree_ldapmod(mem_ctx, mods);
3020 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3021 if (rc != LDAP_SUCCESS) {
3022 return NT_STATUS_ACCESS_DENIED;
3025 return NT_STATUS_OK;
3028 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3029 GROUP_MAP *map)
3031 struct ldapsam_privates *ldap_state =
3032 (struct ldapsam_privates *)methods->private_data;
3033 LDAPMessage *msg = NULL;
3034 LDAPMod **mods = NULL;
3035 const char *attrs[] = { NULL };
3036 char *filter;
3038 char *dn;
3039 TALLOC_CTX *mem_ctx;
3040 NTSTATUS result;
3042 struct dom_sid sid;
3044 int rc;
3046 mem_ctx = talloc_new(NULL);
3047 if (mem_ctx == NULL) {
3048 DEBUG(0, ("talloc_new failed\n"));
3049 return NT_STATUS_NO_MEMORY;
3052 filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3053 sid_string_talloc(mem_ctx, &map->sid));
3054 if (filter == NULL) {
3055 result = NT_STATUS_NO_MEMORY;
3056 goto done;
3059 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3060 LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3061 talloc_autofree_ldapmsg(mem_ctx, msg);
3063 if ((rc == LDAP_SUCCESS) &&
3064 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3066 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3067 "group mapping entry\n", sid_string_dbg(&map->sid)));
3068 result = NT_STATUS_GROUP_EXISTS;
3069 goto done;
3072 switch (map->sid_name_use) {
3074 case SID_NAME_DOM_GRP:
3075 /* To map a domain group we need to have a posix group
3076 to attach to. */
3077 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3078 goto done;
3079 break;
3081 case SID_NAME_ALIAS:
3082 if (!sid_check_is_in_our_sam(&map->sid)
3083 && !sid_check_is_in_builtin(&map->sid) )
3085 DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3086 sid_string_dbg(&map->sid)));
3087 result = NT_STATUS_INVALID_PARAMETER;
3088 goto done;
3090 break;
3092 default:
3093 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3094 sid_type_lookup(map->sid_name_use)));
3095 result = NT_STATUS_INVALID_PARAMETER;
3096 goto done;
3099 /* Domain groups have been mapped in a separate routine, we have to
3100 * create an alias now */
3102 if (map->gid == -1) {
3103 DEBUG(10, ("Refusing to map gid==-1\n"));
3104 result = NT_STATUS_INVALID_PARAMETER;
3105 goto done;
3108 if (pdb_gid_to_sid(map->gid, &sid)) {
3109 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3110 "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3111 result = NT_STATUS_GROUP_EXISTS;
3112 goto done;
3115 /* Ok, enough checks done. It's still racy to go ahead now, but that's
3116 * the best we can get out of LDAP. */
3118 dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3119 sid_string_talloc(mem_ctx, &map->sid),
3120 lp_ldap_group_suffix(talloc_tos()));
3121 if (dn == NULL) {
3122 result = NT_STATUS_NO_MEMORY;
3123 goto done;
3126 mods = NULL;
3128 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3129 LDAP_OBJ_SID_ENTRY);
3130 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3131 LDAP_OBJ_GROUPMAP);
3132 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3133 sid_string_talloc(mem_ctx, &map->sid));
3134 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3135 talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3136 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3137 map->nt_name);
3138 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3139 map->comment);
3140 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3141 talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3142 talloc_autofree_ldapmod(mem_ctx, mods);
3144 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3146 result = (rc == LDAP_SUCCESS) ?
3147 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3149 done:
3150 TALLOC_FREE(mem_ctx);
3151 return result;
3154 /**********************************************************************
3155 * Update a group mapping entry. We're quite strict about what can be changed:
3156 * Only the description and displayname may be changed. It simply does not
3157 * make any sense to change the SID, gid or the type in a mapping.
3158 *********************************************************************/
3160 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3161 GROUP_MAP *map)
3163 struct ldapsam_privates *ldap_state =
3164 (struct ldapsam_privates *)methods->private_data;
3165 int rc;
3166 const char *filter, *dn;
3167 LDAPMessage *msg = NULL;
3168 LDAPMessage *entry = NULL;
3169 LDAPMod **mods = NULL;
3170 TALLOC_CTX *mem_ctx;
3171 NTSTATUS result;
3173 mem_ctx = talloc_new(NULL);
3174 if (mem_ctx == NULL) {
3175 DEBUG(0, ("talloc_new failed\n"));
3176 return NT_STATUS_NO_MEMORY;
3179 /* Make 100% sure that sid, gid and type are not changed by looking up
3180 * exactly the values we're given in LDAP. */
3182 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3183 "(sambaSid=%s)(gidNumber=%u)"
3184 "(sambaGroupType=%d))",
3185 LDAP_OBJ_GROUPMAP,
3186 sid_string_talloc(mem_ctx, &map->sid),
3187 (unsigned int)map->gid, map->sid_name_use);
3188 if (filter == NULL) {
3189 result = NT_STATUS_NO_MEMORY;
3190 goto done;
3193 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3194 get_attr_list(mem_ctx, groupmap_attr_list),
3195 &msg);
3196 talloc_autofree_ldapmsg(mem_ctx, msg);
3198 if ((rc != LDAP_SUCCESS) ||
3199 (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3200 ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3201 result = NT_STATUS_NO_SUCH_GROUP;
3202 goto done;
3205 dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3207 if (dn == NULL) {
3208 result = NT_STATUS_NO_MEMORY;
3209 goto done;
3212 mods = NULL;
3213 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3214 map->nt_name);
3215 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3216 map->comment);
3217 talloc_autofree_ldapmod(mem_ctx, mods);
3219 if (mods == NULL) {
3220 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3221 "nothing to do\n"));
3222 result = NT_STATUS_OK;
3223 goto done;
3226 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3228 if (rc != LDAP_SUCCESS) {
3229 result = NT_STATUS_ACCESS_DENIED;
3230 goto done;
3233 DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3234 "group %lu in LDAP\n", (unsigned long)map->gid));
3236 result = NT_STATUS_OK;
3238 done:
3239 TALLOC_FREE(mem_ctx);
3240 return result;
3243 /**********************************************************************
3244 *********************************************************************/
3246 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3247 struct dom_sid sid)
3249 struct ldapsam_privates *priv =
3250 (struct ldapsam_privates *)methods->private_data;
3251 LDAPMessage *msg, *entry;
3252 int rc;
3253 NTSTATUS result;
3254 TALLOC_CTX *mem_ctx;
3255 char *filter;
3257 mem_ctx = talloc_new(NULL);
3258 if (mem_ctx == NULL) {
3259 DEBUG(0, ("talloc_new failed\n"));
3260 return NT_STATUS_NO_MEMORY;
3263 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3264 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3265 sid_string_talloc(mem_ctx, &sid));
3266 if (filter == NULL) {
3267 result = NT_STATUS_NO_MEMORY;
3268 goto done;
3270 rc = smbldap_search_suffix(priv->smbldap_state, filter,
3271 get_attr_list(mem_ctx, groupmap_attr_list),
3272 &msg);
3273 talloc_autofree_ldapmsg(mem_ctx, msg);
3275 if ((rc != LDAP_SUCCESS) ||
3276 (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3277 ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3278 result = NT_STATUS_NO_SUCH_GROUP;
3279 goto done;
3282 rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3283 get_attr_list(mem_ctx,
3284 groupmap_attr_list_to_delete));
3286 if ((rc == LDAP_NAMING_VIOLATION) ||
3287 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3288 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3289 const char *attrs[] = { "sambaGroupType", "description",
3290 "displayName", "sambaSIDList",
3291 NULL };
3293 /* Second try. Don't delete the sambaSID attribute, this is
3294 for "old" entries that are tacked on a winbind
3295 sambaIdmapEntry. */
3297 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3298 LDAP_OBJ_GROUPMAP, attrs);
3301 if ((rc == LDAP_NAMING_VIOLATION) ||
3302 (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3303 (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3304 const char *attrs[] = { "sambaGroupType", "description",
3305 "displayName", "sambaSIDList",
3306 "gidNumber", NULL };
3308 /* Third try. This is a post-3.0.21 alias (containing only
3309 * sambaSidEntry and sambaGroupMapping classes), we also have
3310 * to delete the gidNumber attribute, only the sambaSidEntry
3311 * remains */
3313 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3314 LDAP_OBJ_GROUPMAP, attrs);
3317 result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3319 done:
3320 TALLOC_FREE(mem_ctx);
3321 return result;
3324 /**********************************************************************
3325 *********************************************************************/
3327 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3328 bool update)
3330 struct ldapsam_privates *ldap_state =
3331 (struct ldapsam_privates *)my_methods->private_data;
3332 char *filter = NULL;
3333 int rc;
3334 const char **attr_list;
3336 filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3337 if (!filter) {
3338 return NT_STATUS_NO_MEMORY;
3340 attr_list = get_attr_list( NULL, groupmap_attr_list );
3341 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3342 LDAP_SCOPE_SUBTREE, filter,
3343 attr_list, 0, &ldap_state->result);
3344 TALLOC_FREE(attr_list);
3346 if (rc != LDAP_SUCCESS) {
3347 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3348 ldap_err2string(rc)));
3349 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3350 lp_ldap_suffix(talloc_tos()), filter));
3351 ldap_msgfree(ldap_state->result);
3352 ldap_state->result = NULL;
3353 TALLOC_FREE(filter);
3354 return NT_STATUS_UNSUCCESSFUL;
3357 TALLOC_FREE(filter);
3359 DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3360 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3361 ldap_state->result)));
3363 ldap_state->entry =
3364 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3365 ldap_state->result);
3366 ldap_state->index = 0;
3368 return NT_STATUS_OK;
3371 /**********************************************************************
3372 *********************************************************************/
3374 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3376 ldapsam_endsampwent(my_methods);
3379 /**********************************************************************
3380 *********************************************************************/
3382 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3383 GROUP_MAP *map)
3385 NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3386 struct ldapsam_privates *ldap_state =
3387 (struct ldapsam_privates *)my_methods->private_data;
3388 bool bret = False;
3390 while (!bret) {
3391 if (!ldap_state->entry)
3392 return ret;
3394 ldap_state->index++;
3395 bret = init_group_from_ldap(ldap_state, map,
3396 ldap_state->entry);
3398 ldap_state->entry =
3399 ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3400 ldap_state->entry);
3403 return NT_STATUS_OK;
3406 /**********************************************************************
3407 *********************************************************************/
3409 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3410 const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3411 GROUP_MAP ***pp_rmap,
3412 size_t *p_num_entries,
3413 bool unix_only)
3415 GROUP_MAP *map = NULL;
3416 size_t entries = 0;
3418 *p_num_entries = 0;
3419 *pp_rmap = NULL;
3421 if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3422 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3423 "passdb\n"));
3424 return NT_STATUS_ACCESS_DENIED;
3427 while (true) {
3429 map = talloc_zero(NULL, GROUP_MAP);
3430 if (!map) {
3431 return NT_STATUS_NO_MEMORY;
3434 if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
3435 TALLOC_FREE(map);
3436 break;
3439 if (sid_name_use != SID_NAME_UNKNOWN &&
3440 sid_name_use != map->sid_name_use) {
3441 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3442 "not of the requested type\n",
3443 map->nt_name));
3444 continue;
3446 if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
3447 DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3448 "non mapped\n", map->nt_name));
3449 continue;
3452 *pp_rmap = talloc_realloc(NULL, *pp_rmap,
3453 GROUP_MAP *, entries + 1);
3454 if (!(*pp_rmap)) {
3455 DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3456 "enlarge group map!\n"));
3457 return NT_STATUS_UNSUCCESSFUL;
3460 (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
3462 entries += 1;
3465 ldapsam_endsamgrent(methods);
3467 *p_num_entries = entries;
3469 return NT_STATUS_OK;
3472 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3473 const struct dom_sid *alias,
3474 const struct dom_sid *member,
3475 int modop)
3477 struct ldapsam_privates *ldap_state =
3478 (struct ldapsam_privates *)methods->private_data;
3479 char *dn = NULL;
3480 LDAPMessage *result = NULL;
3481 LDAPMessage *entry = NULL;
3482 int count;
3483 LDAPMod **mods = NULL;
3484 int rc;
3485 enum lsa_SidType type = SID_NAME_USE_NONE;
3486 fstring tmp;
3488 char *filter = NULL;
3490 if (sid_check_is_in_builtin(alias)) {
3491 type = SID_NAME_ALIAS;
3494 if (sid_check_is_in_our_sam(alias)) {
3495 type = SID_NAME_ALIAS;
3498 if (type == SID_NAME_USE_NONE) {
3499 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3500 sid_string_dbg(alias)));
3501 return NT_STATUS_NO_SUCH_ALIAS;
3504 if (asprintf(&filter,
3505 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3506 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3507 type) < 0) {
3508 return NT_STATUS_NO_MEMORY;
3511 if (ldapsam_search_one_group(ldap_state, filter,
3512 &result) != LDAP_SUCCESS) {
3513 SAFE_FREE(filter);
3514 return NT_STATUS_NO_SUCH_ALIAS;
3517 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3518 result);
3520 if (count < 1) {
3521 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3522 ldap_msgfree(result);
3523 SAFE_FREE(filter);
3524 return NT_STATUS_NO_SUCH_ALIAS;
3527 if (count > 1) {
3528 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3529 "filter %s: count=%d\n", filter, count));
3530 ldap_msgfree(result);
3531 SAFE_FREE(filter);
3532 return NT_STATUS_NO_SUCH_ALIAS;
3535 SAFE_FREE(filter);
3537 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3538 result);
3540 if (!entry) {
3541 ldap_msgfree(result);
3542 return NT_STATUS_UNSUCCESSFUL;
3545 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3546 if (!dn) {
3547 ldap_msgfree(result);
3548 return NT_STATUS_UNSUCCESSFUL;
3551 smbldap_set_mod(&mods, modop,
3552 get_attr_key2string(groupmap_attr_list,
3553 LDAP_ATTR_SID_LIST),
3554 sid_to_fstring(tmp, member));
3556 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3558 ldap_mods_free(mods, True);
3559 ldap_msgfree(result);
3560 TALLOC_FREE(dn);
3562 if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3563 return NT_STATUS_MEMBER_IN_ALIAS;
3566 if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3567 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3570 if (rc != LDAP_SUCCESS) {
3571 return NT_STATUS_UNSUCCESSFUL;
3574 return NT_STATUS_OK;
3577 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3578 const struct dom_sid *alias,
3579 const struct dom_sid *member)
3581 return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3584 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3585 const struct dom_sid *alias,
3586 const struct dom_sid *member)
3588 return ldapsam_modify_aliasmem(methods, alias, member,
3589 LDAP_MOD_DELETE);
3592 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3593 const struct dom_sid *alias,
3594 TALLOC_CTX *mem_ctx,
3595 struct dom_sid **pp_members,
3596 size_t *p_num_members)
3598 struct ldapsam_privates *ldap_state =
3599 (struct ldapsam_privates *)methods->private_data;
3600 LDAPMessage *result = NULL;
3601 LDAPMessage *entry = NULL;
3602 int count;
3603 char **values = NULL;
3604 int i;
3605 char *filter = NULL;
3606 uint32_t num_members = 0;
3607 enum lsa_SidType type = SID_NAME_USE_NONE;
3608 fstring tmp;
3610 *pp_members = NULL;
3611 *p_num_members = 0;
3613 if (sid_check_is_in_builtin(alias)) {
3614 type = SID_NAME_ALIAS;
3617 if (sid_check_is_in_our_sam(alias)) {
3618 type = SID_NAME_ALIAS;
3621 if (type == SID_NAME_USE_NONE) {
3622 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3623 sid_string_dbg(alias)));
3624 return NT_STATUS_NO_SUCH_ALIAS;
3627 if (asprintf(&filter,
3628 "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3629 LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3630 type) < 0) {
3631 return NT_STATUS_NO_MEMORY;
3634 if (ldapsam_search_one_group(ldap_state, filter,
3635 &result) != LDAP_SUCCESS) {
3636 SAFE_FREE(filter);
3637 return NT_STATUS_NO_SUCH_ALIAS;
3640 count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3641 result);
3643 if (count < 1) {
3644 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3645 ldap_msgfree(result);
3646 SAFE_FREE(filter);
3647 return NT_STATUS_NO_SUCH_ALIAS;
3650 if (count > 1) {
3651 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3652 "filter %s: count=%d\n", filter, count));
3653 ldap_msgfree(result);
3654 SAFE_FREE(filter);
3655 return NT_STATUS_NO_SUCH_ALIAS;
3658 SAFE_FREE(filter);
3660 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3661 result);
3663 if (!entry) {
3664 ldap_msgfree(result);
3665 return NT_STATUS_UNSUCCESSFUL;
3668 values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3669 entry,
3670 get_attr_key2string(groupmap_attr_list,
3671 LDAP_ATTR_SID_LIST));
3673 if (values == NULL) {
3674 ldap_msgfree(result);
3675 return NT_STATUS_OK;
3678 count = ldap_count_values(values);
3680 for (i=0; i<count; i++) {
3681 struct dom_sid member;
3682 NTSTATUS status;
3684 if (!string_to_sid(&member, values[i]))
3685 continue;
3687 status = add_sid_to_array(mem_ctx, &member, pp_members,
3688 &num_members);
3689 if (!NT_STATUS_IS_OK(status)) {
3690 ldap_value_free(values);
3691 ldap_msgfree(result);
3692 return status;
3696 *p_num_members = num_members;
3697 ldap_value_free(values);
3698 ldap_msgfree(result);
3700 return NT_STATUS_OK;
3703 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3704 TALLOC_CTX *mem_ctx,
3705 const struct dom_sid *domain_sid,
3706 const struct dom_sid *members,
3707 size_t num_members,
3708 uint32_t **pp_alias_rids,
3709 size_t *p_num_alias_rids)
3711 struct ldapsam_privates *ldap_state =
3712 (struct ldapsam_privates *)methods->private_data;
3713 LDAP *ldap_struct;
3715 const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3717 LDAPMessage *result = NULL;
3718 LDAPMessage *entry = NULL;
3719 int i;
3720 int rc;
3721 char *filter;
3722 enum lsa_SidType type = SID_NAME_USE_NONE;
3723 bool is_builtin = false;
3724 bool sid_added = false;
3726 *pp_alias_rids = NULL;
3727 *p_num_alias_rids = 0;
3729 if (sid_check_is_builtin(domain_sid)) {
3730 is_builtin = true;
3731 type = SID_NAME_ALIAS;
3734 if (sid_check_is_our_sam(domain_sid)) {
3735 type = SID_NAME_ALIAS;
3738 if (type == SID_NAME_USE_NONE) {
3739 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3740 sid_string_dbg(domain_sid)));
3741 return NT_STATUS_UNSUCCESSFUL;
3744 if (num_members == 0) {
3745 return NT_STATUS_OK;
3748 filter = talloc_asprintf(mem_ctx,
3749 "(&(objectclass=%s)(sambaGroupType=%d)(|",
3750 LDAP_OBJ_GROUPMAP, type);
3752 for (i=0; i<num_members; i++)
3753 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3754 filter,
3755 sid_string_talloc(mem_ctx,
3756 &members[i]));
3758 filter = talloc_asprintf(mem_ctx, "%s))", filter);
3760 if (filter == NULL) {
3761 return NT_STATUS_NO_MEMORY;
3764 if (is_builtin &&
3765 ldap_state->search_cache.filter &&
3766 strcmp(ldap_state->search_cache.filter, filter) == 0) {
3767 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3768 result = ldap_state->search_cache.result;
3769 ldap_state->search_cache.result = NULL;
3770 } else {
3771 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3772 LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3773 if (rc != LDAP_SUCCESS) {
3774 return NT_STATUS_UNSUCCESSFUL;
3776 talloc_autofree_ldapmsg(filter, result);
3779 ldap_struct = ldap_state->smbldap_state->ldap_struct;
3781 for (entry = ldap_first_entry(ldap_struct, result);
3782 entry != NULL;
3783 entry = ldap_next_entry(ldap_struct, entry))
3785 fstring sid_str;
3786 struct dom_sid sid;
3787 uint32_t rid;
3789 if (!smbldap_get_single_attribute(ldap_struct, entry,
3790 LDAP_ATTRIBUTE_SID,
3791 sid_str,
3792 sizeof(sid_str)-1))
3793 continue;
3795 if (!string_to_sid(&sid, sid_str))
3796 continue;
3798 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3799 continue;
3801 sid_added = true;
3803 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3804 p_num_alias_rids)) {
3805 return NT_STATUS_NO_MEMORY;
3809 if (!is_builtin && !sid_added) {
3810 TALLOC_FREE(ldap_state->search_cache.filter);
3812 * Note: result is a talloc child of filter because of the
3813 * talloc_autofree_ldapmsg() usage
3815 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3816 ldap_state->search_cache.result = result;
3819 return NT_STATUS_OK;
3822 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3823 enum pdb_policy_type type,
3824 uint32_t value)
3826 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3827 int rc;
3828 LDAPMod **mods = NULL;
3829 fstring value_string;
3830 const char *policy_attr = NULL;
3832 struct ldapsam_privates *ldap_state =
3833 (struct ldapsam_privates *)methods->private_data;
3835 DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3837 if (!ldap_state->domain_dn) {
3838 return NT_STATUS_INVALID_PARAMETER;
3841 policy_attr = get_account_policy_attr(type);
3842 if (policy_attr == NULL) {
3843 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3844 "policy\n"));
3845 return ntstatus;
3848 slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3850 smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3852 rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3853 mods);
3855 ldap_mods_free(mods, True);
3857 if (rc != LDAP_SUCCESS) {
3858 return ntstatus;
3861 if (!cache_account_policy_set(type, value)) {
3862 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3863 "update local tdb cache\n"));
3864 return ntstatus;
3867 return NT_STATUS_OK;
3870 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3871 enum pdb_policy_type type,
3872 uint32_t value)
3874 return ldapsam_set_account_policy_in_ldap(methods, type,
3875 value);
3878 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3879 enum pdb_policy_type type,
3880 uint32_t *value)
3882 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3883 LDAPMessage *result = NULL;
3884 LDAPMessage *entry = NULL;
3885 int count;
3886 int rc;
3887 char **vals = NULL;
3888 char *filter;
3889 const char *policy_attr = NULL;
3891 struct ldapsam_privates *ldap_state =
3892 (struct ldapsam_privates *)methods->private_data;
3894 const char *attrs[2];
3896 DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3898 if (!ldap_state->domain_dn) {
3899 return NT_STATUS_INVALID_PARAMETER;
3902 policy_attr = get_account_policy_attr(type);
3903 if (!policy_attr) {
3904 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3905 "policy index: %d\n", type));
3906 return ntstatus;
3909 attrs[0] = policy_attr;
3910 attrs[1] = NULL;
3912 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3913 if (filter == NULL) {
3914 return NT_STATUS_NO_MEMORY;
3916 rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3917 LDAP_SCOPE_BASE, filter, attrs, 0,
3918 &result);
3919 TALLOC_FREE(filter);
3920 if (rc != LDAP_SUCCESS) {
3921 return ntstatus;
3924 count = ldap_count_entries(priv2ld(ldap_state), result);
3925 if (count < 1) {
3926 goto out;
3929 entry = ldap_first_entry(priv2ld(ldap_state), result);
3930 if (entry == NULL) {
3931 goto out;
3934 vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3935 if (vals == NULL) {
3936 goto out;
3939 *value = (uint32_t)atol(vals[0]);
3941 ntstatus = NT_STATUS_OK;
3943 out:
3944 if (vals)
3945 ldap_value_free(vals);
3946 ldap_msgfree(result);
3948 return ntstatus;
3951 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache
3953 - if user hasn't decided to use account policies inside LDAP just reuse the
3954 old tdb values
3956 - if there is a valid cache entry, return that
3957 - if there is an LDAP entry, update cache and return
3958 - otherwise set to default, update cache and return
3960 Guenther
3962 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3963 enum pdb_policy_type type,
3964 uint32_t *value)
3966 NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3968 if (cache_account_policy_get(type, value)) {
3969 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3970 "cache\n"));
3971 return NT_STATUS_OK;
3974 ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3975 value);
3976 if (NT_STATUS_IS_OK(ntstatus)) {
3977 goto update_cache;
3980 DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3981 "ldap\n"));
3983 #if 0
3984 /* should we automagically migrate old tdb value here ? */
3985 if (account_policy_get(type, value))
3986 goto update_ldap;
3988 DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3989 "default\n", type));
3990 #endif
3992 if (!account_policy_get_default(type, value)) {
3993 return ntstatus;
3996 /* update_ldap: */
3998 ntstatus = ldapsam_set_account_policy(methods, type, *value);
3999 if (!NT_STATUS_IS_OK(ntstatus)) {
4000 return ntstatus;
4003 update_cache:
4005 if (!cache_account_policy_set(type, *value)) {
4006 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
4007 "tdb as a cache\n"));
4008 return NT_STATUS_UNSUCCESSFUL;
4011 return NT_STATUS_OK;
4014 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
4015 const struct dom_sid *domain_sid,
4016 int num_rids,
4017 uint32_t *rids,
4018 const char **names,
4019 enum lsa_SidType *attrs)
4021 struct ldapsam_privates *ldap_state =
4022 (struct ldapsam_privates *)methods->private_data;
4023 LDAPMessage *msg = NULL;
4024 LDAPMessage *entry;
4025 char *allsids = NULL;
4026 int i, rc, num_mapped;
4027 NTSTATUS result = NT_STATUS_NO_MEMORY;
4028 TALLOC_CTX *mem_ctx;
4029 LDAP *ld;
4030 bool is_builtin;
4032 mem_ctx = talloc_new(NULL);
4033 if (mem_ctx == NULL) {
4034 DEBUG(0, ("talloc_new failed\n"));
4035 goto done;
4038 if (!sid_check_is_builtin(domain_sid) &&
4039 !sid_check_is_our_sam(domain_sid)) {
4040 result = NT_STATUS_INVALID_PARAMETER;
4041 goto done;
4044 if (num_rids == 0) {
4045 result = NT_STATUS_NONE_MAPPED;
4046 goto done;
4049 for (i=0; i<num_rids; i++)
4050 attrs[i] = SID_NAME_UNKNOWN;
4052 allsids = talloc_strdup(mem_ctx, "");
4053 if (allsids == NULL) {
4054 goto done;
4057 for (i=0; i<num_rids; i++) {
4058 struct dom_sid sid;
4059 sid_compose(&sid, domain_sid, rids[i]);
4060 allsids = talloc_asprintf_append_buffer(
4061 allsids, "(sambaSid=%s)",
4062 sid_string_talloc(mem_ctx, &sid));
4063 if (allsids == NULL) {
4064 goto done;
4068 /* First look for users */
4071 char *filter;
4072 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4074 filter = talloc_asprintf(
4075 mem_ctx, ("(&(objectClass=%s)(|%s))"),
4076 LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4078 if (filter == NULL) {
4079 goto done;
4082 rc = smbldap_search(ldap_state->smbldap_state,
4083 lp_ldap_user_suffix(talloc_tos()),
4084 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4085 &msg);
4086 talloc_autofree_ldapmsg(mem_ctx, msg);
4089 if (rc != LDAP_SUCCESS)
4090 goto done;
4092 ld = ldap_state->smbldap_state->ldap_struct;
4093 num_mapped = 0;
4095 for (entry = ldap_first_entry(ld, msg);
4096 entry != NULL;
4097 entry = ldap_next_entry(ld, entry)) {
4098 uint32_t rid;
4099 int rid_index;
4100 const char *name;
4102 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4103 &rid)) {
4104 DEBUG(2, ("Could not find sid from ldap entry\n"));
4105 continue;
4108 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4109 names);
4110 if (name == NULL) {
4111 DEBUG(2, ("Could not retrieve uid attribute\n"));
4112 continue;
4115 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4116 if (rid == rids[rid_index])
4117 break;
4120 if (rid_index == num_rids) {
4121 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4122 continue;
4125 attrs[rid_index] = SID_NAME_USER;
4126 names[rid_index] = name;
4127 num_mapped += 1;
4130 if (num_mapped == num_rids) {
4131 /* No need to look for groups anymore -- we're done */
4132 result = NT_STATUS_OK;
4133 goto done;
4136 /* Same game for groups */
4139 char *filter;
4140 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4141 "sambaGroupType", NULL };
4143 filter = talloc_asprintf(
4144 mem_ctx, "(&(objectClass=%s)(|%s))",
4145 LDAP_OBJ_GROUPMAP, allsids);
4146 if (filter == NULL) {
4147 goto done;
4150 rc = smbldap_search(ldap_state->smbldap_state,
4151 lp_ldap_suffix(talloc_tos()),
4152 LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4153 &msg);
4154 talloc_autofree_ldapmsg(mem_ctx, msg);
4157 if (rc != LDAP_SUCCESS)
4158 goto done;
4160 /* ldap_struct might have changed due to a reconnect */
4162 ld = ldap_state->smbldap_state->ldap_struct;
4164 /* For consistency checks, we already checked we're only domain or builtin */
4166 is_builtin = sid_check_is_builtin(domain_sid);
4168 for (entry = ldap_first_entry(ld, msg);
4169 entry != NULL;
4170 entry = ldap_next_entry(ld, entry))
4172 uint32_t rid;
4173 int rid_index;
4174 const char *attr;
4175 enum lsa_SidType type;
4176 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4178 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4179 mem_ctx);
4180 if (attr == NULL) {
4181 DEBUG(2, ("Could not extract type from ldap entry %s\n",
4182 dn));
4183 continue;
4186 type = (enum lsa_SidType)atol(attr);
4188 /* Consistency checks */
4189 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4190 (!is_builtin && ((type != SID_NAME_ALIAS) &&
4191 (type != SID_NAME_DOM_GRP)))) {
4192 DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4195 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4196 &rid)) {
4197 DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4198 continue;
4201 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4203 if (attr == NULL) {
4204 DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4205 dn));
4206 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4209 if (attr == NULL) {
4210 DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4211 dn));
4212 continue;
4215 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4216 if (rid == rids[rid_index])
4217 break;
4220 if (rid_index == num_rids) {
4221 DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4222 continue;
4225 attrs[rid_index] = type;
4226 names[rid_index] = attr;
4227 num_mapped += 1;
4230 result = NT_STATUS_NONE_MAPPED;
4232 if (num_mapped > 0)
4233 result = (num_mapped == num_rids) ?
4234 NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4235 done:
4236 TALLOC_FREE(mem_ctx);
4237 return result;
4240 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4242 char *filter = NULL;
4243 char *escaped = NULL;
4244 char *result = NULL;
4246 if (asprintf(&filter, "(&%s(objectclass=%s))",
4247 "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4248 goto done;
4251 escaped = escape_ldap_string(talloc_tos(), username);
4252 if (escaped == NULL) goto done;
4254 result = talloc_string_sub(mem_ctx, filter, "%u", username);
4256 done:
4257 SAFE_FREE(filter);
4258 TALLOC_FREE(escaped);
4260 return result;
4263 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4265 int i, num = 0;
4266 va_list ap;
4267 const char **result;
4269 va_start(ap, mem_ctx);
4270 while (va_arg(ap, const char *) != NULL)
4271 num += 1;
4272 va_end(ap);
4274 if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4275 return NULL;
4278 va_start(ap, mem_ctx);
4279 for (i=0; i<num; i++) {
4280 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4281 if (result[i] == NULL) {
4282 talloc_free(result);
4283 va_end(ap);
4284 return NULL;
4287 va_end(ap);
4289 result[num] = NULL;
4290 return result;
4293 struct ldap_search_state {
4294 struct smbldap_state *connection;
4296 uint32_t acct_flags;
4297 uint16_t group_type;
4299 const char *base;
4300 int scope;
4301 const char *filter;
4302 const char **attrs;
4303 int attrsonly;
4304 void *pagedresults_cookie;
4306 LDAPMessage *entries, *current_entry;
4307 bool (*ldap2displayentry)(struct ldap_search_state *state,
4308 TALLOC_CTX *mem_ctx,
4309 LDAP *ld, LDAPMessage *entry,
4310 struct samr_displayentry *result);
4313 static bool ldapsam_search_firstpage(struct pdb_search *search)
4315 struct ldap_search_state *state =
4316 (struct ldap_search_state *)search->private_data;
4317 LDAP *ld;
4318 int rc = LDAP_OPERATIONS_ERROR;
4320 state->entries = NULL;
4322 if (state->connection->paged_results) {
4323 rc = smbldap_search_paged(state->connection, state->base,
4324 state->scope, state->filter,
4325 state->attrs, state->attrsonly,
4326 lp_ldap_page_size(), &state->entries,
4327 &state->pagedresults_cookie);
4330 if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4332 if (state->entries != NULL) {
4333 /* Left over from unsuccessful paged attempt */
4334 ldap_msgfree(state->entries);
4335 state->entries = NULL;
4338 rc = smbldap_search(state->connection, state->base,
4339 state->scope, state->filter, state->attrs,
4340 state->attrsonly, &state->entries);
4342 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4343 return False;
4345 /* Ok, the server was lying. It told us it could do paged
4346 * searches when it could not. */
4347 state->connection->paged_results = False;
4350 ld = state->connection->ldap_struct;
4351 if ( ld == NULL) {
4352 DEBUG(5, ("Don't have an LDAP connection right after a "
4353 "search\n"));
4354 return False;
4356 state->current_entry = ldap_first_entry(ld, state->entries);
4358 return True;
4361 static bool ldapsam_search_nextpage(struct pdb_search *search)
4363 struct ldap_search_state *state =
4364 (struct ldap_search_state *)search->private_data;
4365 int rc;
4367 if (!state->connection->paged_results) {
4368 /* There is no next page when there are no paged results */
4369 return False;
4372 rc = smbldap_search_paged(state->connection, state->base,
4373 state->scope, state->filter, state->attrs,
4374 state->attrsonly, lp_ldap_page_size(),
4375 &state->entries,
4376 &state->pagedresults_cookie);
4378 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4379 return False;
4381 state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4383 if (state->current_entry == NULL) {
4384 ldap_msgfree(state->entries);
4385 state->entries = NULL;
4386 return false;
4389 return True;
4392 static bool ldapsam_search_next_entry(struct pdb_search *search,
4393 struct samr_displayentry *entry)
4395 struct ldap_search_state *state =
4396 (struct ldap_search_state *)search->private_data;
4397 bool result;
4399 retry:
4400 if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4401 return False;
4403 if ((state->entries == NULL) &&
4404 !ldapsam_search_nextpage(search))
4405 return False;
4407 if (state->current_entry == NULL) {
4408 return false;
4411 result = state->ldap2displayentry(state, search,
4412 state->connection->ldap_struct,
4413 state->current_entry, entry);
4415 if (!result) {
4416 char *dn;
4417 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4418 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4419 if (dn != NULL) ldap_memfree(dn);
4422 state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4424 if (state->current_entry == NULL) {
4425 ldap_msgfree(state->entries);
4426 state->entries = NULL;
4429 if (!result) goto retry;
4431 return True;
4434 static void ldapsam_search_end(struct pdb_search *search)
4436 struct ldap_search_state *state =
4437 (struct ldap_search_state *)search->private_data;
4438 int rc;
4440 if (state->pagedresults_cookie == NULL)
4441 return;
4443 if (state->entries != NULL)
4444 ldap_msgfree(state->entries);
4446 state->entries = NULL;
4447 state->current_entry = NULL;
4449 if (!state->connection->paged_results)
4450 return;
4452 /* Tell the LDAP server we're not interested in the rest anymore. */
4454 rc = smbldap_search_paged(state->connection, state->base, state->scope,
4455 state->filter, state->attrs,
4456 state->attrsonly, 0, &state->entries,
4457 &state->pagedresults_cookie);
4459 if (rc != LDAP_SUCCESS)
4460 DEBUG(5, ("Could not end search properly\n"));
4462 return;
4465 static bool ldapuser2displayentry(struct ldap_search_state *state,
4466 TALLOC_CTX *mem_ctx,
4467 LDAP *ld, LDAPMessage *entry,
4468 struct samr_displayentry *result)
4470 char **vals;
4471 size_t converted_size;
4472 struct dom_sid sid;
4473 uint32_t acct_flags;
4475 vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4476 if ((vals == NULL) || (vals[0] == NULL)) {
4477 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4478 return False;
4480 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4481 ldap_value_free(vals);
4483 if ((state->acct_flags != 0) &&
4484 ((state->acct_flags & acct_flags) == 0))
4485 return False;
4487 result->acct_flags = acct_flags;
4488 result->account_name = "";
4489 result->fullname = "";
4490 result->description = "";
4492 vals = ldap_get_values(ld, entry, "uid");
4493 if ((vals == NULL) || (vals[0] == NULL)) {
4494 DEBUG(5, ("\"uid\" not found\n"));
4495 return False;
4497 if (!pull_utf8_talloc(mem_ctx,
4498 discard_const_p(char *, &result->account_name),
4499 vals[0], &converted_size))
4501 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4502 strerror(errno)));
4505 ldap_value_free(vals);
4507 vals = ldap_get_values(ld, entry, "displayName");
4508 if ((vals == NULL) || (vals[0] == NULL))
4509 DEBUG(8, ("\"displayName\" not found\n"));
4510 else if (!pull_utf8_talloc(mem_ctx,
4511 discard_const_p(char *, &result->fullname),
4512 vals[0], &converted_size))
4514 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4515 strerror(errno)));
4518 ldap_value_free(vals);
4520 vals = ldap_get_values(ld, entry, "description");
4521 if ((vals == NULL) || (vals[0] == NULL))
4522 DEBUG(8, ("\"description\" not found\n"));
4523 else if (!pull_utf8_talloc(mem_ctx,
4524 discard_const_p(char *, &result->description),
4525 vals[0], &converted_size))
4527 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4528 strerror(errno)));
4531 ldap_value_free(vals);
4533 if ((result->account_name == NULL) ||
4534 (result->fullname == NULL) ||
4535 (result->description == NULL)) {
4536 DEBUG(0, ("talloc failed\n"));
4537 return False;
4540 vals = ldap_get_values(ld, entry, "sambaSid");
4541 if ((vals == NULL) || (vals[0] == NULL)) {
4542 DEBUG(0, ("\"objectSid\" not found\n"));
4543 return False;
4546 if (!string_to_sid(&sid, vals[0])) {
4547 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4548 ldap_value_free(vals);
4549 return False;
4551 ldap_value_free(vals);
4553 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4554 DEBUG(0, ("sid %s does not belong to our domain\n",
4555 sid_string_dbg(&sid)));
4556 return False;
4559 return True;
4563 static bool ldapsam_search_users(struct pdb_methods *methods,
4564 struct pdb_search *search,
4565 uint32_t acct_flags)
4567 struct ldapsam_privates *ldap_state =
4568 (struct ldapsam_privates *)methods->private_data;
4569 struct ldap_search_state *state;
4571 state = talloc(search, struct ldap_search_state);
4572 if (state == NULL) {
4573 DEBUG(0, ("talloc failed\n"));
4574 return False;
4577 state->connection = ldap_state->smbldap_state;
4579 if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4580 state->base = lp_ldap_user_suffix(talloc_tos());
4581 else if ((acct_flags != 0) &&
4582 ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4583 state->base = lp_ldap_machine_suffix(talloc_tos());
4584 else
4585 state->base = lp_ldap_suffix(talloc_tos());
4587 state->acct_flags = acct_flags;
4588 state->base = talloc_strdup(search, state->base);
4589 state->scope = LDAP_SCOPE_SUBTREE;
4590 state->filter = get_ldap_filter(search, "*");
4591 state->attrs = talloc_attrs(search, "uid", "sambaSid",
4592 "displayName", "description",
4593 "sambaAcctFlags", NULL);
4594 state->attrsonly = 0;
4595 state->pagedresults_cookie = NULL;
4596 state->entries = NULL;
4597 state->ldap2displayentry = ldapuser2displayentry;
4599 if ((state->filter == NULL) || (state->attrs == NULL)) {
4600 DEBUG(0, ("talloc failed\n"));
4601 return False;
4604 search->private_data = state;
4605 search->next_entry = ldapsam_search_next_entry;
4606 search->search_end = ldapsam_search_end;
4608 return ldapsam_search_firstpage(search);
4611 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4612 TALLOC_CTX *mem_ctx,
4613 LDAP *ld, LDAPMessage *entry,
4614 struct samr_displayentry *result)
4616 char **vals;
4617 size_t converted_size;
4618 struct dom_sid sid;
4619 uint16_t group_type;
4621 result->account_name = "";
4622 result->fullname = "";
4623 result->description = "";
4626 vals = ldap_get_values(ld, entry, "sambaGroupType");
4627 if ((vals == NULL) || (vals[0] == NULL)) {
4628 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4629 if (vals != NULL) {
4630 ldap_value_free(vals);
4632 return False;
4635 group_type = atoi(vals[0]);
4637 if ((state->group_type != 0) &&
4638 ((state->group_type != group_type))) {
4639 ldap_value_free(vals);
4640 return False;
4643 ldap_value_free(vals);
4645 /* display name is the NT group name */
4647 vals = ldap_get_values(ld, entry, "displayName");
4648 if ((vals == NULL) || (vals[0] == NULL)) {
4649 DEBUG(8, ("\"displayName\" not found\n"));
4651 /* fallback to the 'cn' attribute */
4652 vals = ldap_get_values(ld, entry, "cn");
4653 if ((vals == NULL) || (vals[0] == NULL)) {
4654 DEBUG(5, ("\"cn\" not found\n"));
4655 return False;
4657 if (!pull_utf8_talloc(mem_ctx,
4658 discard_const_p(char *,
4659 &result->account_name),
4660 vals[0], &converted_size))
4662 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4663 "failed: %s", strerror(errno)));
4666 else if (!pull_utf8_talloc(mem_ctx,
4667 discard_const_p(char *,
4668 &result->account_name),
4669 vals[0], &converted_size))
4671 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4672 strerror(errno)));
4675 ldap_value_free(vals);
4677 vals = ldap_get_values(ld, entry, "description");
4678 if ((vals == NULL) || (vals[0] == NULL))
4679 DEBUG(8, ("\"description\" not found\n"));
4680 else if (!pull_utf8_talloc(mem_ctx,
4681 discard_const_p(char *, &result->description),
4682 vals[0], &converted_size))
4684 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4685 strerror(errno)));
4687 ldap_value_free(vals);
4689 if ((result->account_name == NULL) ||
4690 (result->fullname == NULL) ||
4691 (result->description == NULL)) {
4692 DEBUG(0, ("talloc failed\n"));
4693 return False;
4696 vals = ldap_get_values(ld, entry, "sambaSid");
4697 if ((vals == NULL) || (vals[0] == NULL)) {
4698 DEBUG(0, ("\"objectSid\" not found\n"));
4699 if (vals != NULL) {
4700 ldap_value_free(vals);
4702 return False;
4705 if (!string_to_sid(&sid, vals[0])) {
4706 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4707 return False;
4710 ldap_value_free(vals);
4712 switch (group_type) {
4713 case SID_NAME_DOM_GRP:
4714 case SID_NAME_ALIAS:
4716 if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)
4717 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid))
4719 DEBUG(0, ("%s is not in our domain\n",
4720 sid_string_dbg(&sid)));
4721 return False;
4723 break;
4725 default:
4726 DEBUG(0,("unknown group type: %d\n", group_type));
4727 return False;
4730 result->acct_flags = 0;
4732 return True;
4735 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4736 struct pdb_search *search,
4737 const struct dom_sid *sid,
4738 enum lsa_SidType type)
4740 struct ldapsam_privates *ldap_state =
4741 (struct ldapsam_privates *)methods->private_data;
4742 struct ldap_search_state *state;
4743 fstring tmp;
4745 state = talloc(search, struct ldap_search_state);
4746 if (state == NULL) {
4747 DEBUG(0, ("talloc failed\n"));
4748 return False;
4751 state->connection = ldap_state->smbldap_state;
4753 state->base = lp_ldap_suffix(search);
4754 state->connection = ldap_state->smbldap_state;
4755 state->scope = LDAP_SCOPE_SUBTREE;
4756 state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4757 "(sambaGroupType=%d)(sambaSID=%s*))",
4758 LDAP_OBJ_GROUPMAP,
4759 type, sid_to_fstring(tmp, sid));
4760 state->attrs = talloc_attrs(search, "cn", "sambaSid",
4761 "displayName", "description",
4762 "sambaGroupType", NULL);
4763 state->attrsonly = 0;
4764 state->pagedresults_cookie = NULL;
4765 state->entries = NULL;
4766 state->group_type = type;
4767 state->ldap2displayentry = ldapgroup2displayentry;
4769 if ((state->filter == NULL) || (state->attrs == NULL)) {
4770 DEBUG(0, ("talloc failed\n"));
4771 return False;
4774 search->private_data = state;
4775 search->next_entry = ldapsam_search_next_entry;
4776 search->search_end = ldapsam_search_end;
4778 return ldapsam_search_firstpage(search);
4781 static bool ldapsam_search_groups(struct pdb_methods *methods,
4782 struct pdb_search *search)
4784 return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4787 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4788 struct pdb_search *search,
4789 const struct dom_sid *sid)
4791 return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4794 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4796 return PDB_CAP_STORE_RIDS;
4799 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4800 uint32_t *rid)
4802 struct smbldap_state *smbldap_state = priv->smbldap_state;
4804 LDAPMessage *result = NULL;
4805 LDAPMessage *entry = NULL;
4806 LDAPMod **mods = NULL;
4807 NTSTATUS status;
4808 char *value;
4809 int rc;
4810 uint32_t nextRid = 0;
4811 const char *dn;
4813 TALLOC_CTX *mem_ctx;
4815 mem_ctx = talloc_new(NULL);
4816 if (mem_ctx == NULL) {
4817 DEBUG(0, ("talloc_new failed\n"));
4818 return NT_STATUS_NO_MEMORY;
4821 status = smbldap_search_domain_info(smbldap_state, &result,
4822 get_global_sam_name(), False);
4823 if (!NT_STATUS_IS_OK(status)) {
4824 DEBUG(3, ("Could not get domain info: %s\n",
4825 nt_errstr(status)));
4826 goto done;
4829 talloc_autofree_ldapmsg(mem_ctx, result);
4831 entry = ldap_first_entry(priv2ld(priv), result);
4832 if (entry == NULL) {
4833 DEBUG(0, ("Could not get domain info entry\n"));
4834 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4835 goto done;
4838 /* Find the largest of the three attributes "sambaNextRid",
4839 "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4840 concept of differentiating between user and group rids, and will
4841 use only "sambaNextRid" in the future. But for compatibility
4842 reasons I look if others have chosen different strategies -- VL */
4844 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4845 "sambaNextRid", mem_ctx);
4846 if (value != NULL) {
4847 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4848 nextRid = MAX(nextRid, tmp);
4851 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4852 "sambaNextUserRid", mem_ctx);
4853 if (value != NULL) {
4854 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4855 nextRid = MAX(nextRid, tmp);
4858 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4859 "sambaNextGroupRid", mem_ctx);
4860 if (value != NULL) {
4861 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4862 nextRid = MAX(nextRid, tmp);
4865 if (nextRid == 0) {
4866 nextRid = BASE_RID-1;
4869 nextRid += 1;
4871 smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4872 talloc_asprintf(mem_ctx, "%d", nextRid));
4873 talloc_autofree_ldapmod(mem_ctx, mods);
4875 if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4876 status = NT_STATUS_NO_MEMORY;
4877 goto done;
4880 rc = smbldap_modify(smbldap_state, dn, mods);
4882 /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4883 * please retry" */
4885 status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4887 done:
4888 if (NT_STATUS_IS_OK(status)) {
4889 *rid = nextRid;
4892 TALLOC_FREE(mem_ctx);
4893 return status;
4896 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4898 int i;
4900 for (i=0; i<10; i++) {
4901 NTSTATUS result = ldapsam_get_new_rid(
4902 (struct ldapsam_privates *)methods->private_data, rid);
4903 if (NT_STATUS_IS_OK(result)) {
4904 return result;
4907 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4908 return result;
4911 /* The ldap update failed (maybe a race condition), retry */
4914 /* Tried 10 times, fail. */
4915 return NT_STATUS_ACCESS_DENIED;
4918 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4920 NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4921 return NT_STATUS_IS_OK(result) ? True : False;
4924 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4925 const struct dom_sid *sid,
4926 struct unixid *id)
4928 struct ldapsam_privates *priv =
4929 (struct ldapsam_privates *)methods->private_data;
4930 char *filter;
4931 const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4932 NULL };
4933 LDAPMessage *result = NULL;
4934 LDAPMessage *entry = NULL;
4935 bool ret = False;
4936 char *value;
4937 int rc;
4939 TALLOC_CTX *mem_ctx;
4941 if (!sid_check_is_in_our_sam(sid)) {
4942 /* Not our SID */
4943 return False;
4946 mem_ctx = talloc_new(NULL);
4947 if (mem_ctx == NULL) {
4948 DEBUG(0, ("talloc_new failed\n"));
4949 return False;
4952 filter = talloc_asprintf(mem_ctx,
4953 "(&(sambaSid=%s)"
4954 "(|(objectClass=%s)(objectClass=%s)))",
4955 sid_string_talloc(mem_ctx, sid),
4956 LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4957 if (filter == NULL) {
4958 DEBUG(5, ("talloc_asprintf failed\n"));
4959 goto done;
4962 rc = smbldap_search_suffix(priv->smbldap_state, filter,
4963 attrs, &result);
4964 if (rc != LDAP_SUCCESS) {
4965 goto done;
4967 talloc_autofree_ldapmsg(mem_ctx, result);
4969 if (ldap_count_entries(priv2ld(priv), result) != 1) {
4970 DEBUG(10, ("Got %d entries, expected one\n",
4971 ldap_count_entries(priv2ld(priv), result)));
4972 goto done;
4975 entry = ldap_first_entry(priv2ld(priv), result);
4977 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4978 "sambaGroupType", mem_ctx);
4980 if (value != NULL) {
4981 const char *gid_str;
4982 /* It's a group */
4984 gid_str = smbldap_talloc_single_attribute(
4985 priv2ld(priv), entry, "gidNumber", mem_ctx);
4986 if (gid_str == NULL) {
4987 DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4988 smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4989 entry)));
4990 goto done;
4993 id->id = strtoul(gid_str, NULL, 10);
4994 id->type = ID_TYPE_GID;
4995 idmap_cache_set_sid2unixid(sid, id);
4996 ret = True;
4997 goto done;
5000 /* It must be a user */
5002 value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5003 "uidNumber", mem_ctx);
5004 if (value == NULL) {
5005 DEBUG(1, ("Could not find uidNumber in %s\n",
5006 smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
5007 goto done;
5010 id->id = strtoul(value, NULL, 10);
5011 id->type = ID_TYPE_UID;
5012 idmap_cache_set_sid2unixid(sid, id);
5014 ret = True;
5015 done:
5016 TALLOC_FREE(mem_ctx);
5017 return ret;
5021 * Find the SID for a uid.
5022 * This is shortcut is only used if ldapsam:trusted is set to true.
5024 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5025 struct dom_sid *sid)
5027 struct ldapsam_privates *priv =
5028 (struct ldapsam_privates *)methods->private_data;
5029 char *filter;
5030 const char *attrs[] = { "sambaSID", NULL };
5031 LDAPMessage *result = NULL;
5032 LDAPMessage *entry = NULL;
5033 bool ret = false;
5034 char *user_sid_string;
5035 struct dom_sid user_sid;
5036 int rc;
5037 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5038 struct unixid id;
5040 filter = talloc_asprintf(tmp_ctx,
5041 "(&(uidNumber=%u)"
5042 "(objectClass=%s)"
5043 "(objectClass=%s))",
5044 (unsigned int)uid,
5045 LDAP_OBJ_POSIXACCOUNT,
5046 LDAP_OBJ_SAMBASAMACCOUNT);
5047 if (filter == NULL) {
5048 DEBUG(3, ("talloc_asprintf failed\n"));
5049 goto done;
5052 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5053 if (rc != LDAP_SUCCESS) {
5054 goto done;
5056 talloc_autofree_ldapmsg(tmp_ctx, result);
5058 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5059 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5060 ldap_count_entries(priv2ld(priv), result),
5061 (unsigned int)uid));
5062 goto done;
5065 entry = ldap_first_entry(priv2ld(priv), result);
5067 user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5068 "sambaSID", tmp_ctx);
5069 if (user_sid_string == NULL) {
5070 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5071 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5072 goto done;
5075 if (!string_to_sid(&user_sid, user_sid_string)) {
5076 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5077 user_sid_string));
5078 goto done;
5081 sid_copy(sid, &user_sid);
5083 id.id = uid;
5084 id.type = ID_TYPE_UID;
5086 idmap_cache_set_sid2unixid(sid, &id);
5088 ret = true;
5090 done:
5091 TALLOC_FREE(tmp_ctx);
5092 return ret;
5096 * Find the SID for a gid.
5097 * This is shortcut is only used if ldapsam:trusted is set to true.
5099 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5100 struct dom_sid *sid)
5102 struct ldapsam_privates *priv =
5103 (struct ldapsam_privates *)methods->private_data;
5104 char *filter;
5105 const char *attrs[] = { "sambaSID", NULL };
5106 LDAPMessage *result = NULL;
5107 LDAPMessage *entry = NULL;
5108 bool ret = false;
5109 char *group_sid_string;
5110 struct dom_sid group_sid;
5111 int rc;
5112 TALLOC_CTX *tmp_ctx = talloc_stackframe();
5113 struct unixid id;
5115 filter = talloc_asprintf(tmp_ctx,
5116 "(&(gidNumber=%u)"
5117 "(objectClass=%s))",
5118 (unsigned int)gid,
5119 LDAP_OBJ_GROUPMAP);
5120 if (filter == NULL) {
5121 DEBUG(3, ("talloc_asprintf failed\n"));
5122 goto done;
5125 rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5126 if (rc != LDAP_SUCCESS) {
5127 goto done;
5129 talloc_autofree_ldapmsg(tmp_ctx, result);
5131 if (ldap_count_entries(priv2ld(priv), result) != 1) {
5132 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5133 ldap_count_entries(priv2ld(priv), result),
5134 (unsigned int)gid));
5135 goto done;
5138 entry = ldap_first_entry(priv2ld(priv), result);
5140 group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5141 "sambaSID", tmp_ctx);
5142 if (group_sid_string == NULL) {
5143 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5144 smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5145 goto done;
5148 if (!string_to_sid(&group_sid, group_sid_string)) {
5149 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5150 group_sid_string));
5151 goto done;
5154 sid_copy(sid, &group_sid);
5156 id.id = gid;
5157 id.type = ID_TYPE_GID;
5159 idmap_cache_set_sid2unixid(sid, &id);
5161 ret = true;
5163 done:
5164 TALLOC_FREE(tmp_ctx);
5165 return ret;
5170 * The following functions are called only if
5171 * ldapsam:trusted and ldapsam:editposix are
5172 * set to true
5176 * ldapsam_create_user creates a new
5177 * posixAccount and sambaSamAccount object
5178 * in the ldap users subtree
5180 * The uid is allocated by winbindd.
5183 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5184 TALLOC_CTX *tmp_ctx, const char *name,
5185 uint32_t acb_info, uint32_t *rid)
5187 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5188 LDAPMessage *entry = NULL;
5189 LDAPMessage *result = NULL;
5190 uint32_t num_result;
5191 bool is_machine = False;
5192 bool add_posix = False;
5193 LDAPMod **mods = NULL;
5194 struct samu *user;
5195 char *filter;
5196 char *username;
5197 char *homedir;
5198 char *gidstr;
5199 char *uidstr;
5200 char *shell;
5201 const char *dn = NULL;
5202 struct dom_sid group_sid;
5203 struct dom_sid user_sid;
5204 gid_t gid = -1;
5205 uid_t uid = -1;
5206 NTSTATUS ret;
5207 int rc;
5209 if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5210 acb_info & ACB_WSTRUST ||
5211 acb_info & ACB_SVRTRUST ||
5212 acb_info & ACB_DOMTRUST) {
5213 is_machine = True;
5216 username = escape_ldap_string(talloc_tos(), name);
5217 filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5218 username, LDAP_OBJ_POSIXACCOUNT);
5219 TALLOC_FREE(username);
5221 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5222 if (rc != LDAP_SUCCESS) {
5223 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5224 return NT_STATUS_ACCESS_DENIED;
5226 talloc_autofree_ldapmsg(tmp_ctx, result);
5228 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5230 if (num_result > 1) {
5231 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5232 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5235 if (num_result == 1) {
5236 char *tmp;
5237 /* check if it is just a posix account.
5238 * or if there is a sid attached to this entry
5241 entry = ldap_first_entry(priv2ld(ldap_state), result);
5242 if (!entry) {
5243 return NT_STATUS_UNSUCCESSFUL;
5246 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5247 if (tmp) {
5248 DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5249 return NT_STATUS_USER_EXISTS;
5252 /* it is just a posix account, retrieve the dn for later use */
5253 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5254 if (!dn) {
5255 DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5256 return NT_STATUS_NO_MEMORY;
5260 if (num_result == 0) {
5261 add_posix = True;
5264 /* Create the basic samu structure and generate the mods for the ldap commit */
5265 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5266 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5267 return ret;
5270 sid_compose(&user_sid, get_global_sam_sid(), *rid);
5272 user = samu_new(tmp_ctx);
5273 if (!user) {
5274 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5275 return NT_STATUS_NO_MEMORY;
5278 if (!pdb_set_username(user, name, PDB_SET)) {
5279 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5280 return NT_STATUS_UNSUCCESSFUL;
5282 if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5283 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5284 return NT_STATUS_UNSUCCESSFUL;
5286 if (is_machine) {
5287 if (acb_info & ACB_NORMAL) {
5288 if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5289 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5290 return NT_STATUS_UNSUCCESSFUL;
5292 } else {
5293 if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5294 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5295 return NT_STATUS_UNSUCCESSFUL;
5298 } else {
5299 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5300 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5301 return NT_STATUS_UNSUCCESSFUL;
5305 if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5306 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5307 return NT_STATUS_UNSUCCESSFUL;
5310 if (!init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed)) {
5311 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5312 return NT_STATUS_UNSUCCESSFUL;
5315 if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5316 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5318 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5320 if (add_posix) {
5321 char *escape_name;
5323 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5325 /* retrieve the Domain Users group gid */
5326 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5327 !sid_to_gid(&group_sid, &gid)) {
5328 DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5329 return NT_STATUS_INVALID_PRIMARY_GROUP;
5332 /* lets allocate a new userid for this user */
5333 if (!winbind_allocate_uid(&uid)) {
5334 DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5335 return NT_STATUS_UNSUCCESSFUL;
5339 if (is_machine) {
5340 /* TODO: choose a more appropriate default for machines */
5341 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5342 shell = talloc_strdup(tmp_ctx, "/bin/false");
5343 } else {
5344 homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5345 shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5347 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5348 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5350 escape_name = escape_rdn_val_string_alloc(name);
5351 if (!escape_name) {
5352 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5353 return NT_STATUS_NO_MEMORY;
5356 if (is_machine) {
5357 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
5358 } else {
5359 dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
5362 SAFE_FREE(escape_name);
5364 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5365 DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5366 return NT_STATUS_NO_MEMORY;
5369 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5370 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5371 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5372 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5373 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5374 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5375 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5378 talloc_autofree_ldapmod(tmp_ctx, mods);
5380 if (add_posix) {
5381 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5382 } else {
5383 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5386 if (rc != LDAP_SUCCESS) {
5387 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5388 return NT_STATUS_UNSUCCESSFUL;
5391 DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5393 flush_pwnam_cache();
5395 return NT_STATUS_OK;
5398 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5400 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5401 LDAPMessage *result = NULL;
5402 LDAPMessage *entry = NULL;
5403 int num_result;
5404 const char *dn;
5405 char *filter;
5406 int rc;
5408 DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5410 filter = talloc_asprintf(tmp_ctx,
5411 "(&(uid=%s)"
5412 "(objectClass=%s)"
5413 "(objectClass=%s))",
5414 pdb_get_username(sam_acct),
5415 LDAP_OBJ_POSIXACCOUNT,
5416 LDAP_OBJ_SAMBASAMACCOUNT);
5417 if (filter == NULL) {
5418 return NT_STATUS_NO_MEMORY;
5421 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5422 if (rc != LDAP_SUCCESS) {
5423 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5424 return NT_STATUS_UNSUCCESSFUL;
5426 talloc_autofree_ldapmsg(tmp_ctx, result);
5428 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5430 if (num_result == 0) {
5431 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5432 return NT_STATUS_NO_SUCH_USER;
5435 if (num_result > 1) {
5436 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5437 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5440 entry = ldap_first_entry(priv2ld(ldap_state), result);
5441 if (!entry) {
5442 return NT_STATUS_UNSUCCESSFUL;
5445 /* it is just a posix account, retrieve the dn for later use */
5446 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5447 if (!dn) {
5448 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5449 return NT_STATUS_NO_MEMORY;
5452 /* try to remove memberships first */
5454 NTSTATUS status;
5455 struct dom_sid *sids = NULL;
5456 gid_t *gids = NULL;
5457 uint32_t num_groups = 0;
5458 int i;
5459 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5461 status = ldapsam_enum_group_memberships(my_methods,
5462 tmp_ctx,
5463 sam_acct,
5464 &sids,
5465 &gids,
5466 &num_groups);
5467 if (!NT_STATUS_IS_OK(status)) {
5468 goto delete_dn;
5471 for (i=0; i < num_groups; i++) {
5473 uint32_t group_rid;
5475 sid_peek_rid(&sids[i], &group_rid);
5477 ldapsam_del_groupmem(my_methods,
5478 tmp_ctx,
5479 group_rid,
5480 user_rid);
5484 delete_dn:
5486 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5487 if (rc != LDAP_SUCCESS) {
5488 return NT_STATUS_UNSUCCESSFUL;
5491 flush_pwnam_cache();
5493 return NT_STATUS_OK;
5497 * ldapsam_create_group creates a new
5498 * posixGroup and sambaGroupMapping object
5499 * in the ldap groups subtree
5501 * The gid is allocated by winbindd.
5504 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5505 TALLOC_CTX *tmp_ctx,
5506 const char *name,
5507 uint32_t *rid)
5509 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5510 NTSTATUS ret;
5511 LDAPMessage *entry = NULL;
5512 LDAPMessage *result = NULL;
5513 uint32_t num_result;
5514 bool is_new_entry = False;
5515 LDAPMod **mods = NULL;
5516 char *filter;
5517 char *groupsidstr;
5518 char *groupname;
5519 char *grouptype;
5520 char *gidstr;
5521 const char *dn = NULL;
5522 struct dom_sid group_sid;
5523 gid_t gid = -1;
5524 int rc;
5526 groupname = escape_ldap_string(talloc_tos(), name);
5527 filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5528 groupname, LDAP_OBJ_POSIXGROUP);
5529 TALLOC_FREE(groupname);
5531 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5532 if (rc != LDAP_SUCCESS) {
5533 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5534 return NT_STATUS_UNSUCCESSFUL;
5536 talloc_autofree_ldapmsg(tmp_ctx, result);
5538 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5540 if (num_result > 1) {
5541 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5542 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5545 if (num_result == 1) {
5546 char *tmp;
5547 /* check if it is just a posix group.
5548 * or if there is a sid attached to this entry
5551 entry = ldap_first_entry(priv2ld(ldap_state), result);
5552 if (!entry) {
5553 return NT_STATUS_UNSUCCESSFUL;
5556 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5557 if (tmp) {
5558 DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5559 return NT_STATUS_GROUP_EXISTS;
5562 /* it is just a posix group, retrieve the gid and the dn for later use */
5563 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5564 if (!tmp) {
5565 DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5566 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5569 gid = strtoul(tmp, NULL, 10);
5571 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5572 if (!dn) {
5573 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5574 return NT_STATUS_NO_MEMORY;
5578 if (num_result == 0) {
5579 is_new_entry = true;
5582 if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5583 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5584 return ret;
5587 sid_compose(&group_sid, get_global_sam_sid(), *rid);
5589 groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5590 &group_sid));
5591 grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5593 if (!groupsidstr || !grouptype) {
5594 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5595 return NT_STATUS_NO_MEMORY;
5598 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5599 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5600 smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5601 smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5603 if (is_new_entry) {
5604 char *escape_name;
5606 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5608 /* lets allocate a new groupid for this group */
5609 if (!winbind_allocate_gid(&gid)) {
5610 DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5611 return NT_STATUS_UNSUCCESSFUL;
5614 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5616 escape_name = escape_rdn_val_string_alloc(name);
5617 if (!escape_name) {
5618 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5619 return NT_STATUS_NO_MEMORY;
5622 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
5624 SAFE_FREE(escape_name);
5626 if (!gidstr || !dn) {
5627 DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5628 return NT_STATUS_NO_MEMORY;
5631 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5632 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5633 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5636 talloc_autofree_ldapmod(tmp_ctx, mods);
5638 if (is_new_entry) {
5639 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5640 #if 0
5641 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5642 /* This call may fail with rfc2307bis schema */
5643 /* Retry adding a structural class */
5644 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5645 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5647 #endif
5648 } else {
5649 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5652 if (rc != LDAP_SUCCESS) {
5653 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5654 return NT_STATUS_UNSUCCESSFUL;
5657 DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5659 return NT_STATUS_OK;
5662 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5664 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5665 LDAPMessage *result = NULL;
5666 LDAPMessage *entry = NULL;
5667 int num_result;
5668 const char *dn;
5669 char *gidstr;
5670 char *filter;
5671 struct dom_sid group_sid;
5672 int rc;
5674 /* get the group sid */
5675 sid_compose(&group_sid, get_global_sam_sid(), rid);
5677 filter = talloc_asprintf(tmp_ctx,
5678 "(&(sambaSID=%s)"
5679 "(objectClass=%s)"
5680 "(objectClass=%s))",
5681 sid_string_talloc(tmp_ctx, &group_sid),
5682 LDAP_OBJ_POSIXGROUP,
5683 LDAP_OBJ_GROUPMAP);
5684 if (filter == NULL) {
5685 return NT_STATUS_NO_MEMORY;
5688 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5689 if (rc != LDAP_SUCCESS) {
5690 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5691 return NT_STATUS_UNSUCCESSFUL;
5693 talloc_autofree_ldapmsg(tmp_ctx, result);
5695 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5697 if (num_result == 0) {
5698 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5699 return NT_STATUS_NO_SUCH_GROUP;
5702 if (num_result > 1) {
5703 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5704 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5707 entry = ldap_first_entry(priv2ld(ldap_state), result);
5708 if (!entry) {
5709 return NT_STATUS_UNSUCCESSFUL;
5712 /* here it is, retrieve the dn for later use */
5713 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5714 if (!dn) {
5715 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5716 return NT_STATUS_NO_MEMORY;
5719 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5720 if (!gidstr) {
5721 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5722 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5725 /* check no user have this group marked as primary group */
5726 filter = talloc_asprintf(tmp_ctx,
5727 "(&(gidNumber=%s)"
5728 "(objectClass=%s)"
5729 "(objectClass=%s))",
5730 gidstr,
5731 LDAP_OBJ_POSIXACCOUNT,
5732 LDAP_OBJ_SAMBASAMACCOUNT);
5734 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5735 if (rc != LDAP_SUCCESS) {
5736 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5737 return NT_STATUS_UNSUCCESSFUL;
5739 talloc_autofree_ldapmsg(tmp_ctx, result);
5741 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5743 if (num_result != 0) {
5744 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5745 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5748 rc = smbldap_delete(ldap_state->smbldap_state, dn);
5749 if (rc != LDAP_SUCCESS) {
5750 return NT_STATUS_UNSUCCESSFUL;
5753 return NT_STATUS_OK;
5756 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5757 TALLOC_CTX *tmp_ctx,
5758 uint32_t group_rid,
5759 uint32_t member_rid,
5760 int modop)
5762 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5763 LDAPMessage *entry = NULL;
5764 LDAPMessage *result = NULL;
5765 uint32_t num_result;
5766 LDAPMod **mods = NULL;
5767 char *filter;
5768 char *uidstr;
5769 const char *dn = NULL;
5770 struct dom_sid group_sid;
5771 struct dom_sid member_sid;
5772 int rc;
5774 switch (modop) {
5775 case LDAP_MOD_ADD:
5776 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5777 break;
5778 case LDAP_MOD_DELETE:
5779 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5780 break;
5781 default:
5782 return NT_STATUS_UNSUCCESSFUL;
5785 /* get member sid */
5786 sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5788 /* get the group sid */
5789 sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5791 filter = talloc_asprintf(tmp_ctx,
5792 "(&(sambaSID=%s)"
5793 "(objectClass=%s)"
5794 "(objectClass=%s))",
5795 sid_string_talloc(tmp_ctx, &member_sid),
5796 LDAP_OBJ_POSIXACCOUNT,
5797 LDAP_OBJ_SAMBASAMACCOUNT);
5798 if (filter == NULL) {
5799 return NT_STATUS_NO_MEMORY;
5802 /* get the member uid */
5803 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5804 if (rc != LDAP_SUCCESS) {
5805 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5806 return NT_STATUS_UNSUCCESSFUL;
5808 talloc_autofree_ldapmsg(tmp_ctx, result);
5810 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5812 if (num_result == 0) {
5813 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5814 return NT_STATUS_NO_SUCH_MEMBER;
5817 if (num_result > 1) {
5818 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5819 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5822 entry = ldap_first_entry(priv2ld(ldap_state), result);
5823 if (!entry) {
5824 return NT_STATUS_UNSUCCESSFUL;
5827 if (modop == LDAP_MOD_DELETE) {
5828 /* check if we are trying to remove the member from his primary group */
5829 char *gidstr;
5830 gid_t user_gid, group_gid;
5832 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5833 if (!gidstr) {
5834 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5835 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5838 user_gid = strtoul(gidstr, NULL, 10);
5840 if (!sid_to_gid(&group_sid, &group_gid)) {
5841 DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5842 return NT_STATUS_UNSUCCESSFUL;
5845 if (user_gid == group_gid) {
5846 DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5847 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5851 /* here it is, retrieve the uid for later use */
5852 uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5853 if (!uidstr) {
5854 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5855 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5858 filter = talloc_asprintf(tmp_ctx,
5859 "(&(sambaSID=%s)"
5860 "(objectClass=%s)"
5861 "(objectClass=%s))",
5862 sid_string_talloc(tmp_ctx, &group_sid),
5863 LDAP_OBJ_POSIXGROUP,
5864 LDAP_OBJ_GROUPMAP);
5866 /* get the group */
5867 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5868 if (rc != LDAP_SUCCESS) {
5869 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5870 return NT_STATUS_UNSUCCESSFUL;
5872 talloc_autofree_ldapmsg(tmp_ctx, result);
5874 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5876 if (num_result == 0) {
5877 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5878 return NT_STATUS_NO_SUCH_GROUP;
5881 if (num_result > 1) {
5882 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5883 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5886 entry = ldap_first_entry(priv2ld(ldap_state), result);
5887 if (!entry) {
5888 return NT_STATUS_UNSUCCESSFUL;
5891 /* here it is, retrieve the dn for later use */
5892 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5893 if (!dn) {
5894 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5895 return NT_STATUS_NO_MEMORY;
5898 smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5900 talloc_autofree_ldapmod(tmp_ctx, mods);
5902 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5903 if (rc != LDAP_SUCCESS) {
5904 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5905 DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5906 return NT_STATUS_MEMBER_IN_GROUP;
5908 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5909 DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5910 return NT_STATUS_MEMBER_NOT_IN_GROUP;
5912 return NT_STATUS_UNSUCCESSFUL;
5915 return NT_STATUS_OK;
5918 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5919 TALLOC_CTX *tmp_ctx,
5920 uint32_t group_rid,
5921 uint32_t member_rid)
5923 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5925 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5926 TALLOC_CTX *tmp_ctx,
5927 uint32_t group_rid,
5928 uint32_t member_rid)
5930 return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5933 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5934 TALLOC_CTX *mem_ctx,
5935 struct samu *sampass)
5937 struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5938 LDAPMessage *entry = NULL;
5939 LDAPMessage *result = NULL;
5940 uint32_t num_result;
5941 LDAPMod **mods = NULL;
5942 char *filter;
5943 char *escape_username;
5944 char *gidstr;
5945 const char *dn = NULL;
5946 gid_t gid;
5947 int rc;
5949 DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5951 if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5952 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5953 return NT_STATUS_UNSUCCESSFUL;
5955 gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5956 if (!gidstr) {
5957 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5958 return NT_STATUS_NO_MEMORY;
5961 escape_username = escape_ldap_string(talloc_tos(),
5962 pdb_get_username(sampass));
5963 if (escape_username== NULL) {
5964 return NT_STATUS_NO_MEMORY;
5967 filter = talloc_asprintf(mem_ctx,
5968 "(&(uid=%s)"
5969 "(objectClass=%s)"
5970 "(objectClass=%s))",
5971 escape_username,
5972 LDAP_OBJ_POSIXACCOUNT,
5973 LDAP_OBJ_SAMBASAMACCOUNT);
5975 TALLOC_FREE(escape_username);
5977 if (filter == NULL) {
5978 return NT_STATUS_NO_MEMORY;
5981 rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5982 if (rc != LDAP_SUCCESS) {
5983 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5984 return NT_STATUS_UNSUCCESSFUL;
5986 talloc_autofree_ldapmsg(mem_ctx, result);
5988 num_result = ldap_count_entries(priv2ld(ldap_state), result);
5990 if (num_result == 0) {
5991 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5992 return NT_STATUS_NO_SUCH_USER;
5995 if (num_result > 1) {
5996 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5997 return NT_STATUS_INTERNAL_DB_CORRUPTION;
6000 entry = ldap_first_entry(priv2ld(ldap_state), result);
6001 if (!entry) {
6002 return NT_STATUS_UNSUCCESSFUL;
6005 /* retrieve the dn for later use */
6006 dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
6007 if (!dn) {
6008 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
6009 return NT_STATUS_NO_MEMORY;
6012 /* remove the old one, and add the new one, this way we do not risk races */
6013 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
6015 if (mods == NULL) {
6016 return NT_STATUS_OK;
6019 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6021 if (rc != LDAP_SUCCESS) {
6022 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6023 pdb_get_username(sampass), gidstr));
6024 return NT_STATUS_UNSUCCESSFUL;
6027 flush_pwnam_cache();
6029 return NT_STATUS_OK;
6033 /**********************************************************************
6034 trusted domains functions
6035 *********************************************************************/
6037 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6038 const char *domain)
6040 return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6041 ldap_state->domain_dn);
6044 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6045 TALLOC_CTX *mem_ctx,
6046 const char *domain, LDAPMessage **entry)
6048 int rc;
6049 char *filter;
6050 int scope = LDAP_SCOPE_SUBTREE;
6051 const char **attrs = NULL; /* NULL: get all attrs */
6052 int attrsonly = 0; /* 0: return values too */
6053 LDAPMessage *result = NULL;
6054 char *trusted_dn;
6055 uint32_t num_result;
6057 filter = talloc_asprintf(talloc_tos(),
6058 "(&(objectClass=%s)(sambaDomainName=%s))",
6059 LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6061 trusted_dn = trusteddom_dn(ldap_state, domain);
6062 if (trusted_dn == NULL) {
6063 return False;
6065 rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6066 filter, attrs, attrsonly, &result);
6068 if (result != NULL) {
6069 talloc_autofree_ldapmsg(mem_ctx, result);
6072 if (rc == LDAP_NO_SUCH_OBJECT) {
6073 *entry = NULL;
6074 return True;
6077 if (rc != LDAP_SUCCESS) {
6078 return False;
6081 num_result = ldap_count_entries(priv2ld(ldap_state), result);
6083 if (num_result > 1) {
6084 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6085 "%s object for domain '%s'?!\n",
6086 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6087 return False;
6090 if (num_result == 0) {
6091 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6092 "%s object for domain %s.\n",
6093 LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6094 *entry = NULL;
6095 } else {
6096 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6099 return True;
6102 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6103 const char *domain,
6104 char** pwd,
6105 struct dom_sid *sid,
6106 time_t *pass_last_set_time)
6108 struct ldapsam_privates *ldap_state =
6109 (struct ldapsam_privates *)methods->private_data;
6110 LDAPMessage *entry = NULL;
6112 DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6114 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6115 (entry == NULL))
6117 return False;
6120 /* password */
6121 if (pwd != NULL) {
6122 char *pwd_str;
6123 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6124 entry, "sambaClearTextPassword", talloc_tos());
6125 if (pwd_str == NULL) {
6126 return False;
6128 /* trusteddom_pw routines do not use talloc yet... */
6129 *pwd = SMB_STRDUP(pwd_str);
6130 if (*pwd == NULL) {
6131 return False;
6135 /* last change time */
6136 if (pass_last_set_time != NULL) {
6137 char *time_str;
6138 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6139 entry, "sambaPwdLastSet", talloc_tos());
6140 if (time_str == NULL) {
6141 return False;
6143 *pass_last_set_time = (time_t)atol(time_str);
6146 /* domain sid */
6147 if (sid != NULL) {
6148 char *sid_str;
6149 struct dom_sid dom_sid;
6150 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6151 entry, "sambaSID",
6152 talloc_tos());
6153 if (sid_str == NULL) {
6154 return False;
6156 if (!string_to_sid(&dom_sid, sid_str)) {
6157 return False;
6159 sid_copy(sid, &dom_sid);
6162 return True;
6165 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6166 const char* domain,
6167 const char* pwd,
6168 const struct dom_sid *sid)
6170 struct ldapsam_privates *ldap_state =
6171 (struct ldapsam_privates *)methods->private_data;
6172 LDAPMessage *entry = NULL;
6173 LDAPMod **mods = NULL;
6174 char *prev_pwd = NULL;
6175 char *trusted_dn = NULL;
6176 int rc;
6178 DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6181 * get the current entry (if there is one) in order to put the
6182 * current password into the previous password attribute
6184 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6185 return False;
6188 mods = NULL;
6189 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6190 LDAP_OBJ_TRUSTDOM_PASSWORD);
6191 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6192 domain);
6193 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6194 sid_string_tos(sid));
6195 smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6196 talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6197 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6198 "sambaClearTextPassword", pwd);
6200 if (entry != NULL) {
6201 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6202 entry, "sambaClearTextPassword", talloc_tos());
6203 if (prev_pwd != NULL) {
6204 smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6205 "sambaPreviousClearTextPassword",
6206 prev_pwd);
6210 talloc_autofree_ldapmod(talloc_tos(), mods);
6212 trusted_dn = trusteddom_dn(ldap_state, domain);
6213 if (trusted_dn == NULL) {
6214 return False;
6216 if (entry == NULL) {
6217 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6218 } else {
6219 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6222 if (rc != LDAP_SUCCESS) {
6223 DEBUG(1, ("error writing trusted domain password!\n"));
6224 return False;
6227 return True;
6230 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6231 const char *domain)
6233 int rc;
6234 struct ldapsam_privates *ldap_state =
6235 (struct ldapsam_privates *)methods->private_data;
6236 LDAPMessage *entry = NULL;
6237 const char *trusted_dn;
6239 if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6240 return False;
6243 if (entry == NULL) {
6244 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6245 "%s\n", domain));
6246 return True;
6249 trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6250 entry);
6251 if (trusted_dn == NULL) {
6252 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6253 return False;
6256 rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6257 if (rc != LDAP_SUCCESS) {
6258 return False;
6261 return True;
6264 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6265 TALLOC_CTX *mem_ctx,
6266 uint32_t *num_domains,
6267 struct trustdom_info ***domains)
6269 int rc;
6270 struct ldapsam_privates *ldap_state =
6271 (struct ldapsam_privates *)methods->private_data;
6272 char *filter;
6273 int scope = LDAP_SCOPE_SUBTREE;
6274 const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6275 int attrsonly = 0; /* 0: return values too */
6276 LDAPMessage *result = NULL;
6277 LDAPMessage *entry = NULL;
6279 filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6280 LDAP_OBJ_TRUSTDOM_PASSWORD);
6282 rc = smbldap_search(ldap_state->smbldap_state,
6283 ldap_state->domain_dn,
6284 scope,
6285 filter,
6286 attrs,
6287 attrsonly,
6288 &result);
6290 if (result != NULL) {
6291 talloc_autofree_ldapmsg(mem_ctx, result);
6294 if (rc != LDAP_SUCCESS) {
6295 return NT_STATUS_UNSUCCESSFUL;
6298 *num_domains = 0;
6299 if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6300 DEBUG(1, ("talloc failed\n"));
6301 return NT_STATUS_NO_MEMORY;
6304 for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6305 entry != NULL;
6306 entry = ldap_next_entry(priv2ld(ldap_state), entry))
6308 char *dom_name, *dom_sid_str;
6309 struct trustdom_info *dom_info;
6311 dom_info = talloc(*domains, struct trustdom_info);
6312 if (dom_info == NULL) {
6313 DEBUG(1, ("talloc failed\n"));
6314 return NT_STATUS_NO_MEMORY;
6317 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6318 entry,
6319 "sambaDomainName",
6320 talloc_tos());
6321 if (dom_name == NULL) {
6322 DEBUG(1, ("talloc failed\n"));
6323 return NT_STATUS_NO_MEMORY;
6325 dom_info->name = dom_name;
6327 dom_sid_str = smbldap_talloc_single_attribute(
6328 priv2ld(ldap_state), entry, "sambaSID",
6329 talloc_tos());
6330 if (dom_sid_str == NULL) {
6331 DEBUG(1, ("talloc failed\n"));
6332 return NT_STATUS_NO_MEMORY;
6334 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6335 DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6336 dom_sid_str));
6337 return NT_STATUS_UNSUCCESSFUL;
6340 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6341 domains, num_domains);
6343 if (*domains == NULL) {
6344 DEBUG(1, ("talloc failed\n"));
6345 return NT_STATUS_NO_MEMORY;
6349 DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6350 return NT_STATUS_OK;
6354 /**********************************************************************
6355 Housekeeping
6356 *********************************************************************/
6358 static void free_private_data(void **vp)
6360 struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6362 smbldap_free_struct(&(*ldap_state)->smbldap_state);
6364 if ((*ldap_state)->result != NULL) {
6365 ldap_msgfree((*ldap_state)->result);
6366 (*ldap_state)->result = NULL;
6368 if ((*ldap_state)->domain_dn != NULL) {
6369 SAFE_FREE((*ldap_state)->domain_dn);
6372 *ldap_state = NULL;
6374 /* No need to free any further, as it is talloc()ed */
6377 /*********************************************************************
6378 Intitalise the parts of the pdb_methods structure that are common to
6379 all pdb_ldap modes
6380 *********************************************************************/
6382 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6384 NTSTATUS nt_status;
6385 struct ldapsam_privates *ldap_state;
6386 char *bind_dn = NULL;
6387 char *bind_secret = NULL;
6389 if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6390 return nt_status;
6393 (*pdb_method)->name = "ldapsam";
6395 (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6396 (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6397 (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6398 (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6399 (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6400 (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6402 (*pdb_method)->getgrsid = ldapsam_getgrsid;
6403 (*pdb_method)->getgrgid = ldapsam_getgrgid;
6404 (*pdb_method)->getgrnam = ldapsam_getgrnam;
6405 (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6406 (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6407 (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6408 (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6410 (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6411 (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6413 (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6415 (*pdb_method)->capabilities = ldapsam_capabilities;
6416 (*pdb_method)->new_rid = ldapsam_new_rid;
6418 (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6419 (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6420 (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6421 (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6423 /* TODO: Setup private data and free */
6425 if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6426 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6427 return NT_STATUS_NO_MEMORY;
6430 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
6431 DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
6432 return NT_STATUS_NO_MEMORY;
6435 nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
6436 location, false, bind_dn, bind_secret,
6437 &ldap_state->smbldap_state);
6438 memset(bind_secret, '\0', strlen(bind_secret));
6439 SAFE_FREE(bind_secret);
6440 SAFE_FREE(bind_dn);
6441 if ( !NT_STATUS_IS_OK(nt_status) ) {
6442 return nt_status;
6445 if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6446 return NT_STATUS_NO_MEMORY;
6449 (*pdb_method)->private_data = ldap_state;
6451 (*pdb_method)->free_private_data = free_private_data;
6453 return NT_STATUS_OK;
6456 /**********************************************************************
6457 Initialise the normal mode for pdb_ldap
6458 *********************************************************************/
6460 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
6462 NTSTATUS nt_status;
6463 struct ldapsam_privates *ldap_state = NULL;
6464 uint32_t alg_rid_base;
6465 char *alg_rid_base_string = NULL;
6466 LDAPMessage *result = NULL;
6467 LDAPMessage *entry = NULL;
6468 struct dom_sid ldap_domain_sid;
6469 struct dom_sid secrets_domain_sid;
6470 char *domain_sid_string = NULL;
6471 char *dn = NULL;
6472 char *uri = talloc_strdup( NULL, location );
6474 trim_char( uri, '\"', '\"' );
6475 nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6477 TALLOC_FREE(uri);
6479 if (!NT_STATUS_IS_OK(nt_status)) {
6480 return nt_status;
6483 (*pdb_method)->name = "ldapsam";
6485 (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6486 (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6487 (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6488 (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6489 (*pdb_method)->search_users = ldapsam_search_users;
6490 (*pdb_method)->search_groups = ldapsam_search_groups;
6491 (*pdb_method)->search_aliases = ldapsam_search_aliases;
6493 if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6494 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6495 (*pdb_method)->enum_group_memberships =
6496 ldapsam_enum_group_memberships;
6497 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6498 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6499 (*pdb_method)->uid_to_sid = ldapsam_uid_to_sid;
6500 (*pdb_method)->gid_to_sid = ldapsam_gid_to_sid;
6502 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6503 (*pdb_method)->create_user = ldapsam_create_user;
6504 (*pdb_method)->delete_user = ldapsam_delete_user;
6505 (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6506 (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6507 (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6508 (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6509 (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6513 ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6514 ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6516 /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6518 nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6519 &result,
6520 ldap_state->domain_name, True);
6522 if ( !NT_STATUS_IS_OK(nt_status) ) {
6523 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6524 "info, nor add one to the domain. "
6525 "We cannot work reliably without it.\n"));
6526 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6529 /* Given that the above might fail, everything below this must be
6530 * optional */
6532 entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6533 result);
6534 if (!entry) {
6535 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6536 "entry\n"));
6537 ldap_msgfree(result);
6538 return NT_STATUS_UNSUCCESSFUL;
6541 dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6542 if (!dn) {
6543 ldap_msgfree(result);
6544 return NT_STATUS_UNSUCCESSFUL;
6547 ldap_state->domain_dn = smb_xstrdup(dn);
6548 TALLOC_FREE(dn);
6550 domain_sid_string = smbldap_talloc_single_attribute(
6551 ldap_state->smbldap_state->ldap_struct,
6552 entry,
6553 get_userattr_key2string(ldap_state->schema_ver,
6554 LDAP_ATTR_USER_SID),
6555 talloc_tos());
6557 if (domain_sid_string) {
6558 bool found_sid;
6559 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6560 DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6561 "read as a valid SID\n", domain_sid_string));
6562 ldap_msgfree(result);
6563 TALLOC_FREE(domain_sid_string);
6564 return NT_STATUS_INVALID_PARAMETER;
6566 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6567 &secrets_domain_sid);
6568 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6569 &ldap_domain_sid)) {
6570 DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6571 "%s based on pdb_ldap results %s -> %s\n",
6572 ldap_state->domain_name,
6573 sid_string_dbg(&secrets_domain_sid),
6574 sid_string_dbg(&ldap_domain_sid)));
6576 /* reset secrets.tdb sid */
6577 secrets_store_domain_sid(ldap_state->domain_name,
6578 &ldap_domain_sid);
6579 DEBUG(1, ("New global sam SID: %s\n",
6580 sid_string_dbg(get_global_sam_sid())));
6582 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6583 TALLOC_FREE(domain_sid_string);
6586 alg_rid_base_string = smbldap_talloc_single_attribute(
6587 ldap_state->smbldap_state->ldap_struct,
6588 entry,
6589 get_attr_key2string( dominfo_attr_list,
6590 LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6591 talloc_tos());
6592 if (alg_rid_base_string) {
6593 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6594 if (alg_rid_base != algorithmic_rid_base()) {
6595 DEBUG(0, ("The value of 'algorithmic RID base' has "
6596 "changed since the LDAP\n"
6597 "database was initialised. Aborting. \n"));
6598 ldap_msgfree(result);
6599 TALLOC_FREE(alg_rid_base_string);
6600 return NT_STATUS_UNSUCCESSFUL;
6602 TALLOC_FREE(alg_rid_base_string);
6604 ldap_msgfree(result);
6606 return NT_STATUS_OK;
6609 NTSTATUS pdb_ldap_init(void)
6611 NTSTATUS nt_status;
6612 if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6613 return nt_status;
6615 /* Let pdb_nds register backends */
6616 pdb_nds_init();
6618 pdb_ipa_init();
6620 return NT_STATUS_OK;