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