pdb_samba_dsdb: implement pdb_samba_dsdb_enum_trusteddoms()
[bbaumbach/samba-autobuild/.git] / source3 / passdb / pdb_ldap.c
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
10
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.
15
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.
20
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/>.
23
24 */
25
26 /* TODO:
27 *  persistent connections: if using NSS LDAP, many connections are made
28 *      however, using only one within Samba would be nice
29 *  
30 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
31 *
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)
35 *
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)
38 */
39
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
44 */
45
46 #include "includes.h"
47 #include "passdb.h"
48 #include "../libcli/auth/libcli_auth.h"
49 #include "secrets.h"
50 #include "idmap_cache.h"
51 #include "../libcli/security/security.h"
52 #include "../lib/util/util_pw.h"
53 #include "lib/winbind_util.h"
54 #include "librpc/gen_ndr/idmap.h"
55 #include "lib/param/loadparm.h"
56 #include "lib/util_sid_passdb.h"
57
58 #undef DBGC_CLASS
59 #define DBGC_CLASS DBGC_PASSDB
60
61 #include <lber.h>
62 #include <ldap.h>
63
64
65 #include "smbldap.h"
66 #include "passdb/pdb_ldap.h"
67 #include "passdb/pdb_nds.h"
68 #include "passdb/pdb_ldap_util.h"
69 #include "passdb/pdb_ldap_schema.h"
70
71 /**********************************************************************
72  Simple helper function to make stuff better readable
73  **********************************************************************/
74
75 LDAP *priv2ld(struct ldapsam_privates *priv)
76 {
77         return smbldap_get_ldap(priv->smbldap_state);
78 }
79
80 /**********************************************************************
81  Get the attribute name given a user schame version.
82  **********************************************************************/
83  
84 static const char* get_userattr_key2string( int schema_ver, int key )
85 {
86         switch ( schema_ver ) {
87                 case SCHEMAVER_SAMBASAMACCOUNT:
88                         return get_attr_key2string( attrib_map_v30, key );
89
90                 default:
91                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
92                         break;
93         }
94         return NULL;
95 }
96
97 /**********************************************************************
98  Return the list of attribute names given a user schema version.
99 **********************************************************************/
100
101 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
102 {
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;
109         }
110
111         return NULL;
112 }
113
114 /**************************************************************************
115  Return the list of attribute names to delete given a user schema version.
116 **************************************************************************/
117
118 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
119                                               int schema_ver )
120 {
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;
128         }
129
130         return NULL;
131 }
132
133
134 /*******************************************************************
135  Generate the LDAP search filter for the objectclass based on the 
136  version of the schema we are using.
137 ******************************************************************/
138
139 static const char* get_objclass_filter( int schema_ver )
140 {
141         fstring objclass_filter;
142         char *result;
143
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;
152         }
153
154         result = talloc_strdup(talloc_tos(), objclass_filter);
155         SMB_ASSERT(result != NULL);
156         return result;
157 }
158
159 /*****************************************************************
160  Scan a sequence number off OpenLDAP's syncrepl contextCSN
161 ******************************************************************/
162
163 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
164 {
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;
176
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
183          */
184
185         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
186                 return ntstatus;
187         }
188
189         if (!seq_num) {
190                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
191                 return ntstatus;
192         }
193
194         if (!smbldap_has_naming_context(
195                     smbldap_get_ldap(ldap_state->smbldap_state),
196                     lp_ldap_suffix(talloc_tos()))) {
197                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
198                          "as top-level namingContext\n", lp_ldap_suffix(talloc_tos())));
199                 return ntstatus;
200         }
201
202         mem_ctx = talloc_init("ldapsam_get_seq_num");
203
204         if (mem_ctx == NULL)
205                 return NT_STATUS_NO_MEMORY;
206
207         if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
208                 ntstatus = NT_STATUS_NO_MEMORY;
209                 goto done;
210         }
211
212         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
213         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
214         if (rid > 0) {
215
216                 /* consumer syncreplCookie: */
217                 /* csn=20050126161620Z#0000001#00#00000 */
218                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
219                 attrs[1] = NULL;
220                 suffix = talloc_asprintf(mem_ctx,
221                                 "cn=syncrepl%d,%s", rid, lp_ldap_suffix(talloc_tos()));
222                 if (!suffix) {
223                         ntstatus = NT_STATUS_NO_MEMORY;
224                         goto done;
225                 }
226         } else {
227
228                 /* provider contextCSN */
229                 /* 20050126161620Z#000009#00#000000 */
230                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
231                 attrs[1] = NULL;
232                 suffix = talloc_asprintf(mem_ctx,
233                                 "cn=ldapsync,%s", lp_ldap_suffix(talloc_tos()));
234
235                 if (!suffix) {
236                         ntstatus = NT_STATUS_NO_MEMORY;
237                         goto done;
238                 }
239         }
240
241         rc = smbldap_search(ldap_state->smbldap_state, suffix,
242                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
243
244         if (rc != LDAP_SUCCESS) {
245                 goto done;
246         }
247
248         num_result = ldap_count_entries(
249                 smbldap_get_ldap(ldap_state->smbldap_state), msg);
250         if (num_result != 1) {
251                 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
252                 goto done;
253         }
254
255         entry = ldap_first_entry(
256                 smbldap_get_ldap(ldap_state->smbldap_state), msg);
257         if (entry == NULL) {
258                 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
259                 goto done;
260         }
261
262         values = ldap_get_values(
263                 smbldap_get_ldap(ldap_state->smbldap_state), entry, attrs[0]);
264         if (values == NULL) {
265                 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
266                 goto done;
267         }
268
269         num_values = ldap_count_values(values);
270         if (num_values == 0) {
271                 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
272                 goto done;
273         }
274
275         p = values[0];
276         if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
277                 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
278                 goto done;
279         }
280
281         p = tok;
282         if (!strncmp(p, "csn=", strlen("csn=")))
283                 p += strlen("csn=");
284
285         DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
286
287         *seq_num = generalized_to_unix_time(p);
288
289         /* very basic sanity check */
290         if (*seq_num <= 0) {
291                 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n", 
292                         (int)*seq_num));
293                 goto done;
294         }
295
296         ntstatus = NT_STATUS_OK;
297
298  done:
299         if (values != NULL)
300                 ldap_value_free(values);
301         if (msg != NULL)
302                 ldap_msgfree(msg);
303         if (mem_ctx)
304                 talloc_destroy(mem_ctx);
305
306         return ntstatus;
307 }
308
309 /*******************************************************************
310  Run the search by name.
311 ******************************************************************/
312
313 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
314                                           const char *user,
315                                           LDAPMessage ** result,
316                                           const char **attr)
317 {
318         char *filter = NULL;
319         char *escape_user = escape_ldap_string(talloc_tos(), user);
320         int ret = -1;
321
322         if (!escape_user) {
323                 return LDAP_NO_MEMORY;
324         }
325
326         /*
327          * in the filter expression, replace %u with the real name
328          * so in ldap filter, %u MUST exist :-)
329          */
330         filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
331                 get_objclass_filter(ldap_state->schema_ver));
332         if (!filter) {
333                 TALLOC_FREE(escape_user);
334                 return LDAP_NO_MEMORY;
335         }
336         /*
337          * have to use this here because $ is filtered out
338          * in string_sub
339          */
340
341         filter = talloc_all_string_sub(talloc_tos(),
342                                 filter, "%u", escape_user);
343         TALLOC_FREE(escape_user);
344         if (!filter) {
345                 return LDAP_NO_MEMORY;
346         }
347
348         ret = smbldap_search_suffix(ldap_state->smbldap_state,
349                         filter, attr, result);
350         TALLOC_FREE(filter);
351         return ret;
352 }
353
354 /*******************************************************************
355  Run the search by SID.
356 ******************************************************************/
357
358 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
359                                  const struct dom_sid *sid, LDAPMessage ** result,
360                                  const char **attr)
361 {
362         char *filter = NULL;
363         int rc;
364         fstring sid_string;
365
366         filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
367                 get_userattr_key2string(ldap_state->schema_ver,
368                         LDAP_ATTR_USER_SID),
369                 sid_to_fstring(sid_string, sid),
370                 get_objclass_filter(ldap_state->schema_ver));
371         if (!filter) {
372                 return LDAP_NO_MEMORY;
373         }
374
375         rc = smbldap_search_suffix(ldap_state->smbldap_state,
376                         filter, attr, result);
377
378         TALLOC_FREE(filter);
379         return rc;
380 }
381
382 /*******************************************************************
383  Delete complete object or objectclass and attrs from
384  object found in search_result depending on lp_ldap_delete_dn
385 ******************************************************************/
386
387 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
388                                 TALLOC_CTX *mem_ctx,
389                                 LDAPMessage *entry,
390                                 const char *objectclass,
391                                 const char **attrs)
392 {
393         LDAPMod **mods = NULL;
394         char *name;
395         const char *dn;
396         BerElement *ptr = NULL;
397
398         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
399         if (dn == NULL) {
400                 return LDAP_NO_MEMORY;
401         }
402
403         if (lp_ldap_delete_dn()) {
404                 return smbldap_delete(priv->smbldap_state, dn);
405         }
406
407         /* Ok, delete only the SAM attributes */
408
409         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
410              name != NULL;
411              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
412                 const char **attrib;
413
414                 /* We are only allowed to delete the attributes that
415                    really exist. */
416
417                 for (attrib = attrs; *attrib != NULL; attrib++) {
418                         if (strequal(*attrib, name)) {
419                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
420                                            "attribute %s\n", name));
421                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
422                                                 NULL);
423                         }
424                 }
425                 ldap_memfree(name);
426         }
427
428         if (ptr != NULL) {
429                 ber_free(ptr, 0);
430         }
431
432         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
433         smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
434
435         return smbldap_modify(priv->smbldap_state, dn, mods);
436 }
437
438 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
439 {
440         char *temp;
441         struct tm tm;
442
443         temp = smbldap_talloc_single_attribute(
444                 smbldap_get_ldap(ldap_state->smbldap_state), entry,
445                 get_userattr_key2string(ldap_state->schema_ver,
446                                         LDAP_ATTR_MOD_TIMESTAMP),
447                         talloc_tos());
448         if (!temp) {
449                 return (time_t) 0;
450         }
451
452         if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
453                 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
454                         (char*)temp));
455                 TALLOC_FREE(temp);
456                 return (time_t) 0;
457         }
458         TALLOC_FREE(temp);
459         tzset();
460         return timegm(&tm);
461 }
462
463 /**********************************************************************
464  Initialize struct samu from an LDAP query.
465  (Based on init_sam_from_buffer in pdb_tdb.c)
466 *********************************************************************/
467
468 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
469                                 struct samu * sampass,
470                                 LDAPMessage * entry)
471 {
472         time_t  logon_time,
473                         logoff_time,
474                         kickoff_time,
475                         pass_last_set_time,
476                         pass_can_change_time,
477                         ldap_entry_time,
478                         bad_password_time;
479         char *username = NULL,
480                         *domain = NULL,
481                         *nt_username = NULL,
482                         *fullname = NULL,
483                         *homedir = NULL,
484                         *dir_drive = NULL,
485                         *logon_script = NULL,
486                         *profile_path = NULL,
487                         *acct_desc = NULL,
488                         *workstations = NULL,
489                         *munged_dial = NULL;
490         uint32_t                user_rid;
491         uint8_t         smblmpwd[LM_HASH_LEN],
492                         smbntpwd[NT_HASH_LEN];
493         bool            use_samba_attrs = True;
494         uint32_t                acct_ctrl = 0;
495         uint16_t                logon_divs;
496         uint16_t                bad_password_count = 0,
497                         logon_count = 0;
498         uint32_t hours_len;
499         uint8_t         hours[MAX_HOURS_LEN];
500         char *temp = NULL;
501         struct login_cache cache_entry;
502         uint32_t                pwHistLen;
503         bool expand_explicit = lp_passdb_expand_explicit();
504         bool ret = false;
505         TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
506
507         if (!ctx) {
508                 return false;
509         }
510         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
511                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
512                 goto fn_exit;
513         }
514
515         if (priv2ld(ldap_state) == NULL) {
516                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
517                           "ldap_struct is NULL!\n"));
518                 goto fn_exit;
519         }
520
521         if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
522                                         entry,
523                                         "uid",
524                                         ctx))) {
525                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
526                           "this user!\n"));
527                 goto fn_exit;
528         }
529
530         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
531
532         nt_username = talloc_strdup(ctx, username);
533         if (!nt_username) {
534                 goto fn_exit;
535         }
536
537         domain = talloc_strdup(ctx, ldap_state->domain_name);
538         if (!domain) {
539                 goto fn_exit;
540         }
541
542         pdb_set_username(sampass, username, PDB_SET);
543
544         pdb_set_domain(sampass, domain, PDB_DEFAULT);
545         pdb_set_nt_username(sampass, nt_username, PDB_SET);
546
547         /* deal with different attributes between the schema first */
548
549         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
550                 if ((temp = smbldap_talloc_single_attribute(
551                                 smbldap_get_ldap(ldap_state->smbldap_state),
552                                 entry,
553                                 get_userattr_key2string(ldap_state->schema_ver,
554                                         LDAP_ATTR_USER_SID),
555                                 ctx))!=NULL) {
556                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
557                 }
558         } else {
559                 if ((temp = smbldap_talloc_single_attribute(
560                                 smbldap_get_ldap(ldap_state->smbldap_state),
561                                 entry,
562                                 get_userattr_key2string(ldap_state->schema_ver,
563                                         LDAP_ATTR_USER_RID),
564                                 ctx))!=NULL) {
565                         user_rid = (uint32_t)atol(temp);
566                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
567                 }
568         }
569
570         if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
571                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
572                         get_userattr_key2string(ldap_state->schema_ver,
573                                 LDAP_ATTR_USER_SID),
574                         get_userattr_key2string(ldap_state->schema_ver,
575                                 LDAP_ATTR_USER_RID),
576                         username));
577                 return False;
578         }
579
580         temp = smbldap_talloc_single_attribute(
581                         smbldap_get_ldap(ldap_state->smbldap_state),
582                         entry,
583                         get_userattr_key2string(ldap_state->schema_ver,
584                                 LDAP_ATTR_PWD_LAST_SET),
585                         ctx);
586         if (temp) {
587                 pass_last_set_time = (time_t) atol(temp);
588                 pdb_set_pass_last_set_time(sampass,
589                                 pass_last_set_time, PDB_SET);
590         }
591
592         temp = smbldap_talloc_single_attribute(
593                         smbldap_get_ldap(ldap_state->smbldap_state),
594                         entry,
595                         get_userattr_key2string(ldap_state->schema_ver,
596                                 LDAP_ATTR_LOGON_TIME),
597                         ctx);
598         if (temp) {
599                 logon_time = (time_t) atol(temp);
600                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
601         }
602
603         temp = smbldap_talloc_single_attribute(
604                         smbldap_get_ldap(ldap_state->smbldap_state),
605                         entry,
606                         get_userattr_key2string(ldap_state->schema_ver,
607                                 LDAP_ATTR_LOGOFF_TIME),
608                         ctx);
609         if (temp) {
610                 logoff_time = (time_t) atol(temp);
611                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
612         }
613
614         temp = smbldap_talloc_single_attribute(
615                         smbldap_get_ldap(ldap_state->smbldap_state),
616                         entry,
617                         get_userattr_key2string(ldap_state->schema_ver,
618                                 LDAP_ATTR_KICKOFF_TIME),
619                         ctx);
620         if (temp) {
621                 kickoff_time = (time_t) atol(temp);
622                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
623         }
624
625         temp = smbldap_talloc_single_attribute(
626                         smbldap_get_ldap(ldap_state->smbldap_state),
627                         entry,
628                         get_userattr_key2string(ldap_state->schema_ver,
629                                 LDAP_ATTR_PWD_CAN_CHANGE),
630                         ctx);
631         if (temp) {
632                 pass_can_change_time = (time_t) atol(temp);
633                 pdb_set_pass_can_change_time(sampass,
634                                 pass_can_change_time, PDB_SET);
635         }
636
637         /* recommend that 'gecos' and 'displayName' should refer to the same
638          * attribute OID.  userFullName depreciated, only used by Samba
639          * primary rules of LDAP: don't make a new attribute when one is already defined
640          * that fits your needs; using cn then displayName rather than 'userFullName'
641          */
642
643         fullname = smbldap_talloc_single_attribute(
644                         smbldap_get_ldap(ldap_state->smbldap_state),
645                         entry,
646                         get_userattr_key2string(ldap_state->schema_ver,
647                                 LDAP_ATTR_DISPLAY_NAME),
648                         ctx);
649         if (fullname) {
650                 pdb_set_fullname(sampass, fullname, PDB_SET);
651         } else {
652                 fullname = smbldap_talloc_single_attribute(
653                                 smbldap_get_ldap(ldap_state->smbldap_state),
654                                 entry,
655                                 get_userattr_key2string(ldap_state->schema_ver,
656                                         LDAP_ATTR_CN),
657                                 ctx);
658                 if (fullname) {
659                         pdb_set_fullname(sampass, fullname, PDB_SET);
660                 }
661         }
662
663         dir_drive = smbldap_talloc_single_attribute(
664                         smbldap_get_ldap(ldap_state->smbldap_state),
665                         entry,
666                         get_userattr_key2string(ldap_state->schema_ver,
667                                 LDAP_ATTR_HOME_DRIVE),
668                         ctx);
669         if (dir_drive) {
670                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
671         } else {
672                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
673         }
674
675         homedir = smbldap_talloc_single_attribute(
676                         smbldap_get_ldap(ldap_state->smbldap_state),
677                         entry,
678                         get_userattr_key2string(ldap_state->schema_ver,
679                                 LDAP_ATTR_HOME_PATH),
680                         ctx);
681         if (homedir) {
682                 if (expand_explicit) {
683                         homedir = talloc_sub_basic(ctx,
684                                                 username,
685                                                 domain,
686                                                 homedir);
687                         if (!homedir) {
688                                 goto fn_exit;
689                         }
690                 }
691                 pdb_set_homedir(sampass, homedir, PDB_SET);
692         } else {
693                 pdb_set_homedir(sampass,
694                         talloc_sub_basic(ctx, username, domain,
695                                          lp_logon_home()),
696                         PDB_DEFAULT);
697         }
698
699         logon_script = smbldap_talloc_single_attribute(
700                         smbldap_get_ldap(ldap_state->smbldap_state),
701                         entry,
702                         get_userattr_key2string(ldap_state->schema_ver,
703                                 LDAP_ATTR_LOGON_SCRIPT),
704                         ctx);
705         if (logon_script) {
706                 if (expand_explicit) {
707                         logon_script = talloc_sub_basic(ctx,
708                                                 username,
709                                                 domain,
710                                                 logon_script);
711                         if (!logon_script) {
712                                 goto fn_exit;
713                         }
714                 }
715                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
716         } else {
717                 pdb_set_logon_script(sampass,
718                         talloc_sub_basic(ctx, username, domain,
719                                          lp_logon_script()),
720                         PDB_DEFAULT );
721         }
722
723         profile_path = smbldap_talloc_single_attribute(
724                         smbldap_get_ldap(ldap_state->smbldap_state),
725                         entry,
726                         get_userattr_key2string(ldap_state->schema_ver,
727                                 LDAP_ATTR_PROFILE_PATH),
728                         ctx);
729         if (profile_path) {
730                 if (expand_explicit) {
731                         profile_path = talloc_sub_basic(ctx,
732                                                 username,
733                                                 domain,
734                                                 profile_path);
735                         if (!profile_path) {
736                                 goto fn_exit;
737                         }
738                 }
739                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
740         } else {
741                 pdb_set_profile_path(sampass,
742                         talloc_sub_basic(ctx, username, domain,
743                                           lp_logon_path()),
744                         PDB_DEFAULT );
745         }
746
747         acct_desc = smbldap_talloc_single_attribute(
748                         smbldap_get_ldap(ldap_state->smbldap_state),
749                         entry,
750                         get_userattr_key2string(ldap_state->schema_ver,
751                                 LDAP_ATTR_DESC),
752                         ctx);
753         if (acct_desc) {
754                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
755         }
756
757         workstations = smbldap_talloc_single_attribute(
758                         smbldap_get_ldap(ldap_state->smbldap_state),
759                         entry,
760                         get_userattr_key2string(ldap_state->schema_ver,
761                                 LDAP_ATTR_USER_WKS),
762                         ctx);
763         if (workstations) {
764                 pdb_set_workstations(sampass, workstations, PDB_SET);
765         }
766
767         munged_dial = smbldap_talloc_single_attribute(
768                         smbldap_get_ldap(ldap_state->smbldap_state),
769                         entry,
770                         get_userattr_key2string(ldap_state->schema_ver,
771                                 LDAP_ATTR_MUNGED_DIAL),
772                         ctx);
773         if (munged_dial) {
774                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
775         }
776
777         /* FIXME: hours stuff should be cleaner */
778
779         logon_divs = 168;
780         hours_len = 21;
781         memset(hours, 0xff, hours_len);
782
783         if (ldap_state->is_nds_ldap) {
784                 char *user_dn;
785                 size_t pwd_len;
786                 char clear_text_pw[512];
787
788                 /* Make call to Novell eDirectory ldap extension to get clear text password.
789                         NOTE: This will only work if we have an SSL connection to eDirectory. */
790                 user_dn = smbldap_talloc_dn(
791                         ctx, smbldap_get_ldap(ldap_state->smbldap_state),
792                         entry);
793                 if (user_dn != NULL) {
794                         DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
795
796                         pwd_len = sizeof(clear_text_pw);
797                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
798                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
799                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
800                                         TALLOC_FREE(user_dn);
801                                         return False;
802                                 }
803                                 ZERO_STRUCT(smblmpwd);
804                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
805                                         TALLOC_FREE(user_dn);
806                                         return False;
807                                 }
808                                 ZERO_STRUCT(smbntpwd);
809                                 use_samba_attrs = False;
810                         }
811
812                         TALLOC_FREE(user_dn);
813
814                 } else {
815                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
816                 }
817         }
818
819         if (use_samba_attrs) {
820                 temp = smbldap_talloc_single_attribute(
821                                 smbldap_get_ldap(ldap_state->smbldap_state),
822                                 entry,
823                                 get_userattr_key2string(ldap_state->schema_ver,
824                                         LDAP_ATTR_LMPW),
825                                 ctx);
826                 if (temp) {
827                         pdb_gethexpwd(temp, smblmpwd);
828                         memset((char *)temp, '\0', strlen(temp)+1);
829                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
830                                 goto fn_exit;
831                         }
832                         ZERO_STRUCT(smblmpwd);
833                 }
834
835                 temp = smbldap_talloc_single_attribute(
836                                 smbldap_get_ldap(ldap_state->smbldap_state),
837                                 entry,
838                                 get_userattr_key2string(ldap_state->schema_ver,
839                                         LDAP_ATTR_NTPW),
840                                 ctx);
841                 if (temp) {
842                         pdb_gethexpwd(temp, smbntpwd);
843                         memset((char *)temp, '\0', strlen(temp)+1);
844                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
845                                 goto fn_exit;
846                         }
847                         ZERO_STRUCT(smbntpwd);
848                 }
849         }
850
851         pwHistLen = 0;
852
853         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
854         if (pwHistLen > 0){
855                 uint8_t *pwhist = NULL;
856                 int i;
857                 char *history_string = talloc_array(ctx, char,
858                                                 MAX_PW_HISTORY_LEN*64);
859
860                 if (!history_string) {
861                         goto fn_exit;
862                 }
863
864                 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
865
866                 pwhist = talloc_zero_array(ctx, uint8_t,
867                                            pwHistLen * PW_HISTORY_ENTRY_LEN);
868                 if (pwhist == NULL) {
869                         DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
870                         goto fn_exit;
871                 }
872
873                 if (smbldap_get_single_attribute(
874                                 smbldap_get_ldap(ldap_state->smbldap_state),
875                                 entry,
876                                 get_userattr_key2string(ldap_state->schema_ver,
877                                         LDAP_ATTR_PWD_HISTORY),
878                                 history_string,
879                                 MAX_PW_HISTORY_LEN*64)) {
880                         bool hex_failed = false;
881                         for (i = 0; i < pwHistLen; i++){
882                                 /* Get the 16 byte salt. */
883                                 if (!pdb_gethexpwd(&history_string[i*64],
884                                         &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
885                                         hex_failed = true;
886                                         break;
887                                 }
888                                 /* Get the 16 byte MD5 hash of salt+passwd. */
889                                 if (!pdb_gethexpwd(&history_string[(i*64)+32],
890                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
891                                                 PW_HISTORY_SALT_LEN])) {
892                                         hex_failed = True;
893                                         break;
894                                 }
895                         }
896                         if (hex_failed) {
897                                 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
898                                         username));
899                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
900                         }
901                 }
902                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
903                         goto fn_exit;
904                 }
905         }
906
907         temp = smbldap_talloc_single_attribute(
908                         smbldap_get_ldap(ldap_state->smbldap_state),
909                         entry,
910                         get_userattr_key2string(ldap_state->schema_ver,
911                                 LDAP_ATTR_ACB_INFO),
912                         ctx);
913         if (temp) {
914                 acct_ctrl = pdb_decode_acct_ctrl(temp);
915
916                 if (acct_ctrl == 0) {
917                         acct_ctrl |= ACB_NORMAL;
918                 }
919
920                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
921         } else {
922                 acct_ctrl |= ACB_NORMAL;
923         }
924
925         pdb_set_hours_len(sampass, hours_len, PDB_SET);
926         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
927
928         temp = smbldap_talloc_single_attribute(
929                         smbldap_get_ldap(ldap_state->smbldap_state),
930                         entry,
931                         get_userattr_key2string(ldap_state->schema_ver,
932                                 LDAP_ATTR_BAD_PASSWORD_COUNT),
933                         ctx);
934         if (temp) {
935                 bad_password_count = (uint32_t) atol(temp);
936                 pdb_set_bad_password_count(sampass,
937                                 bad_password_count, PDB_SET);
938         }
939
940         temp = smbldap_talloc_single_attribute(
941                         smbldap_get_ldap(ldap_state->smbldap_state),
942                         entry,
943                         get_userattr_key2string(ldap_state->schema_ver,
944                                 LDAP_ATTR_BAD_PASSWORD_TIME),
945                         ctx);
946         if (temp) {
947                 bad_password_time = (time_t) atol(temp);
948                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
949         }
950
951
952         temp = smbldap_talloc_single_attribute(
953                         smbldap_get_ldap(ldap_state->smbldap_state),
954                         entry,
955                         get_userattr_key2string(ldap_state->schema_ver,
956                                 LDAP_ATTR_LOGON_COUNT),
957                         ctx);
958         if (temp) {
959                 logon_count = (uint32_t) atol(temp);
960                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
961         }
962
963         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
964
965         temp = smbldap_talloc_single_attribute(
966                         smbldap_get_ldap(ldap_state->smbldap_state),
967                         entry,
968                         get_userattr_key2string(ldap_state->schema_ver,
969                                 LDAP_ATTR_LOGON_HOURS),
970                         ctx);
971         if (temp) {
972                 pdb_gethexhours(temp, hours);
973                 memset((char *)temp, '\0', strlen(temp) +1);
974                 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
975                 ZERO_STRUCT(hours);
976         }
977
978         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
979                 struct passwd unix_pw;
980                 bool have_uid = false;
981                 bool have_gid = false;
982                 struct dom_sid mapped_gsid;
983                 const struct dom_sid *primary_gsid;
984                 struct unixid id;
985
986                 ZERO_STRUCT(unix_pw);
987
988                 unix_pw.pw_name = username;
989                 unix_pw.pw_passwd = discard_const_p(char, "x");
990
991                 temp = smbldap_talloc_single_attribute(
992                                 priv2ld(ldap_state),
993                                 entry,
994                                 "uidNumber",
995                                 ctx);
996                 if (temp) {
997                         /* We've got a uid, feed the cache */
998                         unix_pw.pw_uid = strtoul(temp, NULL, 10);
999                         have_uid = true;
1000                 }
1001                 temp = smbldap_talloc_single_attribute(
1002                                 priv2ld(ldap_state),
1003                                 entry,
1004                                 "gidNumber",
1005                                 ctx);
1006                 if (temp) {
1007                         /* We've got a uid, feed the cache */
1008                         unix_pw.pw_gid = strtoul(temp, NULL, 10);
1009                         have_gid = true;
1010                 }
1011                 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1012                                 priv2ld(ldap_state),
1013                                 entry,
1014                                 "gecos",
1015                                 ctx);
1016                 if (unix_pw.pw_gecos == NULL) {
1017                         unix_pw.pw_gecos = fullname;
1018                 }
1019                 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1020                                 priv2ld(ldap_state),
1021                                 entry,
1022                                 "homeDirectory",
1023                                 ctx);
1024                 if (unix_pw.pw_dir == NULL) {
1025                         unix_pw.pw_dir = discard_const_p(char, "");
1026                 }
1027                 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1028                                 priv2ld(ldap_state),
1029                                 entry,
1030                                 "loginShell",
1031                                 ctx);
1032                 if (unix_pw.pw_shell == NULL) {
1033                         unix_pw.pw_shell = discard_const_p(char, "");
1034                 }
1035
1036                 if (have_uid && have_gid) {
1037                         sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1038                 } else {
1039                         sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1040                 }
1041
1042                 if (sampass->unix_pw == NULL) {
1043                         DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1044                                  pdb_get_username(sampass)));
1045                         goto fn_exit;
1046                 }
1047
1048                 id.id = sampass->unix_pw->pw_uid;
1049                 id.type = ID_TYPE_UID;
1050
1051                 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1052
1053                 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1054                 primary_gsid = pdb_get_group_sid(sampass);
1055                 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1056                         id.id = sampass->unix_pw->pw_gid;
1057                         id.type = ID_TYPE_GID;
1058
1059                         idmap_cache_set_sid2unixid(primary_gsid, &id);
1060                 }
1061         }
1062
1063         /* check the timestamp of the cache vs ldap entry */
1064         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1065                                                             entry))) {
1066                 ret = true;
1067                 goto fn_exit;
1068         }
1069
1070         /* see if we have newer updates */
1071         if (!login_cache_read(sampass, &cache_entry)) {
1072                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1073                            (unsigned int)pdb_get_bad_password_count(sampass),
1074                            (unsigned int)pdb_get_bad_password_time(sampass)));
1075                 ret = true;
1076                 goto fn_exit;
1077         }
1078
1079         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1080                   (unsigned int)ldap_entry_time,
1081                   (unsigned int)cache_entry.entry_timestamp,
1082                   (unsigned int)cache_entry.bad_password_time));
1083
1084         if (ldap_entry_time > cache_entry.entry_timestamp) {
1085                 /* cache is older than directory , so
1086                    we need to delete the entry but allow the
1087                    fields to be written out */
1088                 login_cache_delentry(sampass);
1089         } else {
1090                 /* read cache in */
1091                 pdb_set_acct_ctrl(sampass,
1092                                   pdb_get_acct_ctrl(sampass) |
1093                                   (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1094                                   PDB_SET);
1095                 pdb_set_bad_password_count(sampass,
1096                                            cache_entry.bad_password_count,
1097                                            PDB_SET);
1098                 pdb_set_bad_password_time(sampass,
1099                                           cache_entry.bad_password_time,
1100                                           PDB_SET);
1101         }
1102
1103         ret = true;
1104
1105   fn_exit:
1106
1107         TALLOC_FREE(ctx);
1108         return ret;
1109 }
1110
1111 /**********************************************************************
1112  Initialize the ldap db from a struct samu. Called on update.
1113  (Based on init_buffer_from_sam in pdb_tdb.c)
1114 *********************************************************************/
1115
1116 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1117                                 LDAPMessage *existing,
1118                                 LDAPMod *** mods, struct samu * sampass,
1119                                 bool (*need_update)(const struct samu *,
1120                                                     enum pdb_elements))
1121 {
1122         char *temp = NULL;
1123
1124         if (mods == NULL || sampass == NULL) {
1125                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1126                 return False;
1127         }
1128
1129         *mods = NULL;
1130
1131         /*
1132          * took out adding "objectclass: sambaAccount"
1133          * do this on a per-mod basis
1134          */
1135         if (need_update(sampass, PDB_USERNAME)) {
1136                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1137                                  existing, mods,
1138                                  "uid", pdb_get_username(sampass));
1139                 if (ldap_state->is_nds_ldap) {
1140                         smbldap_make_mod(
1141                                 smbldap_get_ldap(ldap_state->smbldap_state),
1142                                 existing, mods,
1143                                 "cn", pdb_get_username(sampass));
1144                         smbldap_make_mod(
1145                                 smbldap_get_ldap(ldap_state->smbldap_state),
1146                                 existing, mods,
1147                                 "sn", pdb_get_username(sampass));
1148                 }
1149         }
1150
1151         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1152
1153         /* only update the RID if we actually need to */
1154         if (need_update(sampass, PDB_USERSID)) {
1155                 fstring sid_string;
1156                 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1157
1158                 switch ( ldap_state->schema_ver ) {
1159                         case SCHEMAVER_SAMBASAMACCOUNT:
1160                                 smbldap_make_mod(
1161                                         smbldap_get_ldap(
1162                                                 ldap_state->smbldap_state),
1163                                         existing, mods,
1164                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
1165                                         sid_to_fstring(sid_string, user_sid));
1166                                 break;
1167
1168                         default:
1169                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1170                                 break;
1171                 }
1172         }
1173
1174         /* we don't need to store the primary group RID - so leaving it
1175            'free' to hang off the unix primary group makes life easier */
1176
1177         if (need_update(sampass, PDB_GROUPSID)) {
1178                 fstring sid_string;
1179                 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1180
1181                 switch ( ldap_state->schema_ver ) {
1182                         case SCHEMAVER_SAMBASAMACCOUNT:
1183                                 smbldap_make_mod(
1184                                         smbldap_get_ldap(
1185                                                 ldap_state->smbldap_state),
1186                                         existing, mods,
1187                                         get_userattr_key2string(ldap_state->schema_ver, 
1188                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1189                                 break;
1190
1191                         default:
1192                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1193                                 break;
1194                 }
1195
1196         }
1197
1198         /* displayName, cn, and gecos should all be the same
1199          *  most easily accomplished by giving them the same OID
1200          *  gecos isn't set here b/c it should be handled by the
1201          *  add-user script
1202          *  We change displayName only and fall back to cn if
1203          *  it does not exist.
1204          */
1205
1206         if (need_update(sampass, PDB_FULLNAME))
1207                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1208                                  existing, mods,
1209                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1210                         pdb_get_fullname(sampass));
1211
1212         if (need_update(sampass, PDB_ACCTDESC))
1213                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1214                                  existing, mods,
1215                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1216                         pdb_get_acct_desc(sampass));
1217
1218         if (need_update(sampass, PDB_WORKSTATIONS))
1219                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1220                                  existing, mods,
1221                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1222                         pdb_get_workstations(sampass));
1223
1224         if (need_update(sampass, PDB_MUNGEDDIAL))
1225                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1226                                  existing, mods,
1227                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1228                         pdb_get_munged_dial(sampass));
1229
1230         if (need_update(sampass, PDB_SMBHOME))
1231                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1232                                  existing, mods,
1233                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1234                         pdb_get_homedir(sampass));
1235
1236         if (need_update(sampass, PDB_DRIVE))
1237                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1238                                  existing, mods,
1239                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1240                         pdb_get_dir_drive(sampass));
1241
1242         if (need_update(sampass, PDB_LOGONSCRIPT))
1243                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1244                                  existing, mods,
1245                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1246                         pdb_get_logon_script(sampass));
1247
1248         if (need_update(sampass, PDB_PROFILE))
1249                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1250                                  existing, mods,
1251                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1252                         pdb_get_profile_path(sampass));
1253
1254         if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1255                 return false;
1256         }
1257         if (need_update(sampass, PDB_LOGONTIME))
1258                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1259                                  existing, mods,
1260                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1261         SAFE_FREE(temp);
1262
1263         if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1264                 return false;
1265         }
1266         if (need_update(sampass, PDB_LOGOFFTIME))
1267                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1268                                  existing, mods,
1269                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1270         SAFE_FREE(temp);
1271
1272         if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1273                 return false;
1274         }
1275         if (need_update(sampass, PDB_KICKOFFTIME))
1276                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1277                                  existing, mods,
1278                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1279         SAFE_FREE(temp);
1280
1281         if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1282                 return false;
1283         }
1284         if (need_update(sampass, PDB_CANCHANGETIME))
1285                 smbldap_make_mod(smbldap_get_ldap(ldap_state->smbldap_state),
1286                                  existing, mods,
1287                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1288         SAFE_FREE(temp);
1289
1290         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1291                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1292
1293                 if (need_update(sampass, PDB_LMPASSWD)) {
1294                         const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1295                         if (lm_pw) {
1296                                 char pwstr[34];
1297                                 pdb_sethexpwd(pwstr, lm_pw,
1298                                               pdb_get_acct_ctrl(sampass));
1299                                 smbldap_make_mod(
1300                                         smbldap_get_ldap(
1301                                                 ldap_state->smbldap_state),
1302                                         existing, mods,
1303                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1304                                                  pwstr);
1305                         } else {
1306                                 smbldap_make_mod(
1307                                         smbldap_get_ldap(
1308                                                 ldap_state->smbldap_state),
1309                                         existing, mods,
1310                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1311                                                  NULL);
1312                         }
1313                 }
1314                 if (need_update(sampass, PDB_NTPASSWD)) {
1315                         const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1316                         if (nt_pw) {
1317                                 char pwstr[34];
1318                                 pdb_sethexpwd(pwstr, nt_pw,
1319                                               pdb_get_acct_ctrl(sampass));
1320                                 smbldap_make_mod(
1321                                         smbldap_get_ldap(
1322                                                 ldap_state->smbldap_state),
1323                                         existing, mods,
1324                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1325                                                  pwstr);
1326                         } else {
1327                                 smbldap_make_mod(
1328                                         smbldap_get_ldap(
1329                                                 ldap_state->smbldap_state),
1330                                         existing, mods,
1331                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1332                                                  NULL);
1333                         }
1334                 }
1335
1336                 if (need_update(sampass, PDB_PWHISTORY)) {
1337                         char *pwstr = NULL;
1338                         uint32_t pwHistLen = 0;
1339                         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1340
1341                         pwstr = SMB_MALLOC_ARRAY(char, 1024);
1342                         if (!pwstr) {
1343                                 return false;
1344                         }
1345                         if (pwHistLen == 0) {
1346                                 /* Remove any password history from the LDAP store. */
1347                                 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1348                                 pwstr[64] = '\0';
1349                         } else {
1350                                 int i;
1351                                 uint32_t currHistLen = 0;
1352                                 const uint8_t *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1353                                 if (pwhist != NULL) {
1354                                         /* We can only store (1024-1/64 password history entries. */
1355                                         pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1356                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1357                                                 /* Store the salt. */
1358                                                 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1359                                                 /* Followed by the md5 hash of salt + md4 hash */
1360                                                 pdb_sethexpwd(&pwstr[(i*64)+32],
1361                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1362                                                 DEBUG(100, ("pwstr=%s\n", pwstr));
1363                                         }
1364                                 }
1365                         }
1366                         smbldap_make_mod(
1367                                 smbldap_get_ldap(ldap_state->smbldap_state),
1368                                 existing, mods,
1369                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1370                                          pwstr);
1371                         SAFE_FREE(pwstr);
1372                 }
1373
1374                 if (need_update(sampass, PDB_PASSLASTSET)) {
1375                         if (asprintf(&temp, "%li",
1376                                 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1377                                 return false;
1378                         }
1379                         smbldap_make_mod(
1380                                 smbldap_get_ldap(ldap_state->smbldap_state),
1381                                 existing, mods,
1382                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1383                                 temp);
1384                         SAFE_FREE(temp);
1385                 }
1386         }
1387
1388         if (need_update(sampass, PDB_HOURS)) {
1389                 const uint8_t *hours = pdb_get_hours(sampass);
1390                 if (hours) {
1391                         char hourstr[44];
1392                         pdb_sethexhours(hourstr, hours);
1393                         smbldap_make_mod(
1394                                 smbldap_get_ldap(ldap_state->smbldap_state),
1395                                 existing,
1396                                 mods,
1397                                 get_userattr_key2string(ldap_state->schema_ver,
1398                                                 LDAP_ATTR_LOGON_HOURS),
1399                                 hourstr);
1400                 }
1401         }
1402
1403         if (need_update(sampass, PDB_ACCTCTRL))
1404                 smbldap_make_mod(
1405                         smbldap_get_ldap(ldap_state->smbldap_state),
1406                         existing, mods,
1407                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1408                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1409
1410         /* password lockout cache:
1411            - If we are now autolocking or clearing, we write to ldap
1412            - If we are clearing, we delete the cache entry
1413            - If the count is > 0, we update the cache
1414
1415            This even means when autolocking, we cache, just in case the
1416            update doesn't work, and we have to cache the autolock flag */
1417
1418         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1419             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1420                 uint16_t badcount = pdb_get_bad_password_count(sampass);
1421                 time_t badtime = pdb_get_bad_password_time(sampass);
1422                 uint32_t pol;
1423                 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1424
1425                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1426                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1427
1428                 if ((badcount >= pol) || (badcount == 0)) {
1429                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1430                                 (unsigned int)badcount, (unsigned int)badtime));
1431                         if (asprintf(&temp, "%li", (long)badcount) < 0) {
1432                                 return false;
1433                         }
1434                         smbldap_make_mod(
1435                                 smbldap_get_ldap(ldap_state->smbldap_state),
1436                                 existing, mods,
1437                                 get_userattr_key2string(
1438                                         ldap_state->schema_ver,
1439                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1440                                 temp);
1441                         SAFE_FREE(temp);
1442
1443                         if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1444                                 return false;
1445                         }
1446                         smbldap_make_mod(
1447                                 smbldap_get_ldap(ldap_state->smbldap_state),
1448                                 existing, mods,
1449                                 get_userattr_key2string(
1450                                         ldap_state->schema_ver,
1451                                         LDAP_ATTR_BAD_PASSWORD_TIME),
1452                                 temp);
1453                         SAFE_FREE(temp);
1454                 }
1455                 if (badcount == 0) {
1456                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1457                         login_cache_delentry(sampass);
1458                 } else {
1459                         struct login_cache cache_entry;
1460
1461                         cache_entry.entry_timestamp = time(NULL);
1462                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1463                         cache_entry.bad_password_count = badcount;
1464                         cache_entry.bad_password_time = badtime;
1465
1466                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1467                         login_cache_write(sampass, &cache_entry);
1468                 }
1469         }
1470
1471         return True;
1472 }
1473
1474 /**********************************************************************
1475  End enumeration of the LDAP password list.
1476 *********************************************************************/
1477
1478 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1479 {
1480         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1481         if (ldap_state->result) {
1482                 ldap_msgfree(ldap_state->result);
1483                 ldap_state->result = NULL;
1484         }
1485 }
1486
1487 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1488                         const char *new_attr)
1489 {
1490         int i;
1491
1492         if (new_attr == NULL) {
1493                 return;
1494         }
1495
1496         for (i=0; (*attr_list)[i] != NULL; i++) {
1497                 ;
1498         }
1499
1500         (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1501                                             const char *,  i+2);
1502         SMB_ASSERT((*attr_list) != NULL);
1503         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1504         (*attr_list)[i+1] = NULL;
1505 }
1506
1507 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1508                                         const char ***attr_list)
1509 {
1510         append_attr(mem_ctx, attr_list, "uidNumber");
1511         append_attr(mem_ctx, attr_list, "gidNumber");
1512         append_attr(mem_ctx, attr_list, "homeDirectory");
1513         append_attr(mem_ctx, attr_list, "loginShell");
1514         append_attr(mem_ctx, attr_list, "gecos");
1515 }
1516
1517 /**********************************************************************
1518 Get struct samu entry from LDAP by username.
1519 *********************************************************************/
1520
1521 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1522 {
1523         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1524         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1525         LDAPMessage *result = NULL;
1526         LDAPMessage *entry = NULL;
1527         int count;
1528         const char ** attr_list;
1529         int rc;
1530
1531         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1532         append_attr(user, &attr_list,
1533                     get_userattr_key2string(ldap_state->schema_ver,
1534                                             LDAP_ATTR_MOD_TIMESTAMP));
1535         ldapsam_add_unix_attributes(user, &attr_list);
1536         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1537                                            attr_list);
1538         TALLOC_FREE( attr_list );
1539
1540         if ( rc != LDAP_SUCCESS ) 
1541                 return NT_STATUS_NO_SUCH_USER;
1542
1543         count = ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
1544                                    result);
1545
1546         if (count < 1) {
1547                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1548                 ldap_msgfree(result);
1549                 return NT_STATUS_NO_SUCH_USER;
1550         } else if (count > 1) {
1551                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1552                 ldap_msgfree(result);
1553                 return NT_STATUS_NO_SUCH_USER;
1554         }
1555
1556         entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
1557                                  result);
1558         if (entry) {
1559                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1560                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1561                         ldap_msgfree(result);
1562                         return NT_STATUS_NO_SUCH_USER;
1563                 }
1564                 pdb_set_backend_private_data(user, result, NULL,
1565                                              my_methods, PDB_CHANGED);
1566                 smbldap_talloc_autofree_ldapmsg(user, result);
1567                 ret = NT_STATUS_OK;
1568         } else {
1569                 ldap_msgfree(result);
1570         }
1571         return ret;
1572 }
1573
1574 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1575                                    const struct dom_sid *sid, LDAPMessage **result)
1576 {
1577         int rc = -1;
1578         const char ** attr_list;
1579
1580         switch ( ldap_state->schema_ver ) {
1581                 case SCHEMAVER_SAMBASAMACCOUNT: {
1582                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1583                         if (tmp_ctx == NULL) {
1584                                 return LDAP_NO_MEMORY;
1585                         }
1586
1587                         attr_list = get_userattr_list(tmp_ctx,
1588                                                       ldap_state->schema_ver);
1589                         append_attr(tmp_ctx, &attr_list,
1590                                     get_userattr_key2string(
1591                                             ldap_state->schema_ver,
1592                                             LDAP_ATTR_MOD_TIMESTAMP));
1593                         ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1594                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1595                                                           result, attr_list);
1596                         TALLOC_FREE(tmp_ctx);
1597
1598                         if ( rc != LDAP_SUCCESS ) 
1599                                 return rc;
1600                         break;
1601                 }
1602
1603                 default:
1604                         DEBUG(0,("Invalid schema version specified\n"));
1605                         break;
1606         }
1607         return rc;
1608 }
1609
1610 /**********************************************************************
1611  Get struct samu entry from LDAP by SID.
1612 *********************************************************************/
1613
1614 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1615 {
1616         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1617         LDAPMessage *result = NULL;
1618         LDAPMessage *entry = NULL;
1619         int count;
1620         int rc;
1621
1622         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1623                                           sid, &result); 
1624         if (rc != LDAP_SUCCESS)
1625                 return NT_STATUS_NO_SUCH_USER;
1626
1627         count = ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
1628                                    result);
1629
1630         if (count < 1) {
1631                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1632                           "count=%d\n", sid_string_dbg(sid), count));
1633                 ldap_msgfree(result);
1634                 return NT_STATUS_NO_SUCH_USER;
1635         }  else if (count > 1) {
1636                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1637                           "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1638                           count));
1639                 ldap_msgfree(result);
1640                 return NT_STATUS_NO_SUCH_USER;
1641         }
1642
1643         entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
1644                                  result);
1645         if (!entry) {
1646                 ldap_msgfree(result);
1647                 return NT_STATUS_NO_SUCH_USER;
1648         }
1649
1650         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1651                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1652                 ldap_msgfree(result);
1653                 return NT_STATUS_NO_SUCH_USER;
1654         }
1655
1656         pdb_set_backend_private_data(user, result, NULL,
1657                                      my_methods, PDB_CHANGED);
1658         smbldap_talloc_autofree_ldapmsg(user, result);
1659         return NT_STATUS_OK;
1660 }       
1661
1662 /********************************************************************
1663  Do the actual modification - also change a plaintext passord if 
1664  it it set.
1665 **********************************************************************/
1666
1667 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1668                                      struct samu *newpwd, char *dn,
1669                                      LDAPMod **mods, int ldap_op, 
1670                                      bool (*need_update)(const struct samu *, enum pdb_elements))
1671 {
1672         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1673         int rc;
1674
1675         if (!newpwd || !dn) {
1676                 return NT_STATUS_INVALID_PARAMETER;
1677         }
1678
1679         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1680                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1681                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1682                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1683                 BerElement *ber;
1684                 struct berval *bv;
1685                 char *retoid = NULL;
1686                 struct berval *retdata = NULL;
1687                 char *utf8_password;
1688                 char *utf8_dn;
1689                 size_t converted_size;
1690                 int ret;
1691
1692                 if (!ldap_state->is_nds_ldap) {
1693
1694                         if (!smbldap_has_extension(
1695                                     smbldap_get_ldap(
1696                                             ldap_state->smbldap_state),
1697                                     LDAP_EXOP_MODIFY_PASSWD)) {
1698                                 DEBUG(2, ("ldap password change requested, but LDAP "
1699                                           "server does not support it -- ignoring\n"));
1700                                 return NT_STATUS_OK;
1701                         }
1702                 }
1703
1704                 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1705                                         pdb_get_plaintext_passwd(newpwd),
1706                                         &converted_size))
1707                 {
1708                         return NT_STATUS_NO_MEMORY;
1709                 }
1710
1711                 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1712                         TALLOC_FREE(utf8_password);
1713                         return NT_STATUS_NO_MEMORY;
1714                 }
1715
1716                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1717                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1718                         TALLOC_FREE(utf8_password);
1719                         TALLOC_FREE(utf8_dn);
1720                         return NT_STATUS_UNSUCCESSFUL;
1721                 }
1722
1723                 if ((ber_printf (ber, "{") < 0) ||
1724                     (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1725                                  utf8_dn) < 0)) {
1726                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1727                                  "value <0\n"));
1728                         ber_free(ber,1);
1729                         TALLOC_FREE(utf8_dn);
1730                         TALLOC_FREE(utf8_password);
1731                         return NT_STATUS_UNSUCCESSFUL;
1732                 }
1733
1734                 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1735                         ret = ber_printf(ber, "ts}",
1736                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1737                                          utf8_password);
1738                 } else {
1739                         ret = ber_printf(ber, "}");
1740                 }
1741
1742                 if (ret < 0) {
1743                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1744                                  "value <0\n"));
1745                         ber_free(ber,1);
1746                         TALLOC_FREE(utf8_dn);
1747                         TALLOC_FREE(utf8_password);
1748                         return NT_STATUS_UNSUCCESSFUL;
1749                 }
1750
1751                 if ((rc = ber_flatten (ber, &bv))<0) {
1752                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1753                         ber_free(ber,1);
1754                         TALLOC_FREE(utf8_dn);
1755                         TALLOC_FREE(utf8_password);
1756                         return NT_STATUS_UNSUCCESSFUL;
1757                 }
1758
1759                 TALLOC_FREE(utf8_dn);
1760                 TALLOC_FREE(utf8_password);
1761                 ber_free(ber, 1);
1762
1763                 if (!ldap_state->is_nds_ldap) {
1764                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1765                                                         LDAP_EXOP_MODIFY_PASSWD,
1766                                                         bv, NULL, NULL, &retoid, 
1767                                                         &retdata);
1768                 } else {
1769                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1770                                                         pdb_get_plaintext_passwd(newpwd));
1771                 }
1772                 if (rc != LDAP_SUCCESS) {
1773                         char *ld_error = NULL;
1774
1775                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1776                                 DEBUG(3, ("Could not set userPassword "
1777                                           "attribute due to an objectClass "
1778                                           "violation -- ignoring\n"));
1779                                 ber_bvfree(bv);
1780                                 return NT_STATUS_OK;
1781                         }
1782
1783                         ldap_get_option(
1784                                 smbldap_get_ldap(ldap_state->smbldap_state),
1785                                 LDAP_OPT_ERROR_STRING,
1786                                         &ld_error);
1787                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1788                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1789                         SAFE_FREE(ld_error);
1790                         ber_bvfree(bv);
1791 #if defined(LDAP_CONSTRAINT_VIOLATION)
1792                         if (rc == LDAP_CONSTRAINT_VIOLATION)
1793                                 return NT_STATUS_PASSWORD_RESTRICTION;
1794 #endif
1795                         return NT_STATUS_UNSUCCESSFUL;
1796                 } else {
1797                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1798 #ifdef DEBUG_PASSWORD
1799                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1800 #endif    
1801                         if (retdata)
1802                                 ber_bvfree(retdata);
1803                         if (retoid)
1804                                 ldap_memfree(retoid);
1805                 }
1806                 ber_bvfree(bv);
1807         }
1808
1809         if (!mods) {
1810                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1811                 /* may be password change below however */
1812         } else {
1813                 switch(ldap_op) {
1814                         case LDAP_MOD_ADD:
1815                                 if (ldap_state->is_nds_ldap) {
1816                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1817                                                         "objectclass",
1818                                                         "inetOrgPerson");
1819                                 } else {
1820                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1821                                                         "objectclass",
1822                                                         LDAP_OBJ_ACCOUNT);
1823                                 }
1824                                 rc = smbldap_add(ldap_state->smbldap_state,
1825                                                  dn, mods);
1826                                 break;
1827                         case LDAP_MOD_REPLACE:
1828                                 rc = smbldap_modify(ldap_state->smbldap_state,
1829                                                     dn ,mods);
1830                                 break;
1831                         default:
1832                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1833                                          ldap_op));
1834                                 return NT_STATUS_INVALID_PARAMETER;
1835                 }
1836
1837                 if (rc!=LDAP_SUCCESS) {
1838                         return NT_STATUS_UNSUCCESSFUL;
1839                 }
1840         }
1841
1842         return NT_STATUS_OK;
1843 }
1844
1845 /**********************************************************************
1846  Delete entry from LDAP for username.
1847 *********************************************************************/
1848
1849 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1850                                            struct samu * sam_acct)
1851 {
1852         struct ldapsam_privates *priv =
1853                 (struct ldapsam_privates *)my_methods->private_data;
1854         const char *sname;
1855         int rc;
1856         LDAPMessage *msg, *entry;
1857         NTSTATUS result = NT_STATUS_NO_MEMORY;
1858         const char **attr_list;
1859         TALLOC_CTX *mem_ctx;
1860
1861         if (!sam_acct) {
1862                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1863                 return NT_STATUS_INVALID_PARAMETER;
1864         }
1865
1866         sname = pdb_get_username(sam_acct);
1867
1868         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1869                   "LDAP.\n", sname));
1870
1871         mem_ctx = talloc_new(NULL);
1872         if (mem_ctx == NULL) {
1873                 DEBUG(0, ("talloc_new failed\n"));
1874                 goto done;
1875         }
1876
1877         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1878         if (attr_list == NULL) {
1879                 goto done;
1880         }
1881
1882         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1883
1884         if ((rc != LDAP_SUCCESS) ||
1885             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1886             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1887                 DEBUG(5, ("Could not find user %s\n", sname));
1888                 result = NT_STATUS_NO_SUCH_USER;
1889                 goto done;
1890         }
1891
1892         rc = ldapsam_delete_entry(
1893                 priv, mem_ctx, entry,
1894                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1895                 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1896                 attr_list);
1897
1898         result = (rc == LDAP_SUCCESS) ?
1899                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1900
1901  done:
1902         TALLOC_FREE(mem_ctx);
1903         return result;
1904 }
1905
1906 /**********************************************************************
1907  Update struct samu.
1908 *********************************************************************/
1909
1910 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1911 {
1912         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1913         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1914         int rc = 0;
1915         char *dn;
1916         LDAPMessage *result = NULL;
1917         LDAPMessage *entry = NULL;
1918         LDAPMod **mods = NULL;
1919         const char **attr_list;
1920
1921         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1922         if (!result) {
1923                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1924                 if (pdb_get_username(newpwd) == NULL) {
1925                         return NT_STATUS_INVALID_PARAMETER;
1926                 }
1927                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1928                 TALLOC_FREE( attr_list );
1929                 if (rc != LDAP_SUCCESS) {
1930                         return NT_STATUS_UNSUCCESSFUL;
1931                 }
1932                 pdb_set_backend_private_data(newpwd, result, NULL,
1933                                              my_methods, PDB_CHANGED);
1934                 smbldap_talloc_autofree_ldapmsg(newpwd, result);
1935         }
1936
1937         if (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
1938                                result) == 0) {
1939                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1940                 return NT_STATUS_UNSUCCESSFUL;
1941         }
1942
1943         entry = ldap_first_entry(smbldap_get_ldap(ldap_state->smbldap_state),
1944                                  result);
1945         dn = smbldap_talloc_dn(talloc_tos(),
1946                                smbldap_get_ldap(ldap_state->smbldap_state),
1947                                entry);
1948         if (!dn) {
1949                 return NT_STATUS_UNSUCCESSFUL;
1950         }
1951
1952         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1953
1954         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1955                                 pdb_element_is_changed)) {
1956                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1957                 TALLOC_FREE(dn);
1958                 if (mods != NULL)
1959                         ldap_mods_free(mods,True);
1960                 return NT_STATUS_UNSUCCESSFUL;
1961         }
1962
1963         if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1964             && (mods == NULL)) {
1965                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1966                          pdb_get_username(newpwd)));
1967                 TALLOC_FREE(dn);
1968                 return NT_STATUS_OK;
1969         }
1970
1971         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1972
1973         if (mods != NULL) {
1974                 ldap_mods_free(mods,True);
1975         }
1976
1977         TALLOC_FREE(dn);
1978
1979         /*
1980          * We need to set the backend private data to NULL here. For example
1981          * setuserinfo level 25 does a pdb_update_sam_account twice on the
1982          * same one, and with the explicit delete / add logic for attribute
1983          * values the second time we would use the wrong "old" value which
1984          * does not exist in LDAP anymore. Thus the LDAP server would refuse
1985          * the update.
1986          * The existing LDAPMessage is still being auto-freed by the
1987          * destructor.
1988          */
1989         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1990                                      PDB_CHANGED);
1991
1992         if (!NT_STATUS_IS_OK(ret)) {
1993                 return ret;
1994         }
1995
1996         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1997                   pdb_get_username(newpwd)));
1998         return NT_STATUS_OK;
1999 }
2000
2001 /***************************************************************************
2002  Renames a struct samu
2003  - The "rename user script" has full responsibility for changing everything
2004 ***************************************************************************/
2005
2006 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
2007                                      TALLOC_CTX *tmp_ctx,
2008                                      uint32_t group_rid,
2009                                      uint32_t member_rid);
2010
2011 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2012                                                TALLOC_CTX *mem_ctx,
2013                                                struct samu *user,
2014                                                struct dom_sid **pp_sids,
2015                                                gid_t **pp_gids,
2016                                                uint32_t *p_num_groups);
2017
2018 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
2019                                            struct samu *old_acct,
2020                                            const char *newname)
2021 {
2022         const char *oldname;
2023         int rc;
2024         char *rename_script = NULL;
2025         fstring oldname_lower, newname_lower;
2026
2027         if (!old_acct) {
2028                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
2029                 return NT_STATUS_INVALID_PARAMETER;
2030         }
2031         if (!newname) {
2032                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
2033                 return NT_STATUS_INVALID_PARAMETER;
2034         }
2035
2036         oldname = pdb_get_username(old_acct);
2037
2038         /* rename the posix user */
2039         rename_script = lp_rename_user_script(talloc_tos());
2040         if (rename_script == NULL) {
2041                 return NT_STATUS_NO_MEMORY;
2042         }
2043
2044         if (!(*rename_script)) {
2045                 TALLOC_FREE(rename_script);
2046                 return NT_STATUS_ACCESS_DENIED;
2047         }
2048
2049         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2050                    oldname, newname));
2051
2052         /* We have to allow the account name to end with a '$'.
2053            Also, follow the semantics in _samr_create_user() and lower case the
2054            posix name but preserve the case in passdb */
2055
2056         fstrcpy( oldname_lower, oldname );
2057         if (!strlower_m( oldname_lower )) {
2058                 return NT_STATUS_INVALID_PARAMETER;
2059         }
2060         fstrcpy( newname_lower, newname );
2061         if (!strlower_m( newname_lower )) {
2062                 return NT_STATUS_INVALID_PARAMETER;
2063         }
2064
2065         rename_script = realloc_string_sub2(rename_script,
2066                                         "%unew",
2067                                         newname_lower,
2068                                         true,
2069                                         true);
2070         if (!rename_script) {
2071                 return NT_STATUS_NO_MEMORY;
2072         }
2073         rename_script = realloc_string_sub2(rename_script,
2074                                         "%uold",
2075                                         oldname_lower,
2076                                         true,
2077                                         true);
2078         rc = smbrun(rename_script, NULL, NULL);
2079
2080         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2081                           rename_script, rc));
2082
2083         TALLOC_FREE(rename_script);
2084
2085         if (rc == 0) {
2086                 smb_nscd_flush_user_cache();
2087         }
2088
2089         if (rc)
2090                 return NT_STATUS_UNSUCCESSFUL;
2091
2092         return NT_STATUS_OK;
2093 }
2094
2095 /**********************************************************************
2096  Add struct samu to LDAP.
2097 *********************************************************************/
2098
2099 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2100 {
2101         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2102         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2103         int rc;
2104         LDAPMessage     *result = NULL;
2105         LDAPMessage     *entry  = NULL;
2106         LDAPMod         **mods = NULL;
2107         int             ldap_op = LDAP_MOD_REPLACE;
2108         uint32_t                num_result;
2109         const char      **attr_list;
2110         char *escape_user = NULL;
2111         const char      *username = pdb_get_username(newpwd);
2112         const struct dom_sid    *sid = pdb_get_user_sid(newpwd);
2113         char *filter = NULL;
2114         char *dn = NULL;
2115         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2116         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2117
2118         if (!ctx) {
2119                 return NT_STATUS_NO_MEMORY;
2120         }
2121
2122         if (!username || !*username) {
2123                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2124                 status = NT_STATUS_INVALID_PARAMETER;
2125                 goto fn_exit;
2126         }
2127
2128         /* free this list after the second search or in case we exit on failure */
2129         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2130
2131         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2132
2133         if (rc != LDAP_SUCCESS) {
2134                 goto fn_exit;
2135         }
2136
2137         if (ldap_count_entries(smbldap_get_ldap(ldap_state->smbldap_state),
2138                                result) != 0) {
2139                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2140                          username));
2141                 goto fn_exit;
2142         }
2143         ldap_msgfree(result);
2144         result = NULL;
2145
2146         if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2147                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2148                                                   sid, &result);
2149                 if (rc == LDAP_SUCCESS) {
2150                         if (ldap_count_entries(
2151                                     smbldap_get_ldap(
2152                                             ldap_state->smbldap_state),
2153                                     result) != 0) {
2154                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2155                                          "already in the base, with samba "
2156                                          "attributes\n", sid_string_dbg(sid)));
2157                                 goto fn_exit;
2158                         }
2159                         ldap_msgfree(result);
2160                         result = NULL;
2161                 }
2162         }
2163
2164         /* does the entry already exist but without a samba attributes?
2165            we need to return the samba attributes here */
2166
2167         escape_user = escape_ldap_string(talloc_tos(), username);
2168         filter = talloc_strdup(attr_list, "(uid=%u)");
2169         if (!filter) {
2170                 status = NT_STATUS_NO_MEMORY;
2171                 goto fn_exit;
2172         }
2173         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2174         TALLOC_FREE(escape_user);
2175         if (!filter) {
2176                 status = NT_STATUS_NO_MEMORY;
2177                 goto fn_exit;
2178         }
2179
2180         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2181                                    filter, attr_list, &result);
2182         if ( rc != LDAP_SUCCESS ) {
2183                 goto fn_exit;
2184         }
2185
2186         num_result = ldap_count_entries(
2187                 smbldap_get_ldap(ldap_state->smbldap_state), result);
2188
2189         if (num_result > 1) {
2190                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2191                 goto fn_exit;
2192         }
2193
2194         /* Check if we need to update an existing entry */
2195         if (num_result == 1) {
2196                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2197                 ldap_op = LDAP_MOD_REPLACE;
2198                 entry = ldap_first_entry(
2199                         smbldap_get_ldap(ldap_state->smbldap_state), result);
2200                 dn = smbldap_talloc_dn(
2201                         ctx, smbldap_get_ldap(ldap_state->smbldap_state),
2202                         entry);
2203                 if (!dn) {
2204                         status = NT_STATUS_NO_MEMORY;
2205                         goto fn_exit;
2206                 }
2207
2208         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2209
2210                 /* There might be a SID for this account already - say an idmap entry */
2211
2212                 filter = talloc_asprintf(ctx,
2213                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2214                                  get_userattr_key2string(ldap_state->schema_ver,
2215                                          LDAP_ATTR_USER_SID),
2216                                  sid_string_talloc(ctx, sid),
2217                                  LDAP_OBJ_IDMAP_ENTRY,
2218                                  LDAP_OBJ_SID_ENTRY);
2219                 if (!filter) {
2220                         status = NT_STATUS_NO_MEMORY;
2221                         goto fn_exit;
2222                 }
2223
2224                 /* free old result before doing a new search */
2225                 if (result != NULL) {
2226                         ldap_msgfree(result);
2227                         result = NULL;
2228                 }
2229                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2230                                            filter, attr_list, &result);
2231
2232                 if ( rc != LDAP_SUCCESS ) {
2233                         goto fn_exit;
2234                 }
2235
2236                 num_result = ldap_count_entries(
2237                         smbldap_get_ldap(ldap_state->smbldap_state), result);
2238
2239                 if (num_result > 1) {
2240                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2241                         goto fn_exit;
2242                 }
2243
2244                 /* Check if we need to update an existing entry */
2245                 if (num_result == 1) {
2246
2247                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2248                         ldap_op = LDAP_MOD_REPLACE;
2249                         entry = ldap_first_entry (
2250                                 smbldap_get_ldap(ldap_state->smbldap_state),
2251                                 result);
2252                         dn = smbldap_talloc_dn (
2253                                 ctx,
2254                                 smbldap_get_ldap(ldap_state->smbldap_state),
2255                                 entry);
2256                         if (!dn) {
2257                                 status = NT_STATUS_NO_MEMORY;
2258                                 goto fn_exit;
2259                         }
2260                 }
2261         }
2262
2263         if (num_result == 0) {
2264                 char *escape_username;
2265                 /* Check if we need to add an entry */
2266                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2267                 ldap_op = LDAP_MOD_ADD;
2268
2269                 escape_username = escape_rdn_val_string_alloc(username);
2270                 if (!escape_username) {
2271                         status = NT_STATUS_NO_MEMORY;
2272                         goto fn_exit;
2273                 }
2274
2275                 if (username[strlen(username)-1] == '$') {
2276                         dn = talloc_asprintf(ctx,
2277                                         "uid=%s,%s",
2278                                         escape_username,
2279                                         lp_ldap_machine_suffix(talloc_tos()));
2280                 } else {
2281                         dn = talloc_asprintf(ctx,
2282                                         "uid=%s,%s",
2283                                         escape_username,
2284                                         lp_ldap_user_suffix(talloc_tos()));
2285                 }
2286
2287                 SAFE_FREE(escape_username);
2288                 if (!dn) {
2289                         status = NT_STATUS_NO_MEMORY;
2290                         goto fn_exit;
2291                 }
2292         }
2293
2294         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2295                                 pdb_element_is_set_or_changed)) {
2296                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2297                 if (mods != NULL) {
2298                         ldap_mods_free(mods, true);
2299                 }
2300                 goto fn_exit;
2301         }
2302
2303         if (mods == NULL) {
2304                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2305                 goto fn_exit;
2306         }
2307         switch ( ldap_state->schema_ver ) {
2308                 case SCHEMAVER_SAMBASAMACCOUNT:
2309                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2310                         break;
2311                 default:
2312                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2313                         break;
2314         }
2315
2316         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2317         if (!NT_STATUS_IS_OK(ret)) {
2318                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2319                          pdb_get_username(newpwd),dn));
2320                 ldap_mods_free(mods, true);
2321                 goto fn_exit;
2322         }
2323
2324         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2325         ldap_mods_free(mods, true);
2326
2327         status = NT_STATUS_OK;
2328
2329   fn_exit:
2330
2331         TALLOC_FREE(ctx);
2332         if (result) {
2333                 ldap_msgfree(result);
2334         }
2335         return status;
2336 }
2337
2338 /**********************************************************************
2339  *********************************************************************/
2340
2341 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2342                                      const char *filter,
2343                                      LDAPMessage ** result)
2344 {
2345         int scope = LDAP_SCOPE_SUBTREE;
2346         int rc;
2347         const char **attr_list;
2348
2349         attr_list = get_attr_list(NULL, groupmap_attr_list);
2350         rc = smbldap_search(ldap_state->smbldap_state,
2351                             lp_ldap_suffix (talloc_tos()), scope,
2352                             filter, attr_list, 0, result);
2353         TALLOC_FREE(attr_list);
2354
2355         return rc;
2356 }
2357
2358 /**********************************************************************
2359  *********************************************************************/
2360
2361 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2362                                  GROUP_MAP *map, LDAPMessage *entry)
2363 {
2364         char *temp = NULL;
2365         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2366
2367         if (ldap_state == NULL || map == NULL || entry == NULL ||
2368             smbldap_get_ldap(ldap_state->smbldap_state) == NULL) {
2369                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2370                 TALLOC_FREE(ctx);
2371                 return false;
2372         }
2373
2374         temp = smbldap_talloc_single_attribute(
2375                         smbldap_get_ldap(ldap_state->smbldap_state),
2376                         entry,
2377                         get_attr_key2string(groupmap_attr_list,
2378                                 LDAP_ATTR_GIDNUMBER),
2379                         ctx);
2380         if (!temp) {
2381                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2382                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2383                 TALLOC_FREE(ctx);
2384                 return false;
2385         }
2386         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2387
2388         map->gid = (gid_t)atol(temp);
2389
2390         TALLOC_FREE(temp);
2391         temp = smbldap_talloc_single_attribute(
2392                         smbldap_get_ldap(ldap_state->smbldap_state),
2393                         entry,
2394                         get_attr_key2string(groupmap_attr_list,
2395                                 LDAP_ATTR_GROUP_SID),
2396                         ctx);
2397         if (!temp) {
2398                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2399                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2400                 TALLOC_FREE(ctx);
2401                 return false;
2402         }
2403
2404         if (!string_to_sid(&map->sid, temp)) {
2405                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2406                 TALLOC_FREE(ctx);
2407                 return false;
2408         }
2409
2410         TALLOC_FREE(temp);
2411         temp = smbldap_talloc_single_attribute(
2412                         smbldap_get_ldap(ldap_state->smbldap_state),
2413                         entry,
2414                         get_attr_key2string(groupmap_attr_list,
2415                                 LDAP_ATTR_GROUP_TYPE),
2416                         ctx);
2417         if (!temp) {
2418                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2419                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2420                 TALLOC_FREE(ctx);
2421                 return false;
2422         }
2423         map->sid_name_use = (enum lsa_SidType)atol(temp);
2424
2425         if ((map->sid_name_use < SID_NAME_USER) ||
2426                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2427                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2428                 TALLOC_FREE(ctx);
2429                 return false;
2430         }
2431
2432         TALLOC_FREE(temp);
2433         temp = smbldap_talloc_single_attribute(
2434                         smbldap_get_ldap(ldap_state->smbldap_state),
2435                         entry,
2436                         get_attr_key2string(groupmap_attr_list,
2437                                 LDAP_ATTR_DISPLAY_NAME),
2438                         ctx);
2439         if (!temp) {
2440                 temp = smbldap_talloc_single_attribute(
2441                                 smbldap_get_ldap(ldap_state->smbldap_state),
2442                                 entry,
2443                                 get_attr_key2string(groupmap_attr_list,
2444                                         LDAP_ATTR_CN),
2445                                 ctx);
2446                 if (!temp) {
2447                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2448 for gidNumber(%lu)\n",(unsigned long)map->gid));
2449                         TALLOC_FREE(ctx);
2450                         return false;
2451                 }
2452         }
2453         map->nt_name = talloc_strdup(map, temp);
2454         if (!map->nt_name) {
2455                 TALLOC_FREE(ctx);
2456                 return false;
2457         }
2458
2459         TALLOC_FREE(temp);
2460         temp = smbldap_talloc_single_attribute(
2461                         smbldap_get_ldap(ldap_state->smbldap_state),
2462                         entry,
2463                         get_attr_key2string(groupmap_attr_list,
2464                                 LDAP_ATTR_DESC),
2465                         ctx);
2466         if (!temp) {
2467                 temp = talloc_strdup(ctx, "");
2468                 if (!temp) {
2469                         TALLOC_FREE(ctx);
2470                         return false;
2471                 }
2472         }
2473         map->comment = talloc_strdup(map, temp);
2474         if (!map->comment) {
2475                 TALLOC_FREE(ctx);
2476                 return false;
2477         }
2478
2479         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2480                 struct unixid id;
2481                 id.id = map->gid;
2482                 id.type = ID_TYPE_GID;
2483
2484                 idmap_cache_set_sid2unixid(&map->sid, &id);
2485         }
2486
2487         TALLOC_FREE(ctx);
2488         return true;
2489 }
2490
2491 /**********************************************************************
2492  *********************************************************************/
2493
2494 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2495                                  const char *filter,
2496                                  GROUP_MAP *map)
2497 {
2498         struct ldapsam_privates *ldap_state =
2499                 (struct ldapsam_privates *)methods->private_data;
2500         LDAPMessage *result = NULL;
2501         LDAPMessage *entry = NULL;
2502         int count;
2503
2504         if (ldapsam_search_one_group(ldap_state, filter, &result)
2505             != LDAP_SUCCESS) {
2506                 return NT_STATUS_NO_SUCH_GROUP;
2507         }
2508
2509         count = ldap_count_entries(priv2ld(ldap_state), result);
2510
2511         if (count < 1) {
2512                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2513                           "%s\n", filter));
2514                 ldap_msgfree(result);
2515                 return NT_STATUS_NO_SUCH_GROUP;
2516         }
2517
2518         if (count > 1) {
2519                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2520                           "count=%d\n", filter, count));
2521                 ldap_msgfree(result);
2522                 return NT_STATUS_NO_SUCH_GROUP;
2523         }
2524
2525         entry = ldap_first_entry(priv2ld(ldap_state), result);
2526
2527         if (!entry) {
2528                 ldap_msgfree(result);
2529                 return NT_STATUS_UNSUCCESSFUL;
2530         }
2531
2532         if (!init_group_from_ldap(ldap_state, map, entry)) {
2533                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2534                           "group filter %s\n", filter));
2535                 ldap_msgfree(result);
2536                 return NT_STATUS_NO_SUCH_GROUP;
2537         }
2538
2539         ldap_msgfree(result);
2540         return NT_STATUS_OK;
2541 }
2542
2543 /**********************************************************************
2544  *********************************************************************/
2545
2546 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2547                                  struct dom_sid sid)
2548 {
2549         char *filter = NULL;
2550         NTSTATUS status;
2551         fstring tmp;
2552
2553         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2554                 LDAP_OBJ_GROUPMAP,
2555                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2556                 sid_to_fstring(tmp, &sid)) < 0) {
2557                 return NT_STATUS_NO_MEMORY;
2558         }
2559
2560         status = ldapsam_getgroup(methods, filter, map);
2561         SAFE_FREE(filter);
2562         return status;
2563 }
2564
2565 /**********************************************************************
2566  *********************************************************************/
2567
2568 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2569                                  gid_t gid)
2570 {
2571         char *filter = NULL;
2572         NTSTATUS status;
2573
2574         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2575                 LDAP_OBJ_GROUPMAP,
2576                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2577                 (unsigned long)gid) < 0) {
2578                 return NT_STATUS_NO_MEMORY;
2579         }
2580
2581         status = ldapsam_getgroup(methods, filter, map);
2582         SAFE_FREE(filter);
2583         return status;
2584 }
2585
2586 /**********************************************************************
2587  *********************************************************************/
2588
2589 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2590                                  const char *name)
2591 {
2592         char *filter = NULL;
2593         char *escape_name = escape_ldap_string(talloc_tos(), name);
2594         NTSTATUS status;
2595
2596         if (!escape_name) {
2597                 return NT_STATUS_NO_MEMORY;
2598         }
2599
2600         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2601                 LDAP_OBJ_GROUPMAP,
2602                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2603                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2604                 escape_name) < 0) {
2605                 TALLOC_FREE(escape_name);
2606                 return NT_STATUS_NO_MEMORY;
2607         }
2608
2609         TALLOC_FREE(escape_name);
2610         status = ldapsam_getgroup(methods, filter, map);
2611         SAFE_FREE(filter);
2612         return status;
2613 }
2614
2615 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2616                                            LDAPMessage *entry,
2617                                            const struct dom_sid *domain_sid,
2618                                            uint32_t *rid)
2619 {
2620         fstring str;
2621         struct dom_sid sid;
2622
2623         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2624                                           str, sizeof(str)-1)) {
2625                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2626                 return False;
2627         }
2628
2629         if (!string_to_sid(&sid, str)) {
2630                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2631                 return False;
2632         }
2633
2634         if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2635                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2636                            str, sid_string_dbg(domain_sid)));
2637                 return False;
2638         }
2639
2640         if (!sid_peek_rid(&sid, rid)) {
2641                 DEBUG(10, ("Could not peek into RID\n"));
2642                 return False;
2643         }
2644
2645         return True;
2646 }
2647
2648 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2649                                            TALLOC_CTX *mem_ctx,
2650                                            const struct dom_sid *group,
2651                                            uint32_t **pp_member_rids,
2652                                            size_t *p_num_members)
2653 {
2654         struct ldapsam_privates *ldap_state =
2655                 (struct ldapsam_privates *)methods->private_data;
2656         struct smbldap_state *conn = ldap_state->smbldap_state;
2657         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2658         const char *sid_attrs[] = { "sambaSID", NULL };
2659         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2660         LDAPMessage *result = NULL;
2661         LDAPMessage *entry;
2662         char *filter;
2663         char **values = NULL;
2664         char **memberuid;
2665         char *gidstr;
2666         int rc, count;
2667
2668         *pp_member_rids = NULL;
2669         *p_num_members = 0;
2670
2671         filter = talloc_asprintf(mem_ctx,
2672                                  "(&(objectClass=%s)"
2673                                  "(objectClass=%s)"
2674                                  "(sambaSID=%s))",
2675                                  LDAP_OBJ_POSIXGROUP,
2676                                  LDAP_OBJ_GROUPMAP,
2677                                  sid_string_talloc(mem_ctx, group));
2678         if (filter == NULL) {
2679                 ret = NT_STATUS_NO_MEMORY;
2680                 goto done;
2681         }
2682
2683         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2684                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2685                             &result);
2686
2687         if (rc != LDAP_SUCCESS)
2688                 goto done;
2689
2690         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2691
2692         count = ldap_count_entries(smbldap_get_ldap(conn), result);
2693
2694         if (count > 1) {
2695                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2696                           sid_string_dbg(group)));
2697                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2698                 goto done;
2699         }
2700
2701         if (count == 0) {
2702                 ret = NT_STATUS_NO_SUCH_GROUP;
2703                 goto done;
2704         }
2705
2706         entry = ldap_first_entry(smbldap_get_ldap(conn), result);
2707         if (entry == NULL)
2708                 goto done;
2709
2710         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2711         if (!gidstr) {
2712                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2713                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2714                 goto done;
2715         }
2716
2717         values = ldap_get_values(smbldap_get_ldap(conn), entry, "memberUid");
2718
2719         if ((values != NULL) && (values[0] != NULL)) {
2720
2721                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2722                 if (filter == NULL) {
2723                         ret = NT_STATUS_NO_MEMORY;
2724                         goto done;
2725                 }
2726
2727                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2728                         char *escape_memberuid;
2729
2730                         escape_memberuid = escape_ldap_string(talloc_tos(),
2731                                                               *memberuid);
2732                         if (escape_memberuid == NULL) {
2733                                 ret = NT_STATUS_NO_MEMORY;
2734                                 goto done;
2735                         }
2736
2737                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2738                         TALLOC_FREE(escape_memberuid);
2739                         if (filter == NULL) {
2740                                 ret = NT_STATUS_NO_MEMORY;
2741                                 goto done;
2742                         }
2743                 }
2744
2745                 filter = talloc_asprintf_append_buffer(filter, "))");
2746                 if (filter == NULL) {
2747                         ret = NT_STATUS_NO_MEMORY;
2748                         goto done;
2749                 }
2750
2751                 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2752                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2753                                     &result);
2754
2755                 if (rc != LDAP_SUCCESS)
2756                         goto done;
2757
2758                 count = ldap_count_entries(smbldap_get_ldap(conn), result);
2759                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2760
2761                 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2762
2763                 for (entry = ldap_first_entry(smbldap_get_ldap(conn), result);
2764                      entry != NULL;
2765                      entry = ldap_next_entry(smbldap_get_ldap(conn), entry))
2766                 {
2767                         char *sidstr;
2768                         struct dom_sid sid;
2769                         uint32_t rid;
2770
2771                         sidstr = smbldap_talloc_single_attribute(
2772                                 smbldap_get_ldap(conn), entry, "sambaSID",
2773                                 mem_ctx);
2774                         if (!sidstr) {
2775                                 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2776                                           "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2777                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2778                                 goto done;
2779                         }
2780
2781                         if (!string_to_sid(&sid, sidstr))
2782                                 goto done;
2783
2784                         if (!sid_check_is_in_our_sam(&sid)) {
2785                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2786                                           "in our domain\n"));
2787                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2788                                 goto done;
2789                         }
2790
2791                         sid_peek_rid(&sid, &rid);
2792
2793                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2794                                                 p_num_members)) {
2795                                 ret = NT_STATUS_NO_MEMORY;
2796                                 goto done;
2797                         }
2798                 }
2799         }
2800
2801         filter = talloc_asprintf(mem_ctx,
2802                                  "(&(objectClass=%s)"
2803                                  "(gidNumber=%s))",
2804                                  LDAP_OBJ_SAMBASAMACCOUNT,
2805                                  gidstr);
2806
2807         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2808                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2809                             &result);
2810
2811         if (rc != LDAP_SUCCESS)
2812                 goto done;
2813
2814         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2815
2816         for (entry = ldap_first_entry(smbldap_get_ldap(conn), result);
2817              entry != NULL;
2818              entry = ldap_next_entry(smbldap_get_ldap(conn), entry))
2819         {
2820                 uint32_t rid;
2821
2822                 if (!ldapsam_extract_rid_from_entry(smbldap_get_ldap(conn),
2823                                                     entry,
2824                                                     get_global_sam_sid(),
2825                                                     &rid)) {
2826                         DEBUG(0, ("Severe DB error, %s can't miss the samba SID"                                                                "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2827                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2828                         goto done;
2829                 }
2830
2831                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2832                                         p_num_members)) {
2833                         ret = NT_STATUS_NO_MEMORY;
2834                         goto done;
2835                 }
2836         }
2837
2838         ret = NT_STATUS_OK;
2839
2840  done:
2841
2842         if (values)
2843