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