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