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