750b71fb1c8ac79a2d88c4b62eb587a51cc84267
[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_static(user_sid),
1139                                                   sid_string_static(&ldap_state->domain_sid)));
1140                                         return False;
1141                                 }
1142                                 if (asprintf(&temp, "%i", rid) < 0) {
1143                                         return false;
1144                                 }
1145                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1146                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
1147                                         temp);
1148                                 SAFE_FREE(temp);
1149                                 break;
1150
1151                         case SCHEMAVER_SAMBASAMACCOUNT:
1152                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1153                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
1154                                         sid_to_string(sid_string, user_sid));
1155                                 break;
1156
1157                         default:
1158                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1159                                 break;
1160                 }
1161         }
1162
1163         /* we don't need to store the primary group RID - so leaving it
1164            'free' to hang off the unix primary group makes life easier */
1165
1166         if (need_update(sampass, PDB_GROUPSID)) {
1167                 fstring sid_string;
1168                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1169
1170                 switch ( ldap_state->schema_ver ) {
1171                         case SCHEMAVER_SAMBAACCOUNT:
1172                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1173                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1174                                                   sid_string_static(group_sid),
1175                                                   sid_string_static(&ldap_state->domain_sid)));
1176                                         return False;
1177                                 }
1178
1179                                 if (asprintf(&temp, "%i", rid) < 0) {
1180                                         return false;
1181                                 }
1182                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1183                                         get_userattr_key2string(ldap_state->schema_ver, 
1184                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1185                                 SAFE_FREE(temp);
1186                                 break;
1187
1188                         case SCHEMAVER_SAMBASAMACCOUNT:
1189                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1190                                         get_userattr_key2string(ldap_state->schema_ver, 
1191                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
1192                                 break;
1193
1194                         default:
1195                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1196                                 break;
1197                 }
1198
1199         }
1200
1201         /* displayName, cn, and gecos should all be the same
1202          *  most easily accomplished by giving them the same OID
1203          *  gecos isn't set here b/c it should be handled by the
1204          *  add-user script
1205          *  We change displayName only and fall back to cn if
1206          *  it does not exist.
1207          */
1208
1209         if (need_update(sampass, PDB_FULLNAME))
1210                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1211                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1212                         pdb_get_fullname(sampass));
1213
1214         if (need_update(sampass, PDB_ACCTDESC))
1215                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1216                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1217                         pdb_get_acct_desc(sampass));
1218
1219         if (need_update(sampass, PDB_WORKSTATIONS))
1220                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1221                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1222                         pdb_get_workstations(sampass));
1223
1224         if (need_update(sampass, PDB_MUNGEDDIAL))
1225                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1226                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1227                         pdb_get_munged_dial(sampass));
1228
1229         if (need_update(sampass, PDB_SMBHOME))
1230                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1231                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1232                         pdb_get_homedir(sampass));
1233
1234         if (need_update(sampass, PDB_DRIVE))
1235                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1236                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1237                         pdb_get_dir_drive(sampass));
1238
1239         if (need_update(sampass, PDB_LOGONSCRIPT))
1240                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1241                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1242                         pdb_get_logon_script(sampass));
1243
1244         if (need_update(sampass, PDB_PROFILE))
1245                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1246                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1247                         pdb_get_profile_path(sampass));
1248
1249         if (asprintf(&temp, "%li", pdb_get_logon_time(sampass)) < 0) {
1250                 return false;
1251         }
1252         if (need_update(sampass, PDB_LOGONTIME))
1253                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1254                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1255         SAFE_FREE(temp);
1256
1257         if (asprintf(&temp, "%li", pdb_get_logoff_time(sampass)) < 0) {
1258                 return false;
1259         }
1260         if (need_update(sampass, PDB_LOGOFFTIME))
1261                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1262                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1263         SAFE_FREE(temp);
1264
1265         if (asprintf(&temp, "%li", pdb_get_kickoff_time(sampass)) < 0) {
1266                 return false;
1267         }
1268         if (need_update(sampass, PDB_KICKOFFTIME))
1269                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1270                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1271         SAFE_FREE(temp);
1272
1273         if (asprintf(&temp, "%li", pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1274                 return false;
1275         }
1276         if (need_update(sampass, PDB_CANCHANGETIME))
1277                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1278                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1279         SAFE_FREE(temp);
1280
1281         if (asprintf(&temp, "%li", pdb_get_pass_must_change_time(sampass)) < 0) {
1282                 return false;
1283         }
1284         if (need_update(sampass, PDB_MUSTCHANGETIME))
1285                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1286                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1287         SAFE_FREE(temp);
1288
1289         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1290                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1291
1292                 if (need_update(sampass, PDB_LMPASSWD)) {
1293                         const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1294                         if (lm_pw) {
1295                                 char pwstr[34];
1296                                 pdb_sethexpwd(pwstr, lm_pw,
1297                                               pdb_get_acct_ctrl(sampass));
1298                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1299                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1300                                                  pwstr);
1301                         } else {
1302                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1303                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1304                                                  NULL);
1305                         }
1306                 }
1307                 if (need_update(sampass, PDB_NTPASSWD)) {
1308                         const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1309                         if (nt_pw) {
1310                                 char pwstr[34];
1311                                 pdb_sethexpwd(pwstr, nt_pw,
1312                                               pdb_get_acct_ctrl(sampass));
1313                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1314                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1315                                                  pwstr);
1316                         } else {
1317                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1318                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1319                                                  NULL);
1320                         }
1321                 }
1322
1323                 if (need_update(sampass, PDB_PWHISTORY)) {
1324                         char *pwstr = NULL;
1325                         uint32 pwHistLen = 0;
1326                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1327
1328                         pwstr = SMB_MALLOC_ARRAY(char, 1024);
1329                         if (!pwstr) {
1330                                 return false;
1331                         }
1332                         if (pwHistLen == 0) {
1333                                 /* Remove any password history from the LDAP store. */
1334                                 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1335                                 pwstr[64] = '\0';
1336                         } else {
1337                                 int i;
1338                                 uint32 currHistLen = 0;
1339                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1340                                 if (pwhist != NULL) {
1341                                         /* We can only store (1024-1/64 password history entries. */
1342                                         pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1343                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1344                                                 /* Store the salt. */
1345                                                 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1346                                                 /* Followed by the md5 hash of salt + md4 hash */
1347                                                 pdb_sethexpwd(&pwstr[(i*64)+32],
1348                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1349                                                 DEBUG(100, ("pwstr=%s\n", pwstr));
1350                                         }
1351                                 }
1352                         }
1353                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1354                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1355                                          pwstr);
1356                         SAFE_FREE(pwstr);
1357                 }
1358
1359                 if (need_update(sampass, PDB_PASSLASTSET)) {
1360                         if (asprintf(&temp, "%li",
1361                                 pdb_get_pass_last_set_time(sampass)) < 0) {
1362                                 return false;
1363                         }
1364                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1365                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1366                                 temp);
1367                         SAFE_FREE(temp);
1368                 }
1369         }
1370
1371         if (need_update(sampass, PDB_HOURS)) {
1372                 const uint8 *hours = pdb_get_hours(sampass);
1373                 if (hours) {
1374                         char hourstr[44];
1375                         pdb_sethexhours(hourstr, hours);
1376                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1377                                 existing,
1378                                 mods,
1379                                 get_userattr_key2string(ldap_state->schema_ver,
1380                                                 LDAP_ATTR_LOGON_HOURS),
1381                                 hourstr);
1382                 }
1383         }
1384
1385         if (need_update(sampass, PDB_ACCTCTRL))
1386                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1387                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1388                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1389
1390         /* password lockout cache:
1391            - If we are now autolocking or clearing, we write to ldap
1392            - If we are clearing, we delete the cache entry
1393            - If the count is > 0, we update the cache
1394
1395            This even means when autolocking, we cache, just in case the
1396            update doesn't work, and we have to cache the autolock flag */
1397
1398         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1399             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1400                 uint16 badcount = pdb_get_bad_password_count(sampass);
1401                 time_t badtime = pdb_get_bad_password_time(sampass);
1402                 uint32 pol;
1403                 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1404
1405                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1406                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1407
1408                 if ((badcount >= pol) || (badcount == 0)) {
1409                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1410                                 (unsigned int)badcount, (unsigned int)badtime));
1411                         if (asprintf(&temp, "%li", (long)badcount) < 0) {
1412                                 return false;
1413                         }
1414                         smbldap_make_mod(
1415                                 ldap_state->smbldap_state->ldap_struct,
1416                                 existing, mods,
1417                                 get_userattr_key2string(
1418                                         ldap_state->schema_ver,
1419                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1420                                 temp);
1421                         SAFE_FREE(temp);
1422
1423                         if (asprintf(&temp, "%li", badtime) < 0) {
1424                                 return false;
1425                         }
1426                         smbldap_make_mod(
1427                                 ldap_state->smbldap_state->ldap_struct,
1428                                 existing, mods,
1429                                 get_userattr_key2string(
1430                                         ldap_state->schema_ver,
1431                                         LDAP_ATTR_BAD_PASSWORD_TIME),
1432                                 temp);
1433                         SAFE_FREE(temp);
1434                 }
1435                 if (badcount == 0) {
1436                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1437                         login_cache_delentry(sampass);
1438                 } else {
1439                         LOGIN_CACHE cache_entry;
1440
1441                         cache_entry.entry_timestamp = time(NULL);
1442                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1443                         cache_entry.bad_password_count = badcount;
1444                         cache_entry.bad_password_time = badtime;
1445
1446                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1447                         login_cache_write(sampass, cache_entry);
1448                 }
1449         }
1450
1451         return True;
1452 }
1453
1454 /**********************************************************************
1455  Connect to LDAP server for password enumeration.
1456 *********************************************************************/
1457
1458 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, bool update, uint32 acb_mask)
1459 {
1460         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1461         int rc;
1462         char *filter = NULL;
1463         const char *suffix;
1464         const char **attr_list;
1465         bool machine_mask = False, user_mask = False;
1466         NTSTATUS status = NT_STATUS_OK;
1467         TALLOC_CTX *ctx = talloc_init("ldapsam_setsampwent");
1468
1469         if (!ctx) {
1470                 return NT_STATUS_NO_MEMORY;
1471         }
1472         filter = talloc_asprintf(ctx, "(&%s%s)", "(uid=%u)",
1473                 get_objclass_filter(ldap_state->schema_ver));
1474         if (!filter) {
1475                 status = NT_STATUS_NO_MEMORY;
1476                 goto out;
1477         }
1478
1479         filter = talloc_all_string_sub(ctx, filter, "%u", "*");
1480         if (!filter) {
1481                 status = NT_STATUS_NO_MEMORY;
1482                 goto out;
1483         }
1484
1485         machine_mask    = ((acb_mask != 0) && (acb_mask & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)));
1486         user_mask       = ((acb_mask != 0) && (acb_mask & ACB_NORMAL));
1487
1488         if (machine_mask) {
1489                 suffix = lp_ldap_machine_suffix();
1490         } else if (user_mask) {
1491                 suffix = lp_ldap_user_suffix();
1492         } else {
1493                 suffix = lp_ldap_suffix();
1494         }
1495
1496         DEBUG(10,("ldapsam_setsampwent: LDAP Query for acb_mask 0x%x will use suffix %s\n", 
1497                 acb_mask, suffix));
1498
1499         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1500         rc = smbldap_search(ldap_state->smbldap_state, suffix, LDAP_SCOPE_SUBTREE, filter, 
1501                             attr_list, 0, &ldap_state->result);
1502         TALLOC_FREE( attr_list );
1503
1504         if (rc != LDAP_SUCCESS) {
1505                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1506                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", suffix, filter));
1507                 ldap_msgfree(ldap_state->result);
1508                 ldap_state->result = NULL;
1509                 status = NT_STATUS_UNSUCCESSFUL;
1510                 goto out;
1511         }
1512
1513         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base %s\n",
1514                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
1515                 ldap_state->result), suffix));
1516
1517         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1518                                  ldap_state->result);
1519         ldap_state->index = 0;
1520
1521   out:
1522
1523         TALLOC_FREE(ctx);
1524         return status;
1525 }
1526
1527 /**********************************************************************
1528  End enumeration of the LDAP password list.
1529 *********************************************************************/
1530
1531 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1532 {
1533         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1534         if (ldap_state->result) {
1535                 ldap_msgfree(ldap_state->result);
1536                 ldap_state->result = NULL;
1537         }
1538 }
1539
1540 /**********************************************************************
1541 Get the next entry in the LDAP password database.
1542 *********************************************************************/
1543
1544 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods,
1545                                     struct samu *user)
1546 {
1547         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1548         struct ldapsam_privates *ldap_state =
1549                 (struct ldapsam_privates *)my_methods->private_data;
1550         bool bret = False;
1551
1552         while (!bret) {
1553                 if (!ldap_state->entry)
1554                         return ret;
1555                 
1556                 ldap_state->index++;
1557                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1558                 
1559                 ldap_state->entry = ldap_next_entry(priv2ld(ldap_state),
1560                                                     ldap_state->entry); 
1561         }
1562
1563         return NT_STATUS_OK;
1564 }
1565
1566 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1567                         const char *new_attr)
1568 {
1569         int i;
1570
1571         if (new_attr == NULL) {
1572                 return;
1573         }
1574
1575         for (i=0; (*attr_list)[i] != NULL; i++) {
1576                 ;
1577         }
1578
1579         (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1580                                             const char *,  i+2);
1581         SMB_ASSERT((*attr_list) != NULL);
1582         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1583         (*attr_list)[i+1] = NULL;
1584 }
1585
1586 /**********************************************************************
1587 Get struct samu entry from LDAP by username.
1588 *********************************************************************/
1589
1590 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1591 {
1592         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1593         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1594         LDAPMessage *result = NULL;
1595         LDAPMessage *entry = NULL;
1596         int count;
1597         const char ** attr_list;
1598         int rc;
1599         
1600         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1601         append_attr(user, &attr_list,
1602                     get_userattr_key2string(ldap_state->schema_ver,
1603                                             LDAP_ATTR_MOD_TIMESTAMP));
1604         append_attr(user, &attr_list, "uidNumber");
1605         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1606                                            attr_list);
1607         TALLOC_FREE( attr_list );
1608
1609         if ( rc != LDAP_SUCCESS ) 
1610                 return NT_STATUS_NO_SUCH_USER;
1611         
1612         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1613         
1614         if (count < 1) {
1615                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1616                 ldap_msgfree(result);
1617                 return NT_STATUS_NO_SUCH_USER;
1618         } else if (count > 1) {
1619                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1620                 ldap_msgfree(result);
1621                 return NT_STATUS_NO_SUCH_USER;
1622         }
1623
1624         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1625         if (entry) {
1626                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1627                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1628                         ldap_msgfree(result);
1629                         return NT_STATUS_NO_SUCH_USER;
1630                 }
1631                 pdb_set_backend_private_data(user, result, NULL,
1632                                              my_methods, PDB_CHANGED);
1633                 talloc_autofree_ldapmsg(user, result);
1634                 ret = NT_STATUS_OK;
1635         } else {
1636                 ldap_msgfree(result);
1637         }
1638         return ret;
1639 }
1640
1641 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1642                                    const DOM_SID *sid, LDAPMessage **result) 
1643 {
1644         int rc = -1;
1645         const char ** attr_list;
1646         uint32 rid;
1647
1648         switch ( ldap_state->schema_ver ) {
1649                 case SCHEMAVER_SAMBASAMACCOUNT: {
1650                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1651                         if (tmp_ctx == NULL) {
1652                                 return LDAP_NO_MEMORY;
1653                         }
1654
1655                         attr_list = get_userattr_list(tmp_ctx,
1656                                                       ldap_state->schema_ver);
1657                         append_attr(tmp_ctx, &attr_list,
1658                                     get_userattr_key2string(
1659                                             ldap_state->schema_ver,
1660                                             LDAP_ATTR_MOD_TIMESTAMP));
1661                         append_attr(tmp_ctx, &attr_list, "uidNumber");
1662                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1663                                                           result, attr_list);
1664                         TALLOC_FREE(tmp_ctx);
1665
1666                         if ( rc != LDAP_SUCCESS ) 
1667                                 return rc;
1668                         break;
1669                 }
1670                         
1671                 case SCHEMAVER_SAMBAACCOUNT:
1672                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1673                                 return rc;
1674                         }
1675                 
1676                         attr_list = get_userattr_list(NULL,
1677                                                       ldap_state->schema_ver);
1678                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1679                         TALLOC_FREE( attr_list );
1680
1681                         if ( rc != LDAP_SUCCESS ) 
1682                                 return rc;
1683                         break;
1684         }
1685         return rc;
1686 }
1687
1688 /**********************************************************************
1689  Get struct samu entry from LDAP by SID.
1690 *********************************************************************/
1691
1692 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1693 {
1694         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1695         LDAPMessage *result = NULL;
1696         LDAPMessage *entry = NULL;
1697         int count;
1698         int rc;
1699         fstring sid_string;
1700
1701         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1702                                           sid, &result); 
1703         if (rc != LDAP_SUCCESS)
1704                 return NT_STATUS_NO_SUCH_USER;
1705
1706         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1707         
1708         if (count < 1) {
1709                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1710                        count));
1711                 ldap_msgfree(result);
1712                 return NT_STATUS_NO_SUCH_USER;
1713         }  else if (count > 1) {
1714                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1715                        count));
1716                 ldap_msgfree(result);
1717                 return NT_STATUS_NO_SUCH_USER;
1718         }
1719
1720         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1721         if (!entry) {
1722                 ldap_msgfree(result);
1723                 return NT_STATUS_NO_SUCH_USER;
1724         }
1725
1726         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1727                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1728                 ldap_msgfree(result);
1729                 return NT_STATUS_NO_SUCH_USER;
1730         }
1731
1732         pdb_set_backend_private_data(user, result, NULL,
1733                                      my_methods, PDB_CHANGED);
1734         talloc_autofree_ldapmsg(user, result);
1735         return NT_STATUS_OK;
1736 }       
1737
1738 /********************************************************************
1739  Do the actual modification - also change a plaintext passord if 
1740  it it set.
1741 **********************************************************************/
1742
1743 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1744                                      struct samu *newpwd, char *dn,
1745                                      LDAPMod **mods, int ldap_op, 
1746                                      bool (*need_update)(const struct samu *, enum pdb_elements))
1747 {
1748         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1749         int rc;
1750         
1751         if (!newpwd || !dn) {
1752                 return NT_STATUS_INVALID_PARAMETER;
1753         }
1754         
1755         if (!mods) {
1756                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1757                 /* may be password change below however */
1758         } else {
1759                 switch(ldap_op) {
1760                         case LDAP_MOD_ADD:
1761                                 if (ldap_state->is_nds_ldap) {
1762                                         smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1763                                                         "objectclass", 
1764                                                         "inetOrgPerson");
1765                                 } else {
1766                                         smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1767                                                         "objectclass", 
1768                                                         LDAP_OBJ_ACCOUNT);
1769                                 }
1770                                 rc = smbldap_add(ldap_state->smbldap_state, 
1771                                                  dn, mods);
1772                                 break;
1773                         case LDAP_MOD_REPLACE: 
1774                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1775                                                     dn ,mods);
1776                                 break;
1777                         default:        
1778                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1779                                          ldap_op));
1780                                 return NT_STATUS_INVALID_PARAMETER;
1781                 }
1782                 
1783                 if (rc!=LDAP_SUCCESS) {
1784                         return NT_STATUS_UNSUCCESSFUL;
1785                 }  
1786         }
1787         
1788         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1789                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1790                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1791                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1792                 BerElement *ber;
1793                 struct berval *bv;
1794                 char *retoid = NULL;
1795                 struct berval *retdata = NULL;
1796                 char *utf8_password;
1797                 char *utf8_dn;
1798
1799                 if (!ldap_state->is_nds_ldap) {
1800
1801                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1802                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1803                                 DEBUG(2, ("ldap password change requested, but LDAP "
1804                                           "server does not support it -- ignoring\n"));
1805                                 return NT_STATUS_OK;
1806                         }
1807                 }
1808
1809                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1810                         return NT_STATUS_NO_MEMORY;
1811                 }
1812
1813                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1814                         SAFE_FREE(utf8_password);
1815                         return NT_STATUS_NO_MEMORY;
1816                 }
1817
1818                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1819                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1820                         SAFE_FREE(utf8_password);
1821                         SAFE_FREE(utf8_dn);
1822                         return NT_STATUS_UNSUCCESSFUL;
1823                 }
1824
1825                 ber_printf (ber, "{");
1826                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1827                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1828                 ber_printf (ber, "n}");
1829
1830                 if ((rc = ber_flatten (ber, &bv))<0) {
1831                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1832                         ber_free(ber,1);
1833                         SAFE_FREE(utf8_dn);
1834                         SAFE_FREE(utf8_password);
1835                         return NT_STATUS_UNSUCCESSFUL;
1836                 }
1837                 
1838                 SAFE_FREE(utf8_dn);
1839                 SAFE_FREE(utf8_password);
1840                 ber_free(ber, 1);
1841
1842                 if (!ldap_state->is_nds_ldap) {
1843                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1844                                                         LDAP_EXOP_MODIFY_PASSWD,
1845                                                         bv, NULL, NULL, &retoid, 
1846                                                         &retdata);
1847                 } else {
1848                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1849                                                         pdb_get_plaintext_passwd(newpwd));
1850                 }
1851                 if (rc != LDAP_SUCCESS) {
1852                         char *ld_error = NULL;
1853
1854                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1855                                 DEBUG(3, ("Could not set userPassword "
1856                                           "attribute due to an objectClass "
1857                                           "violation -- ignoring\n"));
1858                                 ber_bvfree(bv);
1859                                 return NT_STATUS_OK;
1860                         }
1861
1862                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1863                                         &ld_error);
1864                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1865                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1866                         SAFE_FREE(ld_error);
1867                         ber_bvfree(bv);
1868                         return NT_STATUS_UNSUCCESSFUL;
1869                 } else {
1870                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1871 #ifdef DEBUG_PASSWORD
1872                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1873 #endif    
1874                         if (retdata)
1875                                 ber_bvfree(retdata);
1876                         if (retoid)
1877                                 ldap_memfree(retoid);
1878                 }
1879                 ber_bvfree(bv);
1880         }
1881         return NT_STATUS_OK;
1882 }
1883
1884 /**********************************************************************
1885  Delete entry from LDAP for username.
1886 *********************************************************************/
1887
1888 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1889                                            struct samu * sam_acct)
1890 {
1891         struct ldapsam_privates *priv =
1892                 (struct ldapsam_privates *)my_methods->private_data;
1893         const char *sname;
1894         int rc;
1895         LDAPMessage *msg, *entry;
1896         NTSTATUS result = NT_STATUS_NO_MEMORY;
1897         const char **attr_list;
1898         TALLOC_CTX *mem_ctx;
1899
1900         if (!sam_acct) {
1901                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1902                 return NT_STATUS_INVALID_PARAMETER;
1903         }
1904
1905         sname = pdb_get_username(sam_acct);
1906
1907         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1908                   "LDAP.\n", sname));
1909
1910         mem_ctx = talloc_new(NULL);
1911         if (mem_ctx == NULL) {
1912                 DEBUG(0, ("talloc_new failed\n"));
1913                 goto done;
1914         }
1915
1916         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1917         if (attr_list == NULL) {
1918                 goto done;
1919         }
1920
1921         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1922
1923         if ((rc != LDAP_SUCCESS) ||
1924             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1925             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1926                 DEBUG(5, ("Could not find user %s\n", sname));
1927                 result = NT_STATUS_NO_SUCH_USER;
1928                 goto done;
1929         }
1930         
1931         rc = ldapsam_delete_entry(
1932                 priv, mem_ctx, entry,
1933                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1934                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1935                 attr_list);
1936
1937         result = (rc == LDAP_SUCCESS) ?
1938                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1939
1940  done:
1941         TALLOC_FREE(mem_ctx);
1942         return result;
1943 }
1944
1945 /**********************************************************************
1946  Helper function to determine for update_sam_account whether
1947  we need LDAP modification.
1948 *********************************************************************/
1949
1950 static bool element_is_changed(const struct samu *sampass,
1951                                enum pdb_elements element)
1952 {
1953         return IS_SAM_CHANGED(sampass, element);
1954 }
1955
1956 /**********************************************************************
1957  Update struct samu.
1958 *********************************************************************/
1959
1960 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1961 {
1962         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1963         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1964         int rc = 0;
1965         char *dn;
1966         LDAPMessage *result = NULL;
1967         LDAPMessage *entry = NULL;
1968         LDAPMod **mods = NULL;
1969         const char **attr_list;
1970
1971         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1972         if (!result) {
1973                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1974                 if (pdb_get_username(newpwd) == NULL) {
1975                         return NT_STATUS_INVALID_PARAMETER;
1976                 }
1977                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1978                 TALLOC_FREE( attr_list );
1979                 if (rc != LDAP_SUCCESS) {
1980                         return NT_STATUS_UNSUCCESSFUL;
1981                 }
1982                 pdb_set_backend_private_data(newpwd, result, NULL,
1983                                              my_methods, PDB_CHANGED);
1984                 talloc_autofree_ldapmsg(newpwd, result);
1985         }
1986
1987         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1988                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1989                 return NT_STATUS_UNSUCCESSFUL;
1990         }
1991
1992         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1993         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1994         if (!dn) {
1995                 return NT_STATUS_UNSUCCESSFUL;
1996         }
1997
1998         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1999
2000         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2001                                 element_is_changed)) {
2002                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
2003                 SAFE_FREE(dn);
2004                 if (mods != NULL)
2005                         ldap_mods_free(mods,True);
2006                 return NT_STATUS_UNSUCCESSFUL;
2007         }
2008         
2009         if (mods == NULL) {
2010                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
2011                          pdb_get_username(newpwd)));
2012                 SAFE_FREE(dn);
2013                 return NT_STATUS_OK;
2014         }
2015         
2016         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
2017         ldap_mods_free(mods,True);
2018         SAFE_FREE(dn);
2019
2020         /*
2021          * We need to set the backend private data to NULL here. For example
2022          * setuserinfo level 25 does a pdb_update_sam_account twice on the
2023          * same one, and with the explicit delete / add logic for attribute
2024          * values the second time we would use the wrong "old" value which
2025          * does not exist in LDAP anymore. Thus the LDAP server would refuse
2026          * the update.
2027          * The existing LDAPMessage is still being auto-freed by the
2028          * destructor.
2029          */
2030         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
2031                                      PDB_CHANGED);
2032
2033         if (!NT_STATUS_IS_OK(ret)) {
2034                 return ret;
2035         }
2036
2037         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
2038                   pdb_get_username(newpwd)));
2039         return NT_STATUS_OK;
2040 }
2041
2042 /***************************************************************************
2043  Renames a struct samu
2044  - The "rename user script" has full responsibility for changing everything
2045 ***************************************************************************/
2046
2047 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
2048                                            struct samu *old_acct,
2049                                            const char *newname)
2050 {
2051         const char *oldname;
2052         int rc;
2053         char *rename_script = NULL;
2054         fstring oldname_lower, newname_lower;
2055
2056         if (!old_acct) {
2057                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
2058                 return NT_STATUS_INVALID_PARAMETER;
2059         }
2060         if (!newname) {
2061                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
2062                 return NT_STATUS_INVALID_PARAMETER;
2063         }
2064
2065         oldname = pdb_get_username(old_acct);
2066
2067         /* rename the posix user */
2068         rename_script = SMB_STRDUP(lp_renameuser_script());
2069         if (rename_script) {
2070                 return NT_STATUS_NO_MEMORY;
2071         }
2072
2073         if (!(*rename_script)) {
2074                 SAFE_FREE(rename_script);
2075                 return NT_STATUS_ACCESS_DENIED;
2076         }
2077
2078         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2079                    oldname, newname));
2080
2081         /* We have to allow the account name to end with a '$'.
2082            Also, follow the semantics in _samr_create_user() and lower case the
2083            posix name but preserve the case in passdb */
2084
2085         fstrcpy( oldname_lower, oldname );
2086         strlower_m( oldname_lower );
2087         fstrcpy( newname_lower, newname );
2088         strlower_m( newname_lower );
2089         rename_script = realloc_string_sub2(rename_script,
2090                                         "%unew",
2091                                         newname_lower,
2092                                         true,
2093                                         true);
2094         if (rename_script) {
2095                 return NT_STATUS_NO_MEMORY;
2096         }
2097         rename_script = realloc_string_sub2(rename_script,
2098                                         "%uold",
2099                                         oldname_lower,
2100                                         true,
2101                                         true);
2102         rc = smbrun(rename_script, NULL);
2103
2104         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2105                           rename_script, rc));
2106
2107         SAFE_FREE(rename_script);
2108
2109         if (rc == 0) {
2110                 smb_nscd_flush_user_cache();
2111         }
2112
2113         if (rc)
2114                 return NT_STATUS_UNSUCCESSFUL;
2115
2116         return NT_STATUS_OK;
2117 }
2118
2119 /**********************************************************************
2120  Helper function to determine for update_sam_account whether
2121  we need LDAP modification.
2122  *********************************************************************/
2123
2124 static bool element_is_set_or_changed(const struct samu *sampass,
2125                                       enum pdb_elements element)
2126 {
2127         return (IS_SAM_SET(sampass, element) ||
2128                 IS_SAM_CHANGED(sampass, element));
2129 }
2130
2131 /**********************************************************************
2132  Add struct samu to LDAP.
2133 *********************************************************************/
2134
2135 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2136 {
2137         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2138         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2139         int rc;
2140         LDAPMessage     *result = NULL;
2141         LDAPMessage     *entry  = NULL;
2142         LDAPMod         **mods = NULL;
2143         int             ldap_op = LDAP_MOD_REPLACE;
2144         uint32          num_result;
2145         const char      **attr_list;
2146         char *escape_user = NULL;
2147         const char      *username = pdb_get_username(newpwd);
2148         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
2149         char *filter = NULL;
2150         char *dn = NULL;
2151         fstring         sid_string;
2152         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2153         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2154
2155         if (!ctx) {
2156                 return NT_STATUS_NO_MEMORY;
2157         }
2158
2159         if (!username || !*username) {
2160                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2161                 status = NT_STATUS_INVALID_PARAMETER;
2162                 goto fn_exit;
2163         }
2164
2165         /* free this list after the second search or in case we exit on failure */
2166         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2167
2168         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2169
2170         if (rc != LDAP_SUCCESS) {
2171                 goto fn_exit;
2172         }
2173
2174         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2175                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2176                          username));
2177                 goto fn_exit;
2178         }
2179         ldap_msgfree(result);
2180         result = NULL;
2181
2182         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
2183                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2184                                                   sid, &result);
2185                 if (rc == LDAP_SUCCESS) {
2186                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2187                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
2188                                          sid_to_string(sid_string, sid)));
2189                                 goto fn_exit;
2190                         }
2191                         ldap_msgfree(result);
2192                         result = NULL;
2193                 }
2194         }
2195
2196         /* does the entry already exist but without a samba attributes?
2197            we need to return the samba attributes here */
2198
2199         escape_user = escape_ldap_string_alloc( username );
2200         filter = talloc_strdup(attr_list, "(uid=%u)");
2201         if (!filter) {
2202                 status = NT_STATUS_NO_MEMORY;
2203                 goto fn_exit;
2204         }
2205         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2206         if (!filter) {
2207                 status = NT_STATUS_NO_MEMORY;
2208                 goto fn_exit;
2209         }
2210         SAFE_FREE(escape_user);
2211
2212         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2213                                    filter, attr_list, &result);
2214         if ( rc != LDAP_SUCCESS ) {
2215                 goto fn_exit;
2216         }
2217
2218         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2219
2220         if (num_result > 1) {
2221                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2222                 goto fn_exit;
2223         }
2224
2225         /* Check if we need to update an existing entry */
2226         if (num_result == 1) {
2227                 char *tmp;
2228
2229                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2230                 ldap_op = LDAP_MOD_REPLACE;
2231                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2232                 tmp = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2233                 if (!tmp) {
2234                         goto fn_exit;
2235                 }
2236                 dn = talloc_asprintf(ctx, "%s", tmp);
2237                 SAFE_FREE(tmp);
2238                 if (!dn) {
2239                         status = NT_STATUS_NO_MEMORY;
2240                         goto fn_exit;
2241                 }
2242
2243         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2244
2245                 /* There might be a SID for this account already - say an idmap entry */
2246
2247                 filter = talloc_asprintf(ctx,
2248                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2249                                  get_userattr_key2string(ldap_state->schema_ver,
2250                                          LDAP_ATTR_USER_SID),
2251                                  sid_string_talloc(ctx, sid),
2252                                  LDAP_OBJ_IDMAP_ENTRY,
2253                                  LDAP_OBJ_SID_ENTRY);
2254                 if (!filter) {
2255                         status = NT_STATUS_NO_MEMORY;
2256                         goto fn_exit;
2257                 }
2258
2259                 /* free old result before doing a new search */
2260                 if (result != NULL) {
2261                         ldap_msgfree(result);
2262                         result = NULL;
2263                 }
2264                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2265                                            filter, attr_list, &result);
2266
2267                 if ( rc != LDAP_SUCCESS ) {
2268                         goto fn_exit;
2269                 }
2270
2271                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2272
2273                 if (num_result > 1) {
2274                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2275                         goto fn_exit;
2276                 }
2277
2278                 /* Check if we need to update an existing entry */
2279                 if (num_result == 1) {
2280                         char *tmp;
2281
2282                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2283                         ldap_op = LDAP_MOD_REPLACE;
2284                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2285                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2286                         if (!tmp) {
2287                                 goto fn_exit;
2288                         }
2289                         dn = talloc_asprintf(ctx, "%s", tmp);
2290                         SAFE_FREE(tmp);
2291                         if (!dn) {
2292                                 status = NT_STATUS_NO_MEMORY;
2293                                 goto fn_exit;
2294                         }
2295                 }
2296         }
2297
2298         if (num_result == 0) {
2299                 char *escape_username;
2300                 /* Check if we need to add an entry */
2301                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2302                 ldap_op = LDAP_MOD_ADD;
2303
2304                 escape_username = escape_rdn_val_string_alloc(username);
2305                 if (!escape_username) {
2306                         status = NT_STATUS_NO_MEMORY;
2307                         goto fn_exit;
2308                 }
2309
2310                 if (username[strlen(username)-1] == '$') {
2311                         dn = talloc_asprintf(ctx,
2312                                         "uid=%s,%s",
2313                                         escape_username,
2314                                         lp_ldap_machine_suffix());
2315                 } else {
2316                         dn = talloc_asprintf(ctx,
2317                                         "uid=%s,%s",
2318                                         escape_username,
2319                                         lp_ldap_user_suffix());
2320                 }
2321
2322                 SAFE_FREE(escape_username);
2323                 if (!dn) {
2324                         status = NT_STATUS_NO_MEMORY;
2325                         goto fn_exit;
2326                 }
2327         }
2328
2329         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2330                                 element_is_set_or_changed)) {
2331                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2332                 if (mods != NULL) {
2333                         ldap_mods_free(mods, true);
2334                 }
2335                 goto fn_exit;
2336         }
2337
2338         if (mods == NULL) {
2339                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2340                 goto fn_exit;
2341         }
2342         switch ( ldap_state->schema_ver ) {
2343                 case SCHEMAVER_SAMBAACCOUNT:
2344                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2345                         break;
2346                 case SCHEMAVER_SAMBASAMACCOUNT:
2347                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2348                         break;
2349                 default:
2350                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2351                         break;
2352         }
2353
2354         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2355         if (!NT_STATUS_IS_OK(ret)) {
2356                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2357                          pdb_get_username(newpwd),dn));
2358                 ldap_mods_free(mods, true);
2359                 goto fn_exit;
2360         }
2361
2362         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2363         ldap_mods_free(mods, true);
2364
2365         status = NT_STATUS_OK;
2366
2367   fn_exit:
2368
2369         TALLOC_FREE(ctx);
2370         SAFE_FREE(escape_user);
2371         if (result) {
2372                 ldap_msgfree(result);
2373         }
2374         return status;
2375 }
2376
2377 /**********************************************************************
2378  *********************************************************************/
2379
2380 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2381                                      const char *filter,
2382                                      LDAPMessage ** result)
2383 {
2384         int scope = LDAP_SCOPE_SUBTREE;
2385         int rc;
2386         const char **attr_list;
2387
2388         attr_list = get_attr_list(NULL, groupmap_attr_list);
2389         rc = smbldap_search(ldap_state->smbldap_state,
2390                             lp_ldap_group_suffix (), scope,
2391                             filter, attr_list, 0, result);
2392         TALLOC_FREE(attr_list);
2393
2394         return rc;
2395 }
2396
2397 /**********************************************************************
2398  *********************************************************************/
2399
2400 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2401                                  GROUP_MAP *map, LDAPMessage *entry)
2402 {
2403         char *temp = NULL;
2404         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2405
2406         if (ldap_state == NULL || map == NULL || entry == NULL ||
2407                         ldap_state->smbldap_state->ldap_struct == NULL) {
2408                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2409                 TALLOC_FREE(ctx);
2410                 return false;
2411         }
2412
2413         temp = smbldap_talloc_single_attribute(
2414                         ldap_state->smbldap_state->ldap_struct,
2415                         entry,
2416                         get_attr_key2string(groupmap_attr_list,
2417                                 LDAP_ATTR_GIDNUMBER),
2418                         ctx);
2419         if (!temp) {
2420                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2421                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2422                 TALLOC_FREE(ctx);
2423                 return false;
2424         }
2425         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2426
2427         map->gid = (gid_t)atol(temp);
2428
2429         TALLOC_FREE(temp);
2430         temp = smbldap_talloc_single_attribute(
2431                         ldap_state->smbldap_state->ldap_struct,
2432                         entry,
2433                         get_attr_key2string(groupmap_attr_list,
2434                                 LDAP_ATTR_GROUP_SID),
2435                         ctx);
2436         if (!temp) {
2437                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2438                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2439                 TALLOC_FREE(ctx);
2440                 return false;
2441         }
2442
2443         if (!string_to_sid(&map->sid, temp)) {
2444                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2445                 TALLOC_FREE(ctx);
2446                 return false;
2447         }
2448
2449         TALLOC_FREE(temp);
2450         temp = smbldap_talloc_single_attribute(
2451                         ldap_state->smbldap_state->ldap_struct,
2452                         entry,
2453                         get_attr_key2string(groupmap_attr_list,
2454                                 LDAP_ATTR_GROUP_TYPE),
2455                         ctx);
2456         if (!temp) {
2457                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2458                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2459                 TALLOC_FREE(ctx);
2460                 return false;
2461         }
2462         map->sid_name_use = (enum lsa_SidType)atol(temp);
2463
2464         if ((map->sid_name_use < SID_NAME_USER) ||
2465                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2466                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2467                 TALLOC_FREE(ctx);
2468                 return false;
2469         }
2470
2471         TALLOC_FREE(temp);
2472         temp = smbldap_talloc_single_attribute(
2473                         ldap_state->smbldap_state->ldap_struct,
2474                         entry,
2475                         get_attr_key2string(groupmap_attr_list,
2476                                 LDAP_ATTR_DISPLAY_NAME),
2477                         ctx);
2478         if (!temp) {
2479                 temp = smbldap_talloc_single_attribute(
2480                                 ldap_state->smbldap_state->ldap_struct,
2481                                 entry,
2482                                 get_attr_key2string(groupmap_attr_list,
2483                                         LDAP_ATTR_CN),
2484                                 ctx);
2485                 if (!temp) {
2486                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2487 for gidNumber(%lu)\n",(unsigned long)map->gid));
2488                         TALLOC_FREE(ctx);
2489                         return false;
2490                 }
2491         }
2492         fstrcpy(map->nt_name, temp);
2493
2494         TALLOC_FREE(temp);
2495         temp = smbldap_talloc_single_attribute(
2496                         ldap_state->smbldap_state->ldap_struct,
2497                         entry,
2498                         get_attr_key2string(groupmap_attr_list,
2499                                 LDAP_ATTR_DESC),
2500                         ctx);
2501         if (!temp) {
2502                 temp = talloc_strdup(ctx, "");
2503                 if (!temp) {
2504                         TALLOC_FREE(ctx);
2505                         return false;
2506                 }
2507         }
2508         fstrcpy(map->comment, temp);
2509
2510         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2511                 store_gid_sid_cache(&map->sid, map->gid);
2512         }
2513
2514         TALLOC_FREE(ctx);
2515         return true;
2516 }
2517
2518 /**********************************************************************
2519  *********************************************************************/
2520
2521 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2522                                  const char *filter,
2523                                  GROUP_MAP *map)
2524 {
2525         struct ldapsam_privates *ldap_state =
2526                 (struct ldapsam_privates *)methods->private_data;
2527         LDAPMessage *result = NULL;
2528         LDAPMessage *entry = NULL;
2529         int count;
2530
2531         if (ldapsam_search_one_group(ldap_state, filter, &result)
2532             != LDAP_SUCCESS) {
2533                 return NT_STATUS_NO_SUCH_GROUP;
2534         }
2535
2536         count = ldap_count_entries(priv2ld(ldap_state), result);
2537
2538         if (count < 1) {
2539                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2540                           "%s\n", filter));
2541                 ldap_msgfree(result);
2542                 return NT_STATUS_NO_SUCH_GROUP;
2543         }
2544
2545         if (count > 1) {
2546                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2547                           "count=%d\n", filter, count));
2548                 ldap_msgfree(result);
2549                 return NT_STATUS_NO_SUCH_GROUP;
2550         }
2551
2552         entry = ldap_first_entry(priv2ld(ldap_state), result);
2553
2554         if (!entry) {
2555                 ldap_msgfree(result);
2556                 return NT_STATUS_UNSUCCESSFUL;
2557         }
2558
2559         if (!init_group_from_ldap(ldap_state, map, entry)) {
2560                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2561                           "group filter %s\n", filter));
2562                 ldap_msgfree(result);
2563                 return NT_STATUS_NO_SUCH_GROUP;
2564         }
2565
2566         ldap_msgfree(result);
2567         return NT_STATUS_OK;
2568 }
2569
2570 /**********************************************************************
2571  *********************************************************************/
2572
2573 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2574                                  DOM_SID sid)
2575 {
2576         char *filter = NULL;
2577         NTSTATUS status;
2578
2579         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2580                 LDAP_OBJ_GROUPMAP,
2581                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2582                 sid_string_static(&sid)) < 0) {
2583                 return NT_STATUS_NO_MEMORY;
2584         }
2585
2586         status = ldapsam_getgroup(methods, filter, map);
2587         SAFE_FREE(filter);
2588         return status;
2589 }
2590
2591 /**********************************************************************
2592  *********************************************************************/
2593
2594 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2595                                  gid_t gid)
2596 {
2597         char *filter = NULL;
2598         NTSTATUS status;
2599
2600         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2601                 LDAP_OBJ_GROUPMAP,
2602                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2603                 (unsigned long)gid) < 0) {
2604                 return NT_STATUS_NO_MEMORY;
2605         }
2606
2607         status = ldapsam_getgroup(methods, filter, map);
2608         SAFE_FREE(filter);
2609         return status;
2610 }
2611
2612 /**********************************************************************
2613  *********************************************************************/
2614
2615 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2616                                  const char *name)
2617 {
2618         char *filter = NULL;
2619         char *escape_name = escape_ldap_string_alloc(name);
2620         NTSTATUS status;
2621
2622         if (!escape_name) {
2623                 return NT_STATUS_NO_MEMORY;
2624         }
2625
2626         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2627                 LDAP_OBJ_GROUPMAP,
2628                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2629                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2630                 escape_name) < 0) {
2631                 SAFE_FREE(escape_name);
2632                 return NT_STATUS_NO_MEMORY;
2633         }
2634
2635         SAFE_FREE(escape_name);
2636         status = ldapsam_getgroup(methods, filter, map);
2637         SAFE_FREE(filter);
2638         return status;
2639 }
2640
2641 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2642                                            LDAPMessage *entry,
2643                                            const DOM_SID *domain_sid,
2644                                            uint32 *rid)
2645 {
2646         fstring str;
2647         DOM_SID sid;
2648
2649         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2650                                           str, sizeof(str)-1)) {
2651                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2652                 return False;
2653         }
2654
2655         if (!string_to_sid(&sid, str)) {
2656                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2657                 return False;
2658         }
2659
2660         if (sid_compare_domain(&sid, domain_sid) != 0) {
2661                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2662                            str, sid_string_static(domain_sid)));
2663                 return False;
2664         }
2665
2666         if (!sid_peek_rid(&sid, rid)) {
2667                 DEBUG(10, ("Could not peek into RID\n"));
2668                 return False;
2669         }
2670
2671         return True;
2672 }
2673
2674 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2675                                            TALLOC_CTX *mem_ctx,
2676                                            const DOM_SID *group,
2677                                            uint32 **pp_member_rids,
2678                                            size_t *p_num_members)
2679 {
2680         struct ldapsam_privates *ldap_state =
2681                 (struct ldapsam_privates *)methods->private_data;
2682         struct smbldap_state *conn = ldap_state->smbldap_state;
2683         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2684         const char *sid_attrs[] = { "sambaSID", NULL };
2685         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2686         LDAPMessage *result = NULL;
2687         LDAPMessage *entry;
2688         char *filter;
2689         char **values = NULL;
2690         char **memberuid;
2691         char *gidstr;
2692         int rc, count;
2693
2694         *pp_member_rids = NULL;
2695         *p_num_members = 0;
2696
2697         filter = talloc_asprintf(mem_ctx,
2698                                  "(&(objectClass=%s)"
2699                                  "(objectClass=%s)"
2700                                  "(sambaSID=%s))",
2701                                  LDAP_OBJ_POSIXGROUP,
2702                                  LDAP_OBJ_GROUPMAP,
2703                                  sid_string_talloc(mem_ctx, group));
2704         if (filter == NULL) {
2705                 ret = NT_STATUS_NO_MEMORY;
2706                 goto done;
2707         }
2708
2709         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2710                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2711                             &result);
2712
2713         if (rc != LDAP_SUCCESS)
2714                 goto done;
2715
2716         talloc_autofree_ldapmsg(mem_ctx, result);
2717
2718         count = ldap_count_entries(conn->ldap_struct, result);
2719
2720         if (count > 1) {
2721                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2722                           sid_string_static(group)));
2723                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2724                 goto done;
2725         }
2726
2727         if (count == 0) {
2728                 ret = NT_STATUS_NO_SUCH_GROUP;
2729                 goto done;
2730         }
2731
2732         entry = ldap_first_entry(conn->ldap_struct, result);
2733         if (entry == NULL)
2734                 goto done;
2735
2736         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2737         if (!gidstr) {
2738                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2739                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2740                 goto done;
2741         }
2742
2743         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2744
2745         if (values) {
2746
2747                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2748                 if (filter == NULL) {
2749                         ret = NT_STATUS_NO_MEMORY;
2750                         goto done;
2751                 }
2752
2753                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2754                         char *escape_memberuid;
2755
2756                         escape_memberuid = escape_ldap_string_alloc(*memberuid);
2757                         if (escape_memberuid == NULL) {
2758                                 ret = NT_STATUS_NO_MEMORY;
2759                                 goto done;
2760                         }
2761                         
2762                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2763                         if (filter == NULL) {
2764                                 SAFE_FREE(escape_memberuid);
2765                                 ret = NT_STATUS_NO_MEMORY;
2766                                 goto done;
2767                         }
2768
2769                         SAFE_FREE(escape_memberuid);
2770                 }
2771
2772                 filter = talloc_asprintf_append_buffer(filter, "))");
2773                 if (filter == NULL) {
2774                         ret = NT_STATUS_NO_MEMORY;
2775                         goto done;
2776                 }
2777
2778                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2779                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2780                                     &result);
2781
2782                 if (rc != LDAP_SUCCESS)
2783                         goto done;
2784
2785                 count = ldap_count_entries(conn->ldap_struct, result);
2786                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2787
2788                 talloc_autofree_ldapmsg(mem_ctx, result);
2789
2790                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2791                      entry != NULL;
2792                      entry = ldap_next_entry(conn->ldap_struct, entry))
2793                 {
2794                         char *sidstr;
2795                         DOM_SID sid;
2796                         uint32 rid;
2797
2798                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2799                                                                  entry, "sambaSID",
2800                                                                  mem_ctx);
2801                         if (!sidstr) {
2802                                 DEBUG(0, ("Severe DB error, sambaSamAccount can't miss "
2803                                           "the sambaSID attribute\n"));
2804                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2805                                 goto done;
2806                         }
2807
2808                         if (!string_to_sid(&sid, sidstr))
2809                                 goto done;
2810
2811                         if (!sid_check_is_in_our_domain(&sid)) {
2812                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2813                                           "in our domain\n"));
2814                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2815                                 goto done;
2816                         }
2817
2818                         sid_peek_rid(&sid, &rid);
2819
2820                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2821                                                 p_num_members)) {
2822                                 ret = NT_STATUS_NO_MEMORY;
2823                                 goto done;
2824                         }
2825                 }
2826         }
2827
2828         filter = talloc_asprintf(mem_ctx,
2829                                  "(&(objectClass=%s)"
2830                                  "(gidNumber=%s))",
2831                                  LDAP_OBJ_SAMBASAMACCOUNT,
2832                                  gidstr);
2833
2834         rc = smbldap_search(conn, lp_ldap_user_suffix(),
2835                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2836                             &result);
2837
2838         if (rc != LDAP_SUCCESS)
2839                 goto done;
2840
2841         talloc_autofree_ldapmsg(mem_ctx, result);
2842
2843         for (entry = ldap_first_entry(conn->ldap_struct, result);
2844              entry != NULL;
2845              entry = ldap_next_entry(conn->ldap_struct, entry))
2846         {
2847                 uint32 rid;
2848
2849                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2850                                                     entry,
2851                                                     get_global_sam_sid(),
2852                                                     &rid)) {
2853                         DEBUG(0, ("Severe DB error, sambaSamAccount can't miss "
2854                                   "the sambaSID attribute\n"));
2855                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2856                         goto done;
2857                 }
2858
2859                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2860                                         p_num_members)) {
2861                         ret = NT_STATUS_NO_MEMORY;
2862                         goto done;
2863                 }
2864         }
2865
2866         ret = NT_STATUS_OK;
2867         
2868  done:
2869
2870         if (values)
2871                 ldap_value_free(values);
2872
2873         return ret;
2874 }
2875
2876 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2877                                                TALLOC_CTX *mem_ctx,
2878                                                struct samu *user,
2879                                                DOM_SID **pp_sids,
2880                                                gid_t **pp_gids,
2881                                                size_t *p_num_groups)
2882 {
2883         struct ldapsam_privates *ldap_state =
2884                 (struct ldapsam_privates *)methods->private_data;
2885         struct smbldap_state *conn = ldap_state->smbldap_state;
2886         char *filter;
2887         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2888         char *escape_name;
2889         int rc, count;
2890         LDAPMessage *result = NULL;
2891         LDAPMessage *entry;
2892         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2893         size_t num_sids, num_gids;
2894         char *gidstr;
2895         gid_t primary_gid = -1;
2896
2897         *pp_sids = NULL;
2898         num_sids = 0;
2899
2900         if (pdb_get_username(user) == NULL) {
2901                 return NT_STATUS_INVALID_PARAMETER;
2902         }
2903
2904         escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2905         if (escape_name == NULL)
2906                 return NT_STATUS_NO_MEMORY;
2907
2908         /* retrieve the users primary gid */
2909         filter = talloc_asprintf(mem_ctx,
2910                                  "(&(objectClass=%s)(uid=%s))",
2911                                  LDAP_OBJ_SAMBASAMACCOUNT,
2912                                  escape_name);
2913         if (filter == NULL) {
2914                 ret = NT_STATUS_NO_MEMORY;
2915                 goto done;
2916         }
2917
2918         rc = smbldap_search(conn, lp_ldap_user_suffix(),
2919                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2920
2921         if (rc != LDAP_SUCCESS)
2922                 goto done;
2923
2924         talloc_autofree_ldapmsg(mem_ctx, result);
2925
2926         count = ldap_count_entries(priv2ld(ldap_state), result);
2927
2928         switch (count) {
2929         case 0: 
2930                 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2931                 ret = NT_STATUS_NO_SUCH_USER;
2932                 goto done;
2933         case 1:
2934                 entry = ldap_first_entry(priv2ld(ldap_state), result);
2935
2936                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2937                 if (!gidstr) {
2938                         DEBUG (1, ("Unable to find the member's gid!\n"));
2939                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2940                         goto done;
2941                 }
2942                 primary_gid = strtoul(gidstr, NULL, 10);
2943                 break;
2944         default:
2945                 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2946                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2947                 goto done;
2948         }
2949
2950         filter = talloc_asprintf(mem_ctx,
2951                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%d)))",
2952                                  LDAP_OBJ_POSIXGROUP, escape_name, primary_gid);
2953         if (filter == NULL) {
2954                 ret = NT_STATUS_NO_MEMORY;
2955                 goto done;
2956         }
2957
2958         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2959                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2960
2961         if (rc != LDAP_SUCCESS)
2962                 goto done;
2963
2964         talloc_autofree_ldapmsg(mem_ctx, result);
2965
2966         num_gids = 0;
2967         *pp_gids = NULL;
2968
2969         num_sids = 0;
2970         *pp_sids = NULL;
2971
2972         /* We need to add the primary group as the first gid/sid */
2973
2974         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2975                 ret = NT_STATUS_NO_MEMORY;
2976                 goto done;
2977         }
2978
2979         /* This sid will be replaced later */
2980
2981         if (!add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids, &num_sids)) {
2982                 ret = NT_STATUS_NO_MEMORY;
2983                 goto done;
2984         }
2985
2986         for (entry = ldap_first_entry(conn->ldap_struct, result);
2987              entry != NULL;
2988              entry = ldap_next_entry(conn->ldap_struct, entry))
2989         {
2990                 fstring str;
2991                 DOM_SID sid;
2992                 gid_t gid;
2993                 char *end;
2994
2995                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2996                                                   entry, "sambaSID",
2997                                                   str, sizeof(str)-1))
2998                         continue;
2999
3000                 if (!string_to_sid(&sid, str))
3001                         goto done;
3002
3003                 if (!smbldap_get_single_attribute(conn->ldap_struct,
3004                                                   entry, "gidNumber",
3005                                                   str, sizeof(str)-1))
3006                         continue;
3007
3008                 gid = strtoul(str, &end, 10);
3009
3010                 if (PTR_DIFF(end, str) != strlen(str))
3011                         goto done;
3012
3013                 if (gid == primary_gid) {
3014                         sid_copy(&(*pp_sids)[0], &sid);
3015                 } else {
3016                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
3017                                                 &num_gids)) {
3018                                 ret = NT_STATUS_NO_MEMORY;
3019                                 goto done;
3020                         }
3021                         if (!add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
3022                                                 &num_sids)) {
3023                                 ret = NT_STATUS_NO_MEMORY;
3024                                 goto done;
3025                         }
3026                 }
3027         }
3028
3029         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
3030                 DEBUG(3, ("primary group of [%s] not found\n",
3031                           pdb_get_username(user)));
3032                 goto done;
3033         }
3034
3035         *p_num_groups = num_sids;
3036
3037         ret = NT_STATUS_OK;
3038
3039  done:
3040
3041         SAFE_FREE(escape_name);
3042         return ret;
3043 }
3044
3045 /**********************************************************************
3046  * Augment a posixGroup object with a sambaGroupMapping domgroup
3047  *********************************************************************/
3048
3049 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
3050                                        struct ldapsam_privates *ldap_state,
3051                                        GROUP_MAP *map)
3052 {
3053         const char *filter, *dn;
3054         LDAPMessage *msg, *entry;
3055         LDAPMod **mods;
3056         int rc;
3057
3058         filter = talloc_asprintf(mem_ctx,
3059                                  "(&(objectClass=posixGroup)(gidNumber=%u))",
3060                                  map->gid);
3061         if (filter == NULL) {
3062                 return NT_STATUS_NO_MEMORY;
3063         }
3064
3065         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3066                                    get_attr_list(mem_ctx, groupmap_attr_list),
3067                                    &msg);
3068         talloc_autofree_ldapmsg(mem_ctx, msg);
3069
3070         if ((rc != LDAP_SUCCESS) ||
3071             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3072             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3073                 return NT_STATUS_NO_SUCH_GROUP;
3074         }
3075
3076         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3077         if (dn == NULL) {
3078                 return NT_STATUS_NO_MEMORY;
3079         }
3080
3081         mods = NULL;
3082         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3083                         "sambaGroupMapping");
3084         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3085                          sid_string_static(&map->sid));
3086         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3087                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3088         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3089                          map->nt_name);
3090         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3091                          map->comment);
3092         talloc_autofree_ldapmod(mem_ctx, mods);
3093
3094         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3095         if (rc != LDAP_SUCCESS) {
3096                 return NT_STATUS_ACCESS_DENIED;
3097         }
3098
3099         return NT_STATUS_OK;
3100 }
3101
3102 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3103                                                 GROUP_MAP *map)
3104 {
3105         struct ldapsam_privates *ldap_state =
3106                 (struct ldapsam_privates *)methods->private_data;
3107         LDAPMessage *msg = NULL;
3108         LDAPMod **mods = NULL;
3109         const char *attrs[] = { NULL };
3110         char *filter;
3111
3112         char *dn;
3113         TALLOC_CTX *mem_ctx;
3114         NTSTATUS result;
3115
3116         DOM_SID sid;
3117
3118         int rc;
3119
3120         mem_ctx = talloc_new(NULL);
3121         if (mem_ctx == NULL) {
3122                 DEBUG(0, ("talloc_new failed\n"));
3123                 return NT_STATUS_NO_MEMORY;
3124         }
3125
3126         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3127                                  sid_string_talloc(mem_ctx, &map->sid));
3128         if (filter == NULL) {
3129                 result = NT_STATUS_NO_MEMORY;
3130                 goto done;
3131         }
3132
3133         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3134                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3135         talloc_autofree_ldapmsg(mem_ctx, msg);
3136
3137         if ((rc == LDAP_SUCCESS) &&
3138             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3139
3140                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3141                           "group mapping entry\n",
3142                           sid_string_static(&map->sid)));
3143                 result = NT_STATUS_GROUP_EXISTS;
3144                 goto done;
3145         }
3146
3147         switch (map->sid_name_use) {
3148
3149         case SID_NAME_DOM_GRP:
3150                 /* To map a domain group we need to have a posix group
3151                    to attach to. */
3152                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3153                 goto done;
3154                 break;
3155
3156         case SID_NAME_ALIAS:
3157                 if (!sid_check_is_in_our_domain(&map->sid) 
3158                         && !sid_check_is_in_builtin(&map->sid) ) 
3159                 {
3160                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3161                                   sid_string_static(&map->sid)));
3162                         result = NT_STATUS_INVALID_PARAMETER;
3163                         goto done;
3164                 }
3165                 break;
3166
3167         default:
3168                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3169                           sid_type_lookup(map->sid_name_use)));
3170                 result = NT_STATUS_INVALID_PARAMETER;
3171                 goto done;
3172         }
3173
3174         /* Domain groups have been mapped in a separate routine, we have to
3175          * create an alias now */
3176
3177         if (map->gid == -1) {
3178                 DEBUG(10, ("Refusing to map gid==-1\n"));
3179                 result = NT_STATUS_INVALID_PARAMETER;
3180                 goto done;
3181         }
3182
3183         if (pdb_gid_to_sid(map->gid, &sid)) {
3184                 DEBUG(3, ("Gid %d is already mapped to SID %s, refusing to "
3185                           "add\n", map->gid, sid_string_static(&sid)));
3186                 result = NT_STATUS_GROUP_EXISTS;
3187                 goto done;
3188         }
3189
3190         /* Ok, enough checks done. It's still racy to go ahead now, but that's
3191          * the best we can get out of LDAP. */
3192
3193         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3194                              sid_string_talloc(mem_ctx, &map->sid),
3195                              lp_ldap_group_suffix());
3196         if (dn == NULL) {
3197                 result = NT_STATUS_NO_MEMORY;
3198                 goto done;
3199         }
3200
3201         mods = NULL;
3202
3203         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3204                          "sambaSidEntry");
3205         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3206                          "sambaGroupMapping");
3207
3208         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3209                          sid_string_talloc(mem_ctx, &map->sid));
3210         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3211                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3212         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3213                          map->nt_name);
3214         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3215                          map->comment);
3216         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3217                          talloc_asprintf(mem_ctx, "%u", map->gid));
3218         talloc_autofree_ldapmod(mem_ctx, mods);
3219
3220         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3221
3222         result = (rc == LDAP_SUCCESS) ?
3223                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3224
3225  done:
3226         TALLOC_FREE(mem_ctx);
3227         return result;
3228 }
3229
3230 /**********************************************************************
3231  * Update a group mapping entry. We're quite strict about what can be changed:
3232  * Only the description and displayname may be changed. It simply does not
3233  * make any sense to change the SID, gid or the type in a mapping.
3234  *********************************************************************/
3235
3236 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3237                                                    GROUP_MAP *map)
3238 {
3239         struct ldapsam_privates *ldap_state =
3240                 (struct ldapsam_privates *)methods->private_data;
3241         int rc;
3242         const char *filter, *dn;
3243         LDAPMessage *msg = NULL;
3244         LDAPMessage *entry = NULL;
3245         LDAPMod **mods = NULL;
3246         TALLOC_CTX *mem_ctx;
3247         NTSTATUS result;
3248
3249         mem_ctx = talloc_new(NULL);
3250         if (mem_ctx == NULL) {
3251                 DEBUG(0, ("talloc_new failed\n"));
3252                 return NT_STATUS_NO_MEMORY;
3253         }
3254
3255         /* Make 100% sure that sid, gid and type are not changed by looking up
3256          * exactly the values we're given in LDAP. */
3257
3258         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3259                                  "(sambaSid=%s)(gidNumber=%u)"
3260                                  "(sambaGroupType=%d))",
3261                                  LDAP_OBJ_GROUPMAP,
3262                                  sid_string_talloc(mem_ctx, &map->sid),
3263                                  map->gid, map->sid_name_use);
3264         if (filter == NULL) {
3265                 result = NT_STATUS_NO_MEMORY;
3266                 goto done;
3267         }
3268
3269         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3270                                    get_attr_list(mem_ctx, groupmap_attr_list),
3271                                    &msg);
3272         talloc_autofree_ldapmsg(mem_ctx, msg);
3273
3274         if ((rc != LDAP_SUCCESS) ||
3275             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3276             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3277                 result = NT_STATUS_NO_SUCH_GROUP;
3278                 goto done;
3279         }
3280
3281         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3282
3283         if (dn == NULL) {
3284                 result = NT_STATUS_NO_MEMORY;
3285                 goto done;
3286         }
3287
3288         mods = NULL;
3289         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3290                          map->nt_name);
3291         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3292                          map->comment);
3293         talloc_autofree_ldapmod(mem_ctx, mods);
3294
3295         if (mods == NULL) {
3296                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3297                           "nothing to do\n"));
3298                 result = NT_STATUS_OK;
3299                 goto done;
3300         }
3301
3302         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3303
3304         if (rc != LDAP_SUCCESS) {
3305                 result = NT_STATUS_ACCESS_DENIED;
3306                 goto done;
3307         }
3308
3309         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3310                   "group %lu in LDAP\n", (unsigned long)map->gid));
3311
3312         result = NT_STATUS_OK;
3313
3314  done:
3315         TALLOC_FREE(mem_ctx);
3316         return result;
3317 }
3318
3319 /**********************************************************************
3320  *********************************************************************/
3321
3322 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3323                                                    DOM_SID sid)
3324 {
3325         struct ldapsam_privates *priv =
3326                 (struct ldapsam_privates *)methods->private_data;
3327         LDAPMessage *msg, *entry;
3328         int rc;
3329         NTSTATUS result;
3330         TALLOC_CTX *mem_ctx;
3331         char *filter;
3332
3333         mem_ctx = talloc_new(NULL);
3334         if (mem_ctx == NULL) {
3335                 DEBUG(0, ("talloc_new failed\n"));
3336                 return NT_STATUS_NO_MEMORY;
3337         }
3338
3339         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3340                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3341                                  sid_string_talloc(mem_ctx, &sid));
3342         if (filter == NULL) {
3343                 result = NT_STATUS_NO_MEMORY;
3344                 goto done;
3345         }
3346         rc = smbldap_search_suffix(priv->smbldap_state, filter,
3347                                    get_attr_list(mem_ctx, groupmap_attr_list),
3348                                    &msg);
3349         talloc_autofree_ldapmsg(mem_ctx, msg);
3350
3351         if ((rc != LDAP_SUCCESS) ||
3352             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3353             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3354                 result = NT_STATUS_NO_SUCH_GROUP;
3355                 goto done;
3356         }
3357
3358         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3359                                   get_attr_list(mem_ctx,
3360                                                 groupmap_attr_list_to_delete));
3361  
3362         if ((rc == LDAP_NAMING_VIOLATION) ||
3363             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3364                 const char *attrs[] = { "sambaGroupType", "description",
3365                                         "displayName", "sambaSIDList",
3366                                         NULL };
3367
3368                 /* Second try. Don't delete the sambaSID attribute, this is
3369                    for "old" entries that are tacked on a winbind
3370                    sambaIdmapEntry. */
3371
3372                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3373                                           LDAP_OBJ_GROUPMAP, attrs);
3374         }
3375
3376         if ((rc == LDAP_NAMING_VIOLATION) ||
3377             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3378                 const char *attrs[] = { "sambaGroupType", "description",
3379                                         "displayName", "sambaSIDList",
3380                                         "gidNumber", NULL };
3381
3382                 /* Third try. This is a post-3.0.21 alias (containing only
3383                  * sambaSidEntry and sambaGroupMapping classes), we also have
3384                  * to delete the gidNumber attribute, only the sambaSidEntry
3385                  * remains */
3386
3387                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3388                                           LDAP_OBJ_GROUPMAP, attrs);
3389         }
3390
3391         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3392
3393  done:
3394         TALLOC_FREE(mem_ctx);
3395         return result;
3396  }
3397
3398 /**********************************************************************
3399  *********************************************************************/
3400
3401 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3402                                     bool update)
3403 {
3404         struct ldapsam_privates *ldap_state =
3405                 (struct ldapsam_privates *)my_methods->private_data;
3406         char *filter = NULL;
3407         int rc;
3408         const char **attr_list;
3409
3410         filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3411         if (!filter) {
3412                 return NT_STATUS_NO_MEMORY;
3413         }
3414         attr_list = get_attr_list( NULL, groupmap_attr_list );
3415         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3416                             LDAP_SCOPE_SUBTREE, filter,
3417                             attr_list, 0, &ldap_state->result);
3418         TALLOC_FREE(attr_list);
3419
3420         if (rc != LDAP_SUCCESS) {
3421                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3422                           ldap_err2string(rc)));
3423                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3424                           lp_ldap_group_suffix(), filter));
3425                 ldap_msgfree(ldap_state->result);
3426                 ldap_state->result = NULL;
3427                 TALLOC_FREE(filter);
3428                 return NT_STATUS_UNSUCCESSFUL;
3429         }
3430
3431         TALLOC_FREE(filter);
3432
3433         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3434                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3435                                      ldap_state->result)));
3436
3437         ldap_state->entry =
3438                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3439                                  ldap_state->result);
3440         ldap_state->index = 0;
3441
3442         return NT_STATUS_OK;
3443 }
3444
3445 /**********************************************************************
3446  *********************************************************************/
3447
3448 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3449 {
3450         ldapsam_endsampwent(my_methods);
3451 }
3452
3453 /**********************************************************************
3454  *********************************************************************/
3455
3456 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3457                                     GROUP_MAP *map)
3458 {
3459         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3460         struct ldapsam_privates *ldap_state =
3461                 (struct ldapsam_privates *)my_methods->private_data;
3462         bool bret = False;
3463
3464         while (!bret) {
3465                 if (!ldap_state->entry)
3466                         return ret;
3467                 
3468                 ldap_state->index++;
3469                 bret = init_group_from_ldap(ldap_state, map,
3470                                             ldap_state->entry);
3471                 
3472                 ldap_state->entry =
3473                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3474                                         ldap_state->entry);     
3475         }
3476
3477         return NT_STATUS_OK;
3478 }
3479
3480 /**********************************************************************
3481  *********************************************************************/
3482
3483 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3484                                            const DOM_SID *domsid, enum lsa_SidType sid_name_use,
3485                                            GROUP_MAP **pp_rmap,
3486                                            size_t *p_num_entries,
3487                                            bool unix_only)
3488 {
3489         GROUP_MAP map;
3490         size_t entries = 0;
3491
3492         *p_num_entries = 0;
3493         *pp_rmap = NULL;
3494
3495         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3496                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3497                           "passdb\n"));
3498                 return NT_STATUS_ACCESS_DENIED;
3499         }
3500
3501         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3502                 if (sid_name_use != SID_NAME_UNKNOWN &&
3503                     sid_name_use != map.sid_name_use) {
3504                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3505                                   "not of the requested type\n", map.nt_name));
3506                         continue;
3507                 }
3508                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3509                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3510                                   "non mapped\n", map.nt_name));
3511                         continue;
3512                 }
3513
3514                 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3515                 if (!(*pp_rmap)) {
3516                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3517                                  "enlarge group map!\n"));
3518                         return NT_STATUS_UNSUCCESSFUL;
3519                 }
3520
3521                 (*pp_rmap)[entries] = map;
3522
3523                 entries += 1;
3524
3525         }
3526         ldapsam_endsamgrent(methods);
3527
3528         *p_num_entries = entries;
3529
3530         return NT_STATUS_OK;
3531 }
3532
3533 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3534                                         const DOM_SID *alias,
3535                                         const DOM_SID *member,
3536                                         int modop)
3537 {
3538         struct ldapsam_privates *ldap_state =
3539                 (struct ldapsam_privates *)methods->private_data;
3540         char *dn = NULL;
3541         LDAPMessage *result = NULL;
3542         LDAPMessage *entry = NULL;
3543         int count;
3544         LDAPMod **mods = NULL;
3545         int rc;
3546         enum lsa_SidType type = SID_NAME_USE_NONE;
3547
3548         char *filter = NULL;
3549
3550         if (sid_check_is_in_builtin(alias)) {
3551                 type = SID_NAME_ALIAS;
3552         }
3553
3554         if (sid_check_is_in_our_domain(alias)) {
3555                 type = SID_NAME_ALIAS;
3556         }
3557
3558         if (type == SID_NAME_USE_NONE) {
3559                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3560                           sid_string_static(alias)));
3561                 return NT_STATUS_NO_SUCH_ALIAS;
3562         }
3563
3564         if (asprintf(&filter,