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