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