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