Correctly check for errors in strlower_m() returns.
[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 #include "lib/param/loadparm.h"
56
57 #undef DBGC_CLASS
58 #define DBGC_CLASS DBGC_PASSDB
59
60 #include <lber.h>
61 #include <ldap.h>
62
63
64 #include "smbldap.h"
65 #include "passdb/pdb_ldap.h"
66 #include "passdb/pdb_nds.h"
67 #include "passdb/pdb_ipa.h"
68 #include "passdb/pdb_ldap_util.h"
69 #include "passdb/pdb_ldap_schema.h"
70
71 /**********************************************************************
72  Simple helper function to make stuff better readable
73  **********************************************************************/
74
75 LDAP *priv2ld(struct ldapsam_privates *priv)
76 {
77         return priv->smbldap_state->ldap_struct;
78 }
79
80 /**********************************************************************
81  Get the attribute name given a user schame version.
82  **********************************************************************/
83  
84 static const char* get_userattr_key2string( int schema_ver, int key )
85 {
86         switch ( schema_ver ) {
87                 case SCHEMAVER_SAMBASAMACCOUNT:
88                         return get_attr_key2string( attrib_map_v30, key );
89
90                 default:
91                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
92                         break;
93         }
94         return NULL;
95 }
96
97 /**********************************************************************
98  Return the list of attribute names given a user schema version.
99 **********************************************************************/
100
101 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
102 {
103         switch ( schema_ver ) {
104                 case SCHEMAVER_SAMBASAMACCOUNT:
105                         return get_attr_list( mem_ctx, attrib_map_v30 );
106                 default:
107                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
108                         break;
109         }
110
111         return NULL;
112 }
113
114 /**************************************************************************
115  Return the list of attribute names to delete given a user schema version.
116 **************************************************************************/
117
118 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
119                                               int schema_ver )
120 {
121         switch ( schema_ver ) {
122                 case SCHEMAVER_SAMBASAMACCOUNT:
123                         return get_attr_list( mem_ctx,
124                                               attrib_map_to_delete_v30 );
125                 default:
126                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
127                         break;
128         }
129
130         return NULL;
131 }
132
133
134 /*******************************************************************
135  Generate the LDAP search filter for the objectclass based on the 
136  version of the schema we are using.
137 ******************************************************************/
138
139 static const char* get_objclass_filter( int schema_ver )
140 {
141         fstring objclass_filter;
142         char *result;
143
144         switch( schema_ver ) {
145                 case SCHEMAVER_SAMBASAMACCOUNT:
146                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
147                         break;
148                 default:
149                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
150                         objclass_filter[0] = '\0';
151                         break;
152         }
153
154         result = talloc_strdup(talloc_tos(), objclass_filter);
155         SMB_ASSERT(result != NULL);
156         return result;
157 }
158
159 /*****************************************************************
160  Scan a sequence number off OpenLDAP's syncrepl contextCSN
161 ******************************************************************/
162
163 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
164 {
165         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
166         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
167         LDAPMessage *msg = NULL;
168         LDAPMessage *entry = NULL;
169         TALLOC_CTX *mem_ctx;
170         char **values = NULL;
171         int rc, num_result, num_values, rid;
172         char *suffix = NULL;
173         char *tok;
174         const char *p;
175         const char **attrs;
176
177         /* Unfortunatly there is no proper way to detect syncrepl-support in
178          * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
179          * but do not show up in the root-DSE yet. Neither we can query the
180          * subschema-context for the syncProviderSubentry or syncConsumerSubentry
181          * objectclass. Currently we require lp_ldap_suffix() to show up as
182          * namingContext.  -  Guenther
183          */
184
185         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
186                 return ntstatus;
187         }
188
189         if (!seq_num) {
190                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
191                 return ntstatus;
192         }
193
194         if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix(talloc_tos()))) {
195                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
196                          "as top-level namingContext\n", lp_ldap_suffix(talloc_tos())));
197                 return ntstatus;
198         }
199
200         mem_ctx = talloc_init("ldapsam_get_seq_num");
201
202         if (mem_ctx == NULL)
203                 return NT_STATUS_NO_MEMORY;
204
205         if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
206                 ntstatus = NT_STATUS_NO_MEMORY;
207                 goto done;
208         }
209
210         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
211         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
212         if (rid > 0) {
213
214                 /* consumer syncreplCookie: */
215                 /* csn=20050126161620Z#0000001#00#00000 */
216                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
217                 attrs[1] = NULL;
218                 suffix = talloc_asprintf(mem_ctx,
219                                 "cn=syncrepl%d,%s", rid, lp_ldap_suffix(talloc_tos()));
220                 if (!suffix) {
221                         ntstatus = NT_STATUS_NO_MEMORY;
222                         goto done;
223                 }
224         } else {
225
226                 /* provider contextCSN */
227                 /* 20050126161620Z#000009#00#000000 */
228                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
229                 attrs[1] = NULL;
230                 suffix = talloc_asprintf(mem_ctx,
231                                 "cn=ldapsync,%s", lp_ldap_suffix(talloc_tos()));
232
233                 if (!suffix) {
234                         ntstatus = NT_STATUS_NO_MEMORY;
235                         goto done;
236                 }
237         }
238
239         rc = smbldap_search(ldap_state->smbldap_state, suffix,
240                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
241
242         if (rc != LDAP_SUCCESS) {
243                 goto done;
244         }
245
246         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
247         if (num_result != 1) {
248                 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
249                 goto done;
250         }
251
252         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
253         if (entry == NULL) {
254                 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
255                 goto done;
256         }
257
258         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
259         if (values == NULL) {
260                 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
261                 goto done;
262         }
263
264         num_values = ldap_count_values(values);
265         if (num_values == 0) {
266                 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
267                 goto done;
268         }
269
270         p = values[0];
271         if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
272                 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
273                 goto done;
274         }
275
276         p = tok;
277         if (!strncmp(p, "csn=", strlen("csn=")))
278                 p += strlen("csn=");
279
280         DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
281
282         *seq_num = generalized_to_unix_time(p);
283
284         /* very basic sanity check */
285         if (*seq_num <= 0) {
286                 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n", 
287                         (int)*seq_num));
288                 goto done;
289         }
290
291         ntstatus = NT_STATUS_OK;
292
293  done:
294         if (values != NULL)
295                 ldap_value_free(values);
296         if (msg != NULL)
297                 ldap_msgfree(msg);
298         if (mem_ctx)
299                 talloc_destroy(mem_ctx);
300
301         return ntstatus;
302 }
303
304 /*******************************************************************
305  Run the search by name.
306 ******************************************************************/
307
308 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
309                                           const char *user,
310                                           LDAPMessage ** result,
311                                           const char **attr)
312 {
313         char *filter = NULL;
314         char *escape_user = escape_ldap_string(talloc_tos(), user);
315         int ret = -1;
316
317         if (!escape_user) {
318                 return LDAP_NO_MEMORY;
319         }
320
321         /*
322          * in the filter expression, replace %u with the real name
323          * so in ldap filter, %u MUST exist :-)
324          */
325         filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
326                 get_objclass_filter(ldap_state->schema_ver));
327         if (!filter) {
328                 TALLOC_FREE(escape_user);
329                 return LDAP_NO_MEMORY;
330         }
331         /*
332          * have to use this here because $ is filtered out
333          * in string_sub
334          */
335
336         filter = talloc_all_string_sub(talloc_tos(),
337                                 filter, "%u", escape_user);
338         TALLOC_FREE(escape_user);
339         if (!filter) {
340                 return LDAP_NO_MEMORY;
341         }
342
343         ret = smbldap_search_suffix(ldap_state->smbldap_state,
344                         filter, attr, result);
345         TALLOC_FREE(filter);
346         return ret;
347 }
348
349 /*******************************************************************
350  Run the search by rid.
351 ******************************************************************/
352
353 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
354                                          uint32_t rid, LDAPMessage ** result,
355                                          const char **attr)
356 {
357         char *filter = NULL;
358         int rc;
359
360         filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
361                 get_objclass_filter(ldap_state->schema_ver));
362         if (!filter) {
363                 return LDAP_NO_MEMORY;
364         }
365
366         rc = smbldap_search_suffix(ldap_state->smbldap_state,
367                         filter, attr, result);
368         TALLOC_FREE(filter);
369         return rc;
370 }
371
372 /*******************************************************************
373  Run the search by SID.
374 ******************************************************************/
375
376 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
377                                  const struct dom_sid *sid, LDAPMessage ** result,
378                                  const char **attr)
379 {
380         char *filter = NULL;
381         int rc;
382         fstring sid_string;
383
384         filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
385                 get_userattr_key2string(ldap_state->schema_ver,
386                         LDAP_ATTR_USER_SID),
387                 sid_to_fstring(sid_string, sid),
388                 get_objclass_filter(ldap_state->schema_ver));
389         if (!filter) {
390                 return LDAP_NO_MEMORY;
391         }
392
393         rc = smbldap_search_suffix(ldap_state->smbldap_state,
394                         filter, attr, result);
395
396         TALLOC_FREE(filter);
397         return rc;
398 }
399
400 /*******************************************************************
401  Delete complete object or objectclass and attrs from
402  object found in search_result depending on lp_ldap_delete_dn
403 ******************************************************************/
404
405 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
406                                 TALLOC_CTX *mem_ctx,
407                                 LDAPMessage *entry,
408                                 const char *objectclass,
409                                 const char **attrs)
410 {
411         LDAPMod **mods = NULL;
412         char *name;
413         const char *dn;
414         BerElement *ptr = NULL;
415
416         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
417         if (dn == NULL) {
418                 return LDAP_NO_MEMORY;
419         }
420
421         if (lp_ldap_delete_dn()) {
422                 return smbldap_delete(priv->smbldap_state, dn);
423         }
424
425         /* Ok, delete only the SAM attributes */
426
427         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
428              name != NULL;
429              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
430                 const char **attrib;
431
432                 /* We are only allowed to delete the attributes that
433                    really exist. */
434
435                 for (attrib = attrs; *attrib != NULL; attrib++) {
436                         if (strequal(*attrib, name)) {
437                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
438                                            "attribute %s\n", name));
439                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
440                                                 NULL);
441                         }
442                 }
443                 ldap_memfree(name);
444         }
445
446         if (ptr != NULL) {
447                 ber_free(ptr, 0);
448         }
449
450         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
451         talloc_autofree_ldapmod(mem_ctx, mods);
452
453         return smbldap_modify(priv->smbldap_state, dn, mods);
454 }
455
456 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
457 {
458         char *temp;
459         struct tm tm;
460
461         temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
462                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
463                         talloc_tos());
464         if (!temp) {
465                 return (time_t) 0;
466         }
467
468         if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
469                 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
470                         (char*)temp));
471                 TALLOC_FREE(temp);
472                 return (time_t) 0;
473         }
474         TALLOC_FREE(temp);
475         tzset();
476         return timegm(&tm);
477 }
478
479 /**********************************************************************
480  Initialize struct samu from an LDAP query.
481  (Based on init_sam_from_buffer in pdb_tdb.c)
482 *********************************************************************/
483
484 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
485                                 struct samu * sampass,
486                                 LDAPMessage * entry)
487 {
488         time_t  logon_time,
489                         logoff_time,
490                         kickoff_time,
491                         pass_last_set_time,
492                         pass_can_change_time,
493                         ldap_entry_time,
494                         bad_password_time;
495         char *username = NULL,
496                         *domain = NULL,
497                         *nt_username = NULL,
498                         *fullname = NULL,
499                         *homedir = NULL,
500                         *dir_drive = NULL,
501                         *logon_script = NULL,
502                         *profile_path = NULL,
503                         *acct_desc = NULL,
504                         *workstations = NULL,
505                         *munged_dial = NULL;
506         uint32_t                user_rid;
507         uint8           smblmpwd[LM_HASH_LEN],
508                         smbntpwd[NT_HASH_LEN];
509         bool            use_samba_attrs = True;
510         uint32_t                acct_ctrl = 0;
511         uint16_t                logon_divs;
512         uint16_t                bad_password_count = 0,
513                         logon_count = 0;
514         uint32_t hours_len;
515         uint8           hours[MAX_HOURS_LEN];
516         char *temp = NULL;
517         struct login_cache cache_entry;
518         uint32_t                pwHistLen;
519         bool expand_explicit = lp_passdb_expand_explicit();
520         bool ret = false;
521         TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
522
523         if (!ctx) {
524                 return false;
525         }
526         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
527                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
528                 goto fn_exit;
529         }
530
531         if (priv2ld(ldap_state) == NULL) {
532                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
533                           "ldap_struct is NULL!\n"));
534                 goto fn_exit;
535         }
536
537         if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
538                                         entry,
539                                         "uid",
540                                         ctx))) {
541                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
542                           "this user!\n"));
543                 goto fn_exit;
544         }
545
546         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
547
548         nt_username = talloc_strdup(ctx, username);
549         if (!nt_username) {
550                 goto fn_exit;
551         }
552
553         domain = talloc_strdup(ctx, ldap_state->domain_name);
554         if (!domain) {
555                 goto fn_exit;
556         }
557
558         pdb_set_username(sampass, username, PDB_SET);
559
560         pdb_set_domain(sampass, domain, PDB_DEFAULT);
561         pdb_set_nt_username(sampass, nt_username, PDB_SET);
562
563         /* deal with different attributes between the schema first */
564
565         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
566                 if ((temp = smbldap_talloc_single_attribute(
567                                 ldap_state->smbldap_state->ldap_struct,
568                                 entry,
569                                 get_userattr_key2string(ldap_state->schema_ver,
570                                         LDAP_ATTR_USER_SID),
571                                 ctx))!=NULL) {
572                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
573                 }
574         } else {
575                 if ((temp = smbldap_talloc_single_attribute(
576                                 ldap_state->smbldap_state->ldap_struct,
577                                 entry,
578                                 get_userattr_key2string(ldap_state->schema_ver,
579                                         LDAP_ATTR_USER_RID),
580                                 ctx))!=NULL) {
581                         user_rid = (uint32_t)atol(temp);
582                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
583                 }
584         }
585
586         if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
587                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
588                         get_userattr_key2string(ldap_state->schema_ver,
589                                 LDAP_ATTR_USER_SID),
590                         get_userattr_key2string(ldap_state->schema_ver,
591                                 LDAP_ATTR_USER_RID),
592                         username));
593                 return False;
594         }
595
596         temp = smbldap_talloc_single_attribute(
597                         ldap_state->smbldap_state->ldap_struct,
598                         entry,
599                         get_userattr_key2string(ldap_state->schema_ver,
600                                 LDAP_ATTR_PWD_LAST_SET),
601                         ctx);
602         if (temp) {
603                 pass_last_set_time = (time_t) atol(temp);
604                 pdb_set_pass_last_set_time(sampass,
605                                 pass_last_set_time, PDB_SET);
606         }
607
608         temp = smbldap_talloc_single_attribute(
609                         ldap_state->smbldap_state->ldap_struct,
610                         entry,
611                         get_userattr_key2string(ldap_state->schema_ver,
612                                 LDAP_ATTR_LOGON_TIME),
613                         ctx);
614         if (temp) {
615                 logon_time = (time_t) atol(temp);
616                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
617         }
618
619         temp = smbldap_talloc_single_attribute(
620                         ldap_state->smbldap_state->ldap_struct,
621                         entry,
622                         get_userattr_key2string(ldap_state->schema_ver,
623                                 LDAP_ATTR_LOGOFF_TIME),
624                         ctx);
625         if (temp) {
626                 logoff_time = (time_t) atol(temp);
627                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
628         }
629
630         temp = smbldap_talloc_single_attribute(
631                         ldap_state->smbldap_state->ldap_struct,
632                         entry,
633                         get_userattr_key2string(ldap_state->schema_ver,
634                                 LDAP_ATTR_KICKOFF_TIME),
635                         ctx);
636         if (temp) {
637                 kickoff_time = (time_t) atol(temp);
638                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
639         }
640
641         temp = smbldap_talloc_single_attribute(
642                         ldap_state->smbldap_state->ldap_struct,
643                         entry,
644                         get_userattr_key2string(ldap_state->schema_ver,
645                                 LDAP_ATTR_PWD_CAN_CHANGE),
646                         ctx);
647         if (temp) {
648                 pass_can_change_time = (time_t) atol(temp);
649                 pdb_set_pass_can_change_time(sampass,
650                                 pass_can_change_time, PDB_SET);
651         }
652
653         /* recommend that 'gecos' and 'displayName' should refer to the same
654          * attribute OID.  userFullName depreciated, only used by Samba
655          * primary rules of LDAP: don't make a new attribute when one is already defined
656          * that fits your needs; using cn then displayName rather than 'userFullName'
657          */
658
659         fullname = smbldap_talloc_single_attribute(
660                         ldap_state->smbldap_state->ldap_struct,
661                         entry,
662                         get_userattr_key2string(ldap_state->schema_ver,
663                                 LDAP_ATTR_DISPLAY_NAME),
664                         ctx);
665         if (fullname) {
666                 pdb_set_fullname(sampass, fullname, PDB_SET);
667         } else {
668                 fullname = smbldap_talloc_single_attribute(
669                                 ldap_state->smbldap_state->ldap_struct,
670                                 entry,
671                                 get_userattr_key2string(ldap_state->schema_ver,
672                                         LDAP_ATTR_CN),
673                                 ctx);
674                 if (fullname) {
675                         pdb_set_fullname(sampass, fullname, PDB_SET);
676                 }
677         }
678
679         dir_drive = smbldap_talloc_single_attribute(
680                         ldap_state->smbldap_state->ldap_struct,
681                         entry,
682                         get_userattr_key2string(ldap_state->schema_ver,
683                                 LDAP_ATTR_HOME_DRIVE),
684                         ctx);
685         if (dir_drive) {
686                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
687         } else {
688                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
689         }
690
691         homedir = smbldap_talloc_single_attribute(
692                         ldap_state->smbldap_state->ldap_struct,
693                         entry,
694                         get_userattr_key2string(ldap_state->schema_ver,
695                                 LDAP_ATTR_HOME_PATH),
696                         ctx);
697         if (homedir) {
698                 if (expand_explicit) {
699                         homedir = talloc_sub_basic(ctx,
700                                                 username,
701                                                 domain,
702                                                 homedir);
703                         if (!homedir) {
704                                 goto fn_exit;
705                         }
706                 }
707                 pdb_set_homedir(sampass, homedir, PDB_SET);
708         } else {
709                 pdb_set_homedir(sampass,
710                         talloc_sub_basic(ctx, username, domain,
711                                          lp_logon_home()),
712                         PDB_DEFAULT);
713         }
714
715         logon_script = smbldap_talloc_single_attribute(
716                         ldap_state->smbldap_state->ldap_struct,
717                         entry,
718                         get_userattr_key2string(ldap_state->schema_ver,
719                                 LDAP_ATTR_LOGON_SCRIPT),
720                         ctx);
721         if (logon_script) {
722                 if (expand_explicit) {
723                         logon_script = talloc_sub_basic(ctx,
724                                                 username,
725                                                 domain,
726                                                 logon_script);
727                         if (!logon_script) {
728                                 goto fn_exit;
729                         }
730                 }
731                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
732         } else {
733                 pdb_set_logon_script(sampass,
734                         talloc_sub_basic(ctx, username, domain,
735                                          lp_logon_script()),
736                         PDB_DEFAULT );
737         }
738
739         profile_path = smbldap_talloc_single_attribute(
740                         ldap_state->smbldap_state->ldap_struct,
741                         entry,
742                         get_userattr_key2string(ldap_state->schema_ver,
743                                 LDAP_ATTR_PROFILE_PATH),
744                         ctx);
745         if (profile_path) {
746                 if (expand_explicit) {
747                         profile_path = talloc_sub_basic(ctx,
748                                                 username,
749                                                 domain,
750                                                 profile_path);
751                         if (!profile_path) {
752                                 goto fn_exit;
753                         }
754                 }
755                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
756         } else {
757                 pdb_set_profile_path(sampass,
758                         talloc_sub_basic(ctx, username, domain,
759                                           lp_logon_path()),
760                         PDB_DEFAULT );
761         }
762
763         acct_desc = smbldap_talloc_single_attribute(
764                         ldap_state->smbldap_state->ldap_struct,
765                         entry,
766                         get_userattr_key2string(ldap_state->schema_ver,
767                                 LDAP_ATTR_DESC),
768                         ctx);
769         if (acct_desc) {
770                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
771         }
772
773         workstations = smbldap_talloc_single_attribute(
774                         ldap_state->smbldap_state->ldap_struct,
775                         entry,
776                         get_userattr_key2string(ldap_state->schema_ver,
777                                 LDAP_ATTR_USER_WKS),
778                         ctx);
779         if (workstations) {
780                 pdb_set_workstations(sampass, workstations, PDB_SET);
781         }
782
783         munged_dial = smbldap_talloc_single_attribute(
784                         ldap_state->smbldap_state->ldap_struct,
785                         entry,
786                         get_userattr_key2string(ldap_state->schema_ver,
787                                 LDAP_ATTR_MUNGED_DIAL),
788                         ctx);
789         if (munged_dial) {
790                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
791         }
792
793         /* FIXME: hours stuff should be cleaner */
794
795         logon_divs = 168;
796         hours_len = 21;
797         memset(hours, 0xff, hours_len);
798
799         if (ldap_state->is_nds_ldap) {
800                 char *user_dn;
801                 size_t pwd_len;
802                 char clear_text_pw[512];
803
804                 /* Make call to Novell eDirectory ldap extension to get clear text password.
805                         NOTE: This will only work if we have an SSL connection to eDirectory. */
806                 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
807                 if (user_dn != NULL) {
808                         DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
809
810                         pwd_len = sizeof(clear_text_pw);
811                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
812                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
813                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
814                                         TALLOC_FREE(user_dn);
815                                         return False;
816                                 }
817                                 ZERO_STRUCT(smblmpwd);
818                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
819                                         TALLOC_FREE(user_dn);
820                                         return False;
821                                 }
822                                 ZERO_STRUCT(smbntpwd);
823                                 use_samba_attrs = False;
824                         }
825
826                         TALLOC_FREE(user_dn);
827
828                 } else {
829                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
830                 }
831         }
832
833         if (use_samba_attrs) {
834                 temp = smbldap_talloc_single_attribute(
835                                 ldap_state->smbldap_state->ldap_struct,
836                                 entry,
837                                 get_userattr_key2string(ldap_state->schema_ver,
838                                         LDAP_ATTR_LMPW),
839                                 ctx);
840                 if (temp) {
841                         pdb_gethexpwd(temp, smblmpwd);
842                         memset((char *)temp, '\0', strlen(temp)+1);
843                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
844                                 goto fn_exit;
845                         }
846                         ZERO_STRUCT(smblmpwd);
847                 }
848
849                 temp = smbldap_talloc_single_attribute(
850                                 ldap_state->smbldap_state->ldap_struct,
851                                 entry,
852                                 get_userattr_key2string(ldap_state->schema_ver,
853                                         LDAP_ATTR_NTPW),
854                                 ctx);
855                 if (temp) {
856                         pdb_gethexpwd(temp, smbntpwd);
857                         memset((char *)temp, '\0', strlen(temp)+1);
858                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
859                                 goto fn_exit;
860                         }
861                         ZERO_STRUCT(smbntpwd);
862                 }
863         }
864
865         pwHistLen = 0;
866
867         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
868         if (pwHistLen > 0){
869                 uint8 *pwhist = NULL;
870                 int i;
871                 char *history_string = talloc_array(ctx, char,
872                                                 MAX_PW_HISTORY_LEN*64);
873
874                 if (!history_string) {
875                         goto fn_exit;
876                 }
877
878                 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
879
880                 pwhist = talloc_array(ctx, uint8,
881                                       pwHistLen * PW_HISTORY_ENTRY_LEN);
882                 if (pwhist == NULL) {
883                         DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
884                         goto fn_exit;
885                 }
886                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
887
888                 if (smbldap_get_single_attribute(
889                                 ldap_state->smbldap_state->ldap_struct,
890                                 entry,
891                                 get_userattr_key2string(ldap_state->schema_ver,
892                                         LDAP_ATTR_PWD_HISTORY),
893                                 history_string,
894                                 MAX_PW_HISTORY_LEN*64)) {
895                         bool hex_failed = false;
896                         for (i = 0; i < pwHistLen; i++){
897                                 /* Get the 16 byte salt. */
898                                 if (!pdb_gethexpwd(&history_string[i*64],
899                                         &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
900                                         hex_failed = true;
901                                         break;
902                                 }
903                                 /* Get the 16 byte MD5 hash of salt+passwd. */
904                                 if (!pdb_gethexpwd(&history_string[(i*64)+32],
905                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
906                                                 PW_HISTORY_SALT_LEN])) {
907                                         hex_failed = True;
908                                         break;
909                                 }
910                         }
911                         if (hex_failed) {
912                                 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
913                                         username));
914                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
915                         }
916                 }
917                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
918                         goto fn_exit;
919                 }
920         }
921
922         temp = smbldap_talloc_single_attribute(
923                         ldap_state->smbldap_state->ldap_struct,
924                         entry,
925                         get_userattr_key2string(ldap_state->schema_ver,
926                                 LDAP_ATTR_ACB_INFO),
927                         ctx);
928         if (temp) {
929                 acct_ctrl = pdb_decode_acct_ctrl(temp);
930
931                 if (acct_ctrl == 0) {
932                         acct_ctrl |= ACB_NORMAL;
933                 }
934
935                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
936         } else {
937                 acct_ctrl |= ACB_NORMAL;
938         }
939
940         pdb_set_hours_len(sampass, hours_len, PDB_SET);
941         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
942
943         temp = smbldap_talloc_single_attribute(
944                         ldap_state->smbldap_state->ldap_struct,
945                         entry,
946                         get_userattr_key2string(ldap_state->schema_ver,
947                                 LDAP_ATTR_BAD_PASSWORD_COUNT),
948                         ctx);
949         if (temp) {
950                 bad_password_count = (uint32_t) atol(temp);
951                 pdb_set_bad_password_count(sampass,
952                                 bad_password_count, PDB_SET);
953         }
954
955         temp = smbldap_talloc_single_attribute(
956                         ldap_state->smbldap_state->ldap_struct,
957                         entry,
958                         get_userattr_key2string(ldap_state->schema_ver,
959                                 LDAP_ATTR_BAD_PASSWORD_TIME),
960                         ctx);
961         if (temp) {
962                 bad_password_time = (time_t) atol(temp);
963                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
964         }
965
966
967         temp = smbldap_talloc_single_attribute(
968                         ldap_state->smbldap_state->ldap_struct,
969                         entry,
970                         get_userattr_key2string(ldap_state->schema_ver,
971                                 LDAP_ATTR_LOGON_COUNT),
972                         ctx);
973         if (temp) {
974                 logon_count = (uint32_t) atol(temp);
975                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
976         }
977
978         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
979
980         temp = smbldap_talloc_single_attribute(
981                         ldap_state->smbldap_state->ldap_struct,
982                         entry,
983                         get_userattr_key2string(ldap_state->schema_ver,
984                                 LDAP_ATTR_LOGON_HOURS),
985                         ctx);
986         if (temp) {
987                 pdb_gethexhours(temp, hours);
988                 memset((char *)temp, '\0', strlen(temp) +1);
989                 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
990                 ZERO_STRUCT(hours);
991         }
992
993         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
994                 struct passwd unix_pw;
995                 bool have_uid = false;
996                 bool have_gid = false;
997                 struct dom_sid mapped_gsid;
998                 const struct dom_sid *primary_gsid;
999                 struct unixid id;
1000
1001                 ZERO_STRUCT(unix_pw);
1002
1003                 unix_pw.pw_name = username;
1004                 unix_pw.pw_passwd = discard_const_p(char, "x");
1005
1006                 temp = smbldap_talloc_single_attribute(
1007                                 priv2ld(ldap_state),
1008                                 entry,
1009                                 "uidNumber",
1010                                 ctx);
1011                 if (temp) {
1012                         /* We've got a uid, feed the cache */
1013                         unix_pw.pw_uid = strtoul(temp, NULL, 10);
1014                         have_uid = true;
1015                 }
1016                 temp = smbldap_talloc_single_attribute(
1017                                 priv2ld(ldap_state),
1018                                 entry,
1019                                 "gidNumber",
1020                                 ctx);
1021                 if (temp) {
1022                         /* We've got a uid, feed the cache */
1023                         unix_pw.pw_gid = strtoul(temp, NULL, 10);
1024                         have_gid = true;
1025                 }
1026                 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1027                                 priv2ld(ldap_state),
1028                                 entry,
1029                                 "gecos",
1030                                 ctx);
1031                 if (unix_pw.pw_gecos) {
1032                         unix_pw.pw_gecos = fullname;
1033                 }
1034                 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1035                                 priv2ld(ldap_state),
1036                                 entry,
1037                                 "homeDirectory",
1038                                 ctx);
1039                 if (unix_pw.pw_dir) {
1040                         unix_pw.pw_dir = discard_const_p(char, "");
1041                 }
1042                 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1043                                 priv2ld(ldap_state),
1044                                 entry,
1045                                 "loginShell",
1046                                 ctx);
1047                 if (unix_pw.pw_shell) {
1048                         unix_pw.pw_shell = discard_const_p(char, "");
1049                 }
1050
1051                 if (have_uid && have_gid) {
1052                         sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1053                 } else {
1054                         sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1055                 }
1056
1057                 if (sampass->unix_pw == NULL) {
1058                         DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1059                                  pdb_get_username(sampass)));
1060                         goto fn_exit;
1061                 }
1062
1063                 id.id = sampass->unix_pw->pw_uid;
1064                 id.type = ID_TYPE_UID;
1065
1066                 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1067
1068                 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1069                 primary_gsid = pdb_get_group_sid(sampass);
1070                 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1071                         id.id = sampass->unix_pw->pw_gid;
1072                         id.type = ID_TYPE_GID;
1073
1074                         idmap_cache_set_sid2unixid(primary_gsid, &id);
1075                 }
1076         }
1077
1078         /* check the timestamp of the cache vs ldap entry */
1079         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1080                                                             entry))) {
1081                 ret = true;
1082                 goto fn_exit;
1083         }
1084
1085         /* see if we have newer updates */
1086         if (!login_cache_read(sampass, &cache_entry)) {
1087                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1088                            (unsigned int)pdb_get_bad_password_count(sampass),
1089                            (unsigned int)pdb_get_bad_password_time(sampass)));
1090                 ret = true;
1091                 goto fn_exit;
1092         }
1093
1094         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1095                   (unsigned int)ldap_entry_time,
1096                   (unsigned int)cache_entry.entry_timestamp,
1097                   (unsigned int)cache_entry.bad_password_time));
1098
1099         if (ldap_entry_time > cache_entry.entry_timestamp) {
1100                 /* cache is older than directory , so
1101                    we need to delete the entry but allow the
1102                    fields to be written out */
1103                 login_cache_delentry(sampass);
1104         } else {
1105                 /* read cache in */
1106                 pdb_set_acct_ctrl(sampass,
1107                                   pdb_get_acct_ctrl(sampass) |
1108                                   (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1109                                   PDB_SET);
1110                 pdb_set_bad_password_count(sampass,
1111                                            cache_entry.bad_password_count,
1112                                            PDB_SET);
1113                 pdb_set_bad_password_time(sampass,
1114                                           cache_entry.bad_password_time,
1115                                           PDB_SET);
1116         }
1117
1118         ret = true;
1119
1120   fn_exit:
1121
1122         TALLOC_FREE(ctx);
1123         return ret;
1124 }
1125
1126 /**********************************************************************
1127  Initialize the ldap db from a struct samu. Called on update.
1128  (Based on init_buffer_from_sam in pdb_tdb.c)
1129 *********************************************************************/
1130
1131 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1132                                 LDAPMessage *existing,
1133                                 LDAPMod *** mods, struct samu * sampass,
1134                                 bool (*need_update)(const struct samu *,
1135                                                     enum pdb_elements))
1136 {
1137         char *temp = NULL;
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
1551         switch ( ldap_state->schema_ver ) {
1552                 case SCHEMAVER_SAMBASAMACCOUNT: {
1553                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1554                         if (tmp_ctx == NULL) {
1555                                 return LDAP_NO_MEMORY;
1556                         }
1557
1558                         attr_list = get_userattr_list(tmp_ctx,
1559                                                       ldap_state->schema_ver);
1560                         append_attr(tmp_ctx, &attr_list,
1561                                     get_userattr_key2string(
1562                                             ldap_state->schema_ver,
1563                                             LDAP_ATTR_MOD_TIMESTAMP));
1564                         ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1565                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1566                                                           result, attr_list);
1567                         TALLOC_FREE(tmp_ctx);
1568
1569                         if ( rc != LDAP_SUCCESS ) 
1570                                 return rc;
1571                         break;
1572                 }
1573
1574                 default:
1575                         DEBUG(0,("Invalid schema version specified\n"));
1576                         break;
1577         }
1578         return rc;
1579 }
1580
1581 /**********************************************************************
1582  Get struct samu entry from LDAP by SID.
1583 *********************************************************************/
1584
1585 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1586 {
1587         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1588         LDAPMessage *result = NULL;
1589         LDAPMessage *entry = NULL;
1590         int count;
1591         int rc;
1592
1593         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1594                                           sid, &result); 
1595         if (rc != LDAP_SUCCESS)
1596                 return NT_STATUS_NO_SUCH_USER;
1597
1598         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1599
1600         if (count < 1) {
1601                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1602                           "count=%d\n", sid_string_dbg(sid), count));
1603                 ldap_msgfree(result);
1604                 return NT_STATUS_NO_SUCH_USER;
1605         }  else if (count > 1) {
1606                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1607                           "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1608                           count));
1609                 ldap_msgfree(result);
1610                 return NT_STATUS_NO_SUCH_USER;
1611         }
1612
1613         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1614         if (!entry) {
1615                 ldap_msgfree(result);
1616                 return NT_STATUS_NO_SUCH_USER;
1617         }
1618
1619         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1620                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1621                 ldap_msgfree(result);
1622                 return NT_STATUS_NO_SUCH_USER;
1623         }
1624
1625         pdb_set_backend_private_data(user, result, NULL,
1626                                      my_methods, PDB_CHANGED);
1627         talloc_autofree_ldapmsg(user, result);
1628         return NT_STATUS_OK;
1629 }       
1630
1631 /********************************************************************
1632  Do the actual modification - also change a plaintext passord if 
1633  it it set.
1634 **********************************************************************/
1635
1636 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1637                                      struct samu *newpwd, char *dn,
1638                                      LDAPMod **mods, int ldap_op, 
1639                                      bool (*need_update)(const struct samu *, enum pdb_elements))
1640 {
1641         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1642         int rc;
1643
1644         if (!newpwd || !dn) {
1645                 return NT_STATUS_INVALID_PARAMETER;
1646         }
1647
1648         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1649                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1650                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1651                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1652                 BerElement *ber;
1653                 struct berval *bv;
1654                 char *retoid = NULL;
1655                 struct berval *retdata = NULL;
1656                 char *utf8_password;
1657                 char *utf8_dn;
1658                 size_t converted_size;
1659                 int ret;
1660
1661                 if (!ldap_state->is_nds_ldap) {
1662
1663                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1664                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1665                                 DEBUG(2, ("ldap password change requested, but LDAP "
1666                                           "server does not support it -- ignoring\n"));
1667                                 return NT_STATUS_OK;
1668                         }
1669                 }
1670
1671                 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1672                                         pdb_get_plaintext_passwd(newpwd),
1673                                         &converted_size))
1674                 {
1675                         return NT_STATUS_NO_MEMORY;
1676                 }
1677
1678                 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1679                         TALLOC_FREE(utf8_password);
1680                         return NT_STATUS_NO_MEMORY;
1681                 }
1682
1683                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1684                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1685                         TALLOC_FREE(utf8_password);
1686                         TALLOC_FREE(utf8_dn);
1687                         return NT_STATUS_UNSUCCESSFUL;
1688                 }
1689
1690                 if ((ber_printf (ber, "{") < 0) ||
1691                     (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1692                                  utf8_dn) < 0)) {
1693                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1694                                  "value <0\n"));
1695                         ber_free(ber,1);
1696                         TALLOC_FREE(utf8_dn);
1697                         TALLOC_FREE(utf8_password);
1698                         return NT_STATUS_UNSUCCESSFUL;
1699                 }
1700
1701                 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1702                         ret = ber_printf(ber, "ts}",
1703                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1704                                          utf8_password);
1705                 } else {
1706                         ret = ber_printf(ber, "}");
1707                 }
1708
1709                 if (ret < 0) {
1710                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1711                                  "value <0\n"));
1712                         ber_free(ber,1);
1713                         TALLOC_FREE(utf8_dn);
1714                         TALLOC_FREE(utf8_password);
1715                         return NT_STATUS_UNSUCCESSFUL;
1716                 }
1717
1718                 if ((rc = ber_flatten (ber, &bv))<0) {
1719                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1720                         ber_free(ber,1);
1721                         TALLOC_FREE(utf8_dn);
1722                         TALLOC_FREE(utf8_password);
1723                         return NT_STATUS_UNSUCCESSFUL;
1724                 }
1725
1726                 TALLOC_FREE(utf8_dn);
1727                 TALLOC_FREE(utf8_password);
1728                 ber_free(ber, 1);
1729
1730                 if (!ldap_state->is_nds_ldap) {
1731                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1732                                                         LDAP_EXOP_MODIFY_PASSWD,
1733                                                         bv, NULL, NULL, &retoid, 
1734                                                         &retdata);
1735                 } else {
1736                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1737                                                         pdb_get_plaintext_passwd(newpwd));
1738                 }
1739                 if (rc != LDAP_SUCCESS) {
1740                         char *ld_error = NULL;
1741
1742                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1743                                 DEBUG(3, ("Could not set userPassword "
1744                                           "attribute due to an objectClass "
1745                                           "violation -- ignoring\n"));
1746                                 ber_bvfree(bv);
1747                                 return NT_STATUS_OK;
1748                         }
1749
1750                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1751                                         &ld_error);
1752                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1753                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1754                         SAFE_FREE(ld_error);
1755                         ber_bvfree(bv);
1756 #if defined(LDAP_CONSTRAINT_VIOLATION)
1757                         if (rc == LDAP_CONSTRAINT_VIOLATION)
1758                                 return NT_STATUS_PASSWORD_RESTRICTION;
1759 #endif
1760                         return NT_STATUS_UNSUCCESSFUL;
1761                 } else {
1762                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1763 #ifdef DEBUG_PASSWORD
1764                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1765 #endif    
1766                         if (retdata)
1767                                 ber_bvfree(retdata);
1768                         if (retoid)
1769                                 ldap_memfree(retoid);
1770                 }
1771                 ber_bvfree(bv);
1772         }
1773
1774         if (!mods) {
1775                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1776                 /* may be password change below however */
1777         } else {
1778                 switch(ldap_op) {
1779                         case LDAP_MOD_ADD:
1780                                 if (ldap_state->is_nds_ldap) {
1781                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1782                                                         "objectclass",
1783                                                         "inetOrgPerson");
1784                                 } else {
1785                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1786                                                         "objectclass",
1787                                                         LDAP_OBJ_ACCOUNT);
1788                                 }
1789                                 rc = smbldap_add(ldap_state->smbldap_state,
1790                                                  dn, mods);
1791                                 break;
1792                         case LDAP_MOD_REPLACE:
1793                                 rc = smbldap_modify(ldap_state->smbldap_state,
1794                                                     dn ,mods);
1795                                 break;
1796                         default:
1797                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1798                                          ldap_op));
1799                                 return NT_STATUS_INVALID_PARAMETER;
1800                 }
1801
1802                 if (rc!=LDAP_SUCCESS) {
1803                         return NT_STATUS_UNSUCCESSFUL;
1804                 }
1805         }
1806
1807         return NT_STATUS_OK;
1808 }
1809
1810 /**********************************************************************
1811  Delete entry from LDAP for username.
1812 *********************************************************************/
1813
1814 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1815                                            struct samu * sam_acct)
1816 {
1817         struct ldapsam_privates *priv =
1818                 (struct ldapsam_privates *)my_methods->private_data;
1819         const char *sname;
1820         int rc;
1821         LDAPMessage *msg, *entry;
1822         NTSTATUS result = NT_STATUS_NO_MEMORY;
1823         const char **attr_list;
1824         TALLOC_CTX *mem_ctx;
1825
1826         if (!sam_acct) {
1827                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1828                 return NT_STATUS_INVALID_PARAMETER;
1829         }
1830
1831         sname = pdb_get_username(sam_acct);
1832
1833         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1834                   "LDAP.\n", sname));
1835
1836         mem_ctx = talloc_new(NULL);
1837         if (mem_ctx == NULL) {
1838                 DEBUG(0, ("talloc_new failed\n"));
1839                 goto done;
1840         }
1841
1842         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1843         if (attr_list == NULL) {
1844                 goto done;
1845         }
1846
1847         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1848
1849         if ((rc != LDAP_SUCCESS) ||
1850             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1851             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1852                 DEBUG(5, ("Could not find user %s\n", sname));
1853                 result = NT_STATUS_NO_SUCH_USER;
1854                 goto done;
1855         }
1856
1857         rc = ldapsam_delete_entry(
1858                 priv, mem_ctx, entry,
1859                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1860                 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1861                 attr_list);
1862
1863         result = (rc == LDAP_SUCCESS) ?
1864                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1865
1866  done:
1867         TALLOC_FREE(mem_ctx);
1868         return result;
1869 }
1870
1871 /**********************************************************************
1872  Update struct samu.
1873 *********************************************************************/
1874
1875 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1876 {
1877         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1878         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1879         int rc = 0;
1880         char *dn;
1881         LDAPMessage *result = NULL;
1882         LDAPMessage *entry = NULL;
1883         LDAPMod **mods = NULL;
1884         const char **attr_list;
1885
1886         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1887         if (!result) {
1888                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1889                 if (pdb_get_username(newpwd) == NULL) {
1890                         return NT_STATUS_INVALID_PARAMETER;
1891                 }
1892                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1893                 TALLOC_FREE( attr_list );
1894                 if (rc != LDAP_SUCCESS) {
1895                         return NT_STATUS_UNSUCCESSFUL;
1896                 }
1897                 pdb_set_backend_private_data(newpwd, result, NULL,
1898                                              my_methods, PDB_CHANGED);
1899                 talloc_autofree_ldapmsg(newpwd, result);
1900         }
1901
1902         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1903                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1904                 return NT_STATUS_UNSUCCESSFUL;
1905         }
1906
1907         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1908         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1909         if (!dn) {
1910                 return NT_STATUS_UNSUCCESSFUL;
1911         }
1912
1913         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1914
1915         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1916                                 pdb_element_is_changed)) {
1917                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1918                 TALLOC_FREE(dn);
1919                 if (mods != NULL)
1920                         ldap_mods_free(mods,True);
1921                 return NT_STATUS_UNSUCCESSFUL;
1922         }
1923
1924         if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1925             && (mods == NULL)) {
1926                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1927                          pdb_get_username(newpwd)));
1928                 TALLOC_FREE(dn);
1929                 return NT_STATUS_OK;
1930         }
1931
1932         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1933
1934         if (mods != NULL) {
1935                 ldap_mods_free(mods,True);
1936         }
1937
1938         TALLOC_FREE(dn);
1939
1940         /*
1941          * We need to set the backend private data to NULL here. For example
1942          * setuserinfo level 25 does a pdb_update_sam_account twice on the
1943          * same one, and with the explicit delete / add logic for attribute
1944          * values the second time we would use the wrong "old" value which
1945          * does not exist in LDAP anymore. Thus the LDAP server would refuse
1946          * the update.
1947          * The existing LDAPMessage is still being auto-freed by the
1948          * destructor.
1949          */
1950         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1951                                      PDB_CHANGED);
1952
1953         if (!NT_STATUS_IS_OK(ret)) {
1954                 return ret;
1955         }
1956
1957         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1958                   pdb_get_username(newpwd)));
1959         return NT_STATUS_OK;
1960 }
1961
1962 /***************************************************************************
1963  Renames a struct samu
1964  - The "rename user script" has full responsibility for changing everything
1965 ***************************************************************************/
1966
1967 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1968                                      TALLOC_CTX *tmp_ctx,
1969                                      uint32_t group_rid,
1970                                      uint32_t member_rid);
1971
1972 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1973                                                TALLOC_CTX *mem_ctx,
1974                                                struct samu *user,
1975                                                struct dom_sid **pp_sids,
1976                                                gid_t **pp_gids,
1977                                                uint32_t *p_num_groups);
1978
1979 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1980                                            struct samu *old_acct,
1981                                            const char *newname)
1982 {
1983         const char *oldname;
1984         int rc;
1985         char *rename_script = NULL;
1986         fstring oldname_lower, newname_lower;
1987
1988         if (!old_acct) {
1989                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1990                 return NT_STATUS_INVALID_PARAMETER;
1991         }
1992         if (!newname) {
1993                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1994                 return NT_STATUS_INVALID_PARAMETER;
1995         }
1996
1997         oldname = pdb_get_username(old_acct);
1998
1999         /* rename the posix user */
2000         rename_script = lp_renameuser_script(talloc_tos());
2001         if (rename_script == NULL) {
2002                 return NT_STATUS_NO_MEMORY;
2003         }
2004
2005         if (!(*rename_script)) {
2006                 TALLOC_FREE(rename_script);
2007                 return NT_STATUS_ACCESS_DENIED;
2008         }
2009
2010         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2011                    oldname, newname));
2012
2013         /* We have to allow the account name to end with a '$'.
2014            Also, follow the semantics in _samr_create_user() and lower case the
2015            posix name but preserve the case in passdb */
2016
2017         fstrcpy( oldname_lower, oldname );
2018         if (!strlower_m( oldname_lower )) {
2019                 return NT_STATUS_INVALID_PARAMETER;
2020         }
2021         fstrcpy( newname_lower, newname );
2022         if (!strlower_m( newname_lower )) {
2023                 return NT_STATUS_INVALID_PARAMETER;
2024         }
2025
2026         rename_script = realloc_string_sub2(rename_script,
2027                                         "%unew",
2028                                         newname_lower,
2029                                         true,
2030                                         true);
2031         if (!rename_script) {
2032                 return NT_STATUS_NO_MEMORY;
2033         }
2034         rename_script = realloc_string_sub2(rename_script,
2035                                         "%uold",
2036                                         oldname_lower,
2037                                         true,
2038                                         true);
2039         rc = smbrun(rename_script, NULL);
2040
2041         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2042                           rename_script, rc));
2043
2044         TALLOC_FREE(rename_script);
2045
2046         if (rc == 0) {
2047                 smb_nscd_flush_user_cache();
2048         }
2049
2050         if (rc)
2051                 return NT_STATUS_UNSUCCESSFUL;
2052
2053         return NT_STATUS_OK;
2054 }
2055
2056 /**********************************************************************
2057  Add struct samu to LDAP.
2058 *********************************************************************/
2059
2060 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2061 {
2062         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2063         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2064         int rc;
2065         LDAPMessage     *result = NULL;
2066         LDAPMessage     *entry  = NULL;
2067         LDAPMod         **mods = NULL;
2068         int             ldap_op = LDAP_MOD_REPLACE;
2069         uint32_t                num_result;
2070         const char      **attr_list;
2071         char *escape_user = NULL;
2072         const char      *username = pdb_get_username(newpwd);
2073         const struct dom_sid    *sid = pdb_get_user_sid(newpwd);
2074         char *filter = NULL;
2075         char *dn = NULL;
2076         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2077         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2078
2079         if (!ctx) {
2080                 return NT_STATUS_NO_MEMORY;
2081         }
2082
2083         if (!username || !*username) {
2084                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2085                 status = NT_STATUS_INVALID_PARAMETER;
2086                 goto fn_exit;
2087         }
2088
2089         /* free this list after the second search or in case we exit on failure */
2090         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2091
2092         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2093
2094         if (rc != LDAP_SUCCESS) {
2095                 goto fn_exit;
2096         }
2097
2098         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2099                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2100                          username));
2101                 goto fn_exit;
2102         }
2103         ldap_msgfree(result);
2104         result = NULL;
2105
2106         if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2107                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2108                                                   sid, &result);
2109                 if (rc == LDAP_SUCCESS) {
2110                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2111                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2112                                          "already in the base, with samba "
2113                                          "attributes\n", sid_string_dbg(sid)));
2114                                 goto fn_exit;
2115                         }
2116                         ldap_msgfree(result);
2117                         result = NULL;
2118                 }
2119         }
2120
2121         /* does the entry already exist but without a samba attributes?
2122            we need to return the samba attributes here */
2123
2124         escape_user = escape_ldap_string(talloc_tos(), username);
2125         filter = talloc_strdup(attr_list, "(uid=%u)");
2126         if (!filter) {
2127                 status = NT_STATUS_NO_MEMORY;
2128                 goto fn_exit;
2129         }
2130         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2131         TALLOC_FREE(escape_user);
2132         if (!filter) {
2133                 status = NT_STATUS_NO_MEMORY;
2134                 goto fn_exit;
2135         }
2136
2137         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2138                                    filter, attr_list, &result);
2139         if ( rc != LDAP_SUCCESS ) {
2140                 goto fn_exit;
2141         }
2142
2143         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2144
2145         if (num_result > 1) {
2146                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2147                 goto fn_exit;
2148         }
2149
2150         /* Check if we need to update an existing entry */
2151         if (num_result == 1) {
2152                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2153                 ldap_op = LDAP_MOD_REPLACE;
2154                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2155                 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2156                 if (!dn) {
2157                         status = NT_STATUS_NO_MEMORY;
2158                         goto fn_exit;
2159                 }
2160
2161         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2162
2163                 /* There might be a SID for this account already - say an idmap entry */
2164
2165                 filter = talloc_asprintf(ctx,
2166                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2167                                  get_userattr_key2string(ldap_state->schema_ver,
2168                                          LDAP_ATTR_USER_SID),
2169                                  sid_string_talloc(ctx, sid),
2170                                  LDAP_OBJ_IDMAP_ENTRY,
2171                                  LDAP_OBJ_SID_ENTRY);
2172                 if (!filter) {
2173                         status = NT_STATUS_NO_MEMORY;
2174                         goto fn_exit;
2175                 }
2176
2177                 /* free old result before doing a new search */
2178                 if (result != NULL) {
2179                         ldap_msgfree(result);
2180                         result = NULL;
2181                 }
2182                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2183                                            filter, attr_list, &result);
2184
2185                 if ( rc != LDAP_SUCCESS ) {
2186                         goto fn_exit;
2187                 }
2188
2189                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2190
2191                 if (num_result > 1) {
2192                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2193                         goto fn_exit;
2194                 }
2195
2196                 /* Check if we need to update an existing entry */
2197                 if (num_result == 1) {
2198
2199                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2200                         ldap_op = LDAP_MOD_REPLACE;
2201                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2202                         dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2203                         if (!dn) {
2204                                 status = NT_STATUS_NO_MEMORY;
2205                                 goto fn_exit;
2206                         }
2207                 }
2208         }
2209
2210         if (num_result == 0) {
2211                 char *escape_username;
2212                 /* Check if we need to add an entry */
2213                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2214                 ldap_op = LDAP_MOD_ADD;
2215
2216                 escape_username = escape_rdn_val_string_alloc(username);
2217                 if (!escape_username) {
2218                         status = NT_STATUS_NO_MEMORY;
2219                         goto fn_exit;
2220                 }
2221
2222                 if (username[strlen(username)-1] == '$') {
2223                         dn = talloc_asprintf(ctx,
2224                                         "uid=%s,%s",
2225                                         escape_username,
2226                                         lp_ldap_machine_suffix(talloc_tos()));
2227                 } else {
2228                         dn = talloc_asprintf(ctx,
2229                                         "uid=%s,%s",
2230                                         escape_username,
2231                                         lp_ldap_user_suffix(talloc_tos()));
2232                 }
2233
2234                 SAFE_FREE(escape_username);
2235                 if (!dn) {
2236                         status = NT_STATUS_NO_MEMORY;
2237                         goto fn_exit;
2238                 }
2239         }
2240
2241         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2242                                 pdb_element_is_set_or_changed)) {
2243                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2244                 if (mods != NULL) {
2245                         ldap_mods_free(mods, true);
2246                 }
2247                 goto fn_exit;
2248         }
2249
2250         if (mods == NULL) {
2251                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2252                 goto fn_exit;
2253         }
2254         switch ( ldap_state->schema_ver ) {
2255                 case SCHEMAVER_SAMBASAMACCOUNT:
2256                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2257                         break;
2258                 default:
2259                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2260                         break;
2261         }
2262
2263         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2264         if (!NT_STATUS_IS_OK(ret)) {
2265                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2266                          pdb_get_username(newpwd),dn));
2267                 ldap_mods_free(mods, true);
2268                 goto fn_exit;
2269         }
2270
2271         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2272         ldap_mods_free(mods, true);
2273
2274         status = NT_STATUS_OK;
2275
2276   fn_exit:
2277
2278         TALLOC_FREE(ctx);
2279         if (result) {
2280                 ldap_msgfree(result);
2281         }
2282         return status;
2283 }
2284
2285 /**********************************************************************
2286  *********************************************************************/
2287
2288 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2289                                      const char *filter,
2290                                      LDAPMessage ** result)
2291 {
2292         int scope = LDAP_SCOPE_SUBTREE;
2293         int rc;
2294         const char **attr_list;
2295
2296         attr_list = get_attr_list(NULL, groupmap_attr_list);
2297         rc = smbldap_search(ldap_state->smbldap_state,
2298                             lp_ldap_suffix (talloc_tos()), scope,
2299                             filter, attr_list, 0, result);
2300         TALLOC_FREE(attr_list);
2301
2302         return rc;
2303 }
2304
2305 /**********************************************************************
2306  *********************************************************************/
2307
2308 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2309                                  GROUP_MAP *map, LDAPMessage *entry)
2310 {
2311         char *temp = NULL;
2312         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2313
2314         if (ldap_state == NULL || map == NULL || entry == NULL ||
2315                         ldap_state->smbldap_state->ldap_struct == NULL) {
2316                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2317                 TALLOC_FREE(ctx);
2318                 return false;
2319         }
2320
2321         temp = smbldap_talloc_single_attribute(
2322                         ldap_state->smbldap_state->ldap_struct,
2323                         entry,
2324                         get_attr_key2string(groupmap_attr_list,
2325                                 LDAP_ATTR_GIDNUMBER),
2326                         ctx);
2327         if (!temp) {
2328                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2329                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2330                 TALLOC_FREE(ctx);
2331                 return false;
2332         }
2333         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2334
2335         map->gid = (gid_t)atol(temp);
2336
2337         TALLOC_FREE(temp);
2338         temp = smbldap_talloc_single_attribute(
2339                         ldap_state->smbldap_state->ldap_struct,
2340                         entry,
2341                         get_attr_key2string(groupmap_attr_list,
2342                                 LDAP_ATTR_GROUP_SID),
2343                         ctx);
2344         if (!temp) {
2345                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2346                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2347                 TALLOC_FREE(ctx);
2348                 return false;
2349         }
2350
2351         if (!string_to_sid(&map->sid, temp)) {
2352                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2353                 TALLOC_FREE(ctx);
2354                 return false;
2355         }
2356
2357         TALLOC_FREE(temp);
2358         temp = smbldap_talloc_single_attribute(
2359                         ldap_state->smbldap_state->ldap_struct,
2360                         entry,
2361                         get_attr_key2string(groupmap_attr_list,
2362                                 LDAP_ATTR_GROUP_TYPE),
2363                         ctx);
2364         if (!temp) {
2365                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2366                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2367                 TALLOC_FREE(ctx);
2368                 return false;
2369         }
2370         map->sid_name_use = (enum lsa_SidType)atol(temp);
2371
2372         if ((map->sid_name_use < SID_NAME_USER) ||
2373                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2374                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2375                 TALLOC_FREE(ctx);
2376                 return false;
2377         }
2378
2379         TALLOC_FREE(temp);
2380         temp = smbldap_talloc_single_attribute(
2381                         ldap_state->smbldap_state->ldap_struct,
2382                         entry,
2383                         get_attr_key2string(groupmap_attr_list,
2384                                 LDAP_ATTR_DISPLAY_NAME),
2385                         ctx);
2386         if (!temp) {
2387                 temp = smbldap_talloc_single_attribute(
2388                                 ldap_state->smbldap_state->ldap_struct,
2389                                 entry,
2390                                 get_attr_key2string(groupmap_attr_list,
2391                                         LDAP_ATTR_CN),
2392                                 ctx);
2393                 if (!temp) {
2394                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2395 for gidNumber(%lu)\n",(unsigned long)map->gid));
2396                         TALLOC_FREE(ctx);
2397                         return false;
2398                 }
2399         }
2400         map->nt_name = talloc_strdup(map, temp);
2401         if (!map->nt_name) {
2402                 TALLOC_FREE(ctx);
2403                 return false;
2404         }
2405
2406         TALLOC_FREE(temp);
2407         temp = smbldap_talloc_single_attribute(
2408                         ldap_state->smbldap_state->ldap_struct,
2409                         entry,
2410                         get_attr_key2string(groupmap_attr_list,
2411                                 LDAP_ATTR_DESC),
2412                         ctx);
2413         if (!temp) {
2414                 temp = talloc_strdup(ctx, "");
2415                 if (!temp) {
2416                         TALLOC_FREE(ctx);
2417                         return false;
2418                 }
2419         }
2420         map->comment = talloc_strdup(map, temp);
2421         if (!map->comment) {
2422                 TALLOC_FREE(ctx);
2423                 return false;
2424         }
2425
2426         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2427                 struct unixid id;
2428                 id.id = map->gid;
2429                 id.type = ID_TYPE_GID;
2430
2431                 idmap_cache_set_sid2unixid(&map->sid, &id);
2432         }
2433
2434         TALLOC_FREE(ctx);
2435         return true;
2436 }
2437
2438 /**********************************************************************
2439  *********************************************************************/
2440
2441 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2442                                  const char *filter,
2443                                  GROUP_MAP *map)
2444 {
2445         struct ldapsam_privates *ldap_state =
2446                 (struct ldapsam_privates *)methods->private_data;
2447         LDAPMessage *result = NULL;
2448         LDAPMessage *entry = NULL;
2449         int count;
2450
2451         if (ldapsam_search_one_group(ldap_state, filter, &result)
2452             != LDAP_SUCCESS) {
2453                 return NT_STATUS_NO_SUCH_GROUP;
2454         }
2455
2456         count = ldap_count_entries(priv2ld(ldap_state), result);
2457
2458         if (count < 1) {
2459                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2460                           "%s\n", filter));
2461                 ldap_msgfree(result);
2462                 return NT_STATUS_NO_SUCH_GROUP;
2463         }
2464
2465         if (count > 1) {
2466                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2467                           "count=%d\n", filter, count));
2468                 ldap_msgfree(result);
2469                 return NT_STATUS_NO_SUCH_GROUP;
2470         }
2471
2472         entry = ldap_first_entry(priv2ld(ldap_state), result);
2473
2474         if (!entry) {
2475                 ldap_msgfree(result);
2476                 return NT_STATUS_UNSUCCESSFUL;
2477         }
2478
2479         if (!init_group_from_ldap(ldap_state, map, entry)) {
2480                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2481                           "group filter %s\n", filter));
2482                 ldap_msgfree(result);
2483                 return NT_STATUS_NO_SUCH_GROUP;
2484         }
2485
2486         ldap_msgfree(result);
2487         return NT_STATUS_OK;
2488 }
2489
2490 /**********************************************************************
2491  *********************************************************************/
2492
2493 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2494                                  struct dom_sid sid)
2495 {
2496         char *filter = NULL;
2497         NTSTATUS status;
2498         fstring tmp;
2499
2500         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2501                 LDAP_OBJ_GROUPMAP,
2502                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2503                 sid_to_fstring(tmp, &sid)) < 0) {
2504                 return NT_STATUS_NO_MEMORY;
2505         }
2506
2507         status = ldapsam_getgroup(methods, filter, map);
2508         SAFE_FREE(filter);
2509         return status;
2510 }
2511
2512 /**********************************************************************
2513  *********************************************************************/
2514
2515 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2516                                  gid_t gid)
2517 {
2518         char *filter = NULL;
2519         NTSTATUS status;
2520
2521         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2522                 LDAP_OBJ_GROUPMAP,
2523                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2524                 (unsigned long)gid) < 0) {
2525                 return NT_STATUS_NO_MEMORY;
2526         }
2527
2528         status = ldapsam_getgroup(methods, filter, map);
2529         SAFE_FREE(filter);
2530         return status;
2531 }
2532
2533 /**********************************************************************
2534  *********************************************************************/
2535
2536 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2537                                  const char *name)
2538 {
2539         char *filter = NULL;
2540         char *escape_name = escape_ldap_string(talloc_tos(), name);
2541         NTSTATUS status;
2542
2543         if (!escape_name) {
2544                 return NT_STATUS_NO_MEMORY;
2545         }
2546
2547         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2548                 LDAP_OBJ_GROUPMAP,
2549                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2550                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2551                 escape_name) < 0) {
2552                 TALLOC_FREE(escape_name);
2553                 return NT_STATUS_NO_MEMORY;
2554         }
2555
2556         TALLOC_FREE(escape_name);
2557         status = ldapsam_getgroup(methods, filter, map);
2558         SAFE_FREE(filter);
2559         return status;
2560 }
2561
2562 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2563                                            LDAPMessage *entry,
2564                                            const struct dom_sid *domain_sid,
2565                                            uint32_t *rid)
2566 {
2567         fstring str;
2568         struct dom_sid sid;
2569
2570         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2571                                           str, sizeof(str)-1)) {
2572                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2573                 return False;
2574         }
2575
2576         if (!string_to_sid(&sid, str)) {
2577                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2578                 return False;
2579         }
2580
2581         if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2582                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2583                            str, sid_string_dbg(domain_sid)));
2584                 return False;
2585         }
2586
2587         if (!sid_peek_rid(&sid, rid)) {
2588                 DEBUG(10, ("Could not peek into RID\n"));
2589                 return False;
2590         }
2591
2592         return True;
2593 }
2594
2595 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2596                                            TALLOC_CTX *mem_ctx,
2597                                            const struct dom_sid *group,
2598                                            uint32_t **pp_member_rids,
2599                                            size_t *p_num_members)
2600 {
2601         struct ldapsam_privates *ldap_state =
2602                 (struct ldapsam_privates *)methods->private_data;
2603         struct smbldap_state *conn = ldap_state->smbldap_state;
2604         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2605         const char *sid_attrs[] = { "sambaSID", NULL };
2606         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2607         LDAPMessage *result = NULL;
2608         LDAPMessage *entry;
2609         char *filter;
2610         char **values = NULL;
2611         char **memberuid;
2612         char *gidstr;
2613         int rc, count;
2614
2615         *pp_member_rids = NULL;
2616         *p_num_members = 0;
2617
2618         filter = talloc_asprintf(mem_ctx,
2619                                  "(&(objectClass=%s)"
2620                                  "(objectClass=%s)"
2621                                  "(sambaSID=%s))",
2622                                  LDAP_OBJ_POSIXGROUP,
2623                                  LDAP_OBJ_GROUPMAP,
2624                                  sid_string_talloc(mem_ctx, group));
2625         if (filter == NULL) {
2626                 ret = NT_STATUS_NO_MEMORY;
2627                 goto done;
2628         }
2629
2630         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2631                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2632                             &result);
2633
2634         if (rc != LDAP_SUCCESS)
2635                 goto done;
2636
2637         talloc_autofree_ldapmsg(mem_ctx, result);
2638
2639         count = ldap_count_entries(conn->ldap_struct, result);
2640
2641         if (count > 1) {
2642                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2643                           sid_string_dbg(group)));
2644                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2645                 goto done;
2646         }
2647
2648         if (count == 0) {
2649                 ret = NT_STATUS_NO_SUCH_GROUP;
2650                 goto done;
2651         }
2652
2653         entry = ldap_first_entry(conn->ldap_struct, result);
2654         if (entry == NULL)
2655                 goto done;
2656
2657         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2658         if (!gidstr) {
2659                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2660                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2661                 goto done;
2662         }
2663
2664         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2665
2666         if ((values != NULL) && (values[0] != NULL)) {
2667
2668                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2669                 if (filter == NULL) {
2670                         ret = NT_STATUS_NO_MEMORY;
2671                         goto done;
2672                 }
2673
2674                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2675                         char *escape_memberuid;
2676
2677                         escape_memberuid = escape_ldap_string(talloc_tos(),
2678                                                               *memberuid);
2679                         if (escape_memberuid == NULL) {
2680                                 ret = NT_STATUS_NO_MEMORY;
2681                                 goto done;
2682                         }
2683
2684                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2685                         TALLOC_FREE(escape_memberuid);
2686                         if (filter == NULL) {
2687                                 ret = NT_STATUS_NO_MEMORY;
2688                                 goto done;
2689                         }
2690                 }
2691
2692                 filter = talloc_asprintf_append_buffer(filter, "))");
2693                 if (filter == NULL) {
2694                         ret = NT_STATUS_NO_MEMORY;
2695                         goto done;
2696                 }
2697
2698                 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2699                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2700                                     &result);
2701
2702                 if (rc != LDAP_SUCCESS)
2703                         goto done;
2704
2705                 count = ldap_count_entries(conn->ldap_struct, result);
2706                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2707
2708                 talloc_autofree_ldapmsg(mem_ctx, result);
2709
2710                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2711                      entry != NULL;
2712                      entry = ldap_next_entry(conn->ldap_struct, entry))
2713                 {
2714                         char *sidstr;
2715                         struct dom_sid sid;
2716                         uint32_t rid;
2717
2718                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2719                                                                  entry, "sambaSID",
2720                                                                  mem_ctx);
2721                         if (!sidstr) {
2722                                 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2723                                           "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2724                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2725                                 goto done;
2726                         }
2727
2728                         if (!string_to_sid(&sid, sidstr))
2729                                 goto done;
2730
2731                         if (!sid_check_is_in_our_sam(&sid)) {
2732                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2733                                           "in our domain\n"));
2734                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2735                                 goto done;
2736                         }
2737
2738                         sid_peek_rid(&sid, &rid);
2739
2740                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2741                                                 p_num_members)) {
2742                                 ret = NT_STATUS_NO_MEMORY;
2743                                 goto done;
2744                         }
2745                 }
2746         }
2747
2748         filter = talloc_asprintf(mem_ctx,
2749                                  "(&(objectClass=%s)"
2750                                  "(gidNumber=%s))",
2751                                  LDAP_OBJ_SAMBASAMACCOUNT,
2752                                  gidstr);
2753
2754         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2755                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2756                             &result);
2757
2758         if (rc != LDAP_SUCCESS)
2759                 goto done;
2760
2761         talloc_autofree_ldapmsg(mem_ctx, result);
2762
2763         for (entry = ldap_first_entry(conn->ldap_struct, result);
2764              entry != NULL;
2765              entry = ldap_next_entry(conn->ldap_struct, entry))
2766         {
2767                 uint32_t rid;
2768
2769                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2770                                                     entry,
2771                                                     get_global_sam_sid(),
2772                                                     &rid)) {
2773                         DEBUG(0, ("Severe DB error, %s can't miss the samba SID"                                                                "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2774                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2775                         goto done;
2776                 }
2777
2778                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2779                                         p_num_members)) {
2780                         ret = NT_STATUS_NO_MEMORY;
2781                         goto done;
2782                 }
2783         }
2784
2785         ret = NT_STATUS_OK;
2786
2787  done:
2788
2789         if (values)
2790                 ldap_value_free(values);
2791
2792         return ret;
2793 }
2794
2795 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2796                                                TALLOC_CTX *mem_ctx,
2797                                                struct samu *user,
2798                                                struct dom_sid **pp_sids,
2799                                                gid_t **pp_gids,
2800                                                uint32_t *p_num_groups)
2801 {
2802         struct ldapsam_privates *ldap_state =
2803                 (struct ldapsam_privates *)methods->private_data;
2804         struct smbldap_state *conn = ldap_state->smbldap_state;
2805         char *filter;
2806         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2807         char *escape_name;
2808         int rc, count;
2809         LDAPMessage *result = NULL;
2810         LDAPMessage *entry;
2811         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2812         uint32_t num_sids;
2813         uint32_t num_gids;
2814         char *gidstr;
2815         gid_t primary_gid = -1;
2816
2817         *pp_sids = NULL;
2818         num_sids = 0;
2819
2820         if (pdb_get_username(user) == NULL) {
2821                 return NT_STATUS_INVALID_PARAMETER;
2822         }
2823
2824         escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2825         if (escape_name == NULL)
2826                 return NT_STATUS_NO_MEMORY;
2827
2828         if (user->unix_pw) {
2829                 primary_gid = user->unix_pw->pw_gid;
2830         } else {
2831                 /* retrieve the users primary gid */
2832                 filter = talloc_asprintf(mem_ctx,
2833                                          "(&(objectClass=%s)(uid=%s))",
2834                                          LDAP_OBJ_SAMBASAMACCOUNT,
2835                                          escape_name);
2836                 if (filter == NULL) {
2837                         ret = NT_STATUS_NO_MEMORY;
2838                         goto done;
2839                 }
2840
2841                 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2842                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2843
2844                 if (rc != LDAP_SUCCESS)
2845                         goto done;
2846
2847                 talloc_autofree_ldapmsg(mem_ctx, result);
2848
2849                 count = ldap_count_entries(priv2ld(ldap_state), result);
2850
2851                 switch (count) {
2852                 case 0:
2853                         DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2854                         ret = NT_STATUS_NO_SUCH_USER;
2855                         goto done;
2856                 case 1:
2857                         entry = ldap_first_entry(priv2ld(ldap_state), result);
2858
2859                         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2860                         if (!gidstr) {
2861                                 DEBUG (1, ("Unable to find the member's gid!\n"));
2862                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2863                                 goto done;
2864                         }
2865                         primary_gid = strtoul(gidstr, NULL, 10);
2866                         break;
2867                 default:
2868                         DEBUG(1, ("found more than one account with the same user name ?!\n"));
2869                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2870                         goto done;
2871                 }
2872         }
2873
2874         filter = talloc_asprintf(mem_ctx,
2875                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2876                                  LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2877         if (filter == NULL) {
2878                 ret = NT_STATUS_NO_MEMORY;
2879                 goto done;
2880         }
2881
2882         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2883                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2884
2885         if (rc != LDAP_SUCCESS)
2886                 goto done;
2887
2888         talloc_autofree_ldapmsg(mem_ctx, result);
2889
2890         num_gids = 0;
2891         *pp_gids = NULL;
2892
2893         num_sids = 0;
2894         *pp_sids = NULL;
2895
2896         /* We need to add the primary group as the first gid/sid */
2897
2898         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2899                 ret = NT_STATUS_NO_MEMORY;
2900                 goto done;
2901         }
2902
2903         /* This sid will be replaced later */
2904
2905         ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2906                                       &num_sids);
2907         if (!NT_STATUS_IS_OK(ret)) {
2908                 goto done;
2909         }
2910
2911         for (entry = ldap_first_entry(conn->ldap_struct, result);
2912              entry != NULL;
2913              entry = ldap_next_entry(conn->ldap_struct, entry))
2914         {
2915                 fstring str;
2916                 struct dom_sid sid;
2917                 gid_t gid;
2918                 char *end;
2919
2920                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2921                                                   entry, "sambaSID",
2922                                                   str, sizeof(str)-1))
2923                         continue;
2924
2925                 if (!string_to_sid(&sid, str))
2926                         goto done;
2927
2928                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2929                                                   entry, "gidNumber",
2930                                                   str, sizeof(str)-1))
2931                         continue;
2932
2933                 gid = strtoul(str, &end, 10);
2934
2935                 if (PTR_DIFF(end, str) != strlen(str))
2936                         goto done;
2937
2938                 if (gid == primary_gid) {
2939                         sid_copy(&(*pp_sids)[0], &sid);
2940                 } else {
2941                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2942                                                 &num_gids)) {
2943                                 ret = NT_STATUS_NO_MEMORY;
2944                                 goto done;
2945                         }
2946                         ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2947                                                       &num_sids);
2948                         if (!NT_STATUS_IS_OK(ret)) {
2949                                 goto done;
2950                         }
2951                 }
2952         }
2953
2954         if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2955                 DEBUG(3, ("primary group of [%s] not found\n",
2956                           pdb_get_username(user)));
2957                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2958                 goto done;
2959         }
2960
2961         *p_num_groups = num_sids;
2962
2963         ret = NT_STATUS_OK;
2964
2965  done:
2966
2967         TALLOC_FREE(escape_name);
2968         return ret;
2969 }
2970
2971 /**********************************************************************
2972  * Augment a posixGroup object with a sambaGroupMapping domgroup
2973  *********************************************************************/
2974
2975 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2976                                        struct ldapsam_privates *ldap_state,
2977                                        GROUP_MAP *map)
2978 {
2979         const char *filter, *dn;
2980         LDAPMessage *msg, *entry;
2981         LDAPMod **mods;
2982         int rc;
2983
2984         filter = talloc_asprintf(mem_ctx,
2985                                  "(&(objectClass=%s)(gidNumber=%u))",
2986                                  LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2987         if (filter == NULL) {
2988                 return NT_STATUS_NO_MEMORY;
2989         }
2990
2991         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2992                                    get_attr_list(mem_ctx, groupmap_attr_list),
2993                                    &msg);
2994         talloc_autofree_ldapmsg(mem_ctx, msg);
2995
2996         if ((rc != LDAP_SUCCESS) ||
2997             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2998             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2999                 return NT_STATUS_NO_SUCH_GROUP;
3000         }
3001
3002         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3003         if (dn == NULL) {
3004                 return NT_STATUS_NO_MEMORY;
3005         }
3006
3007         mods = NULL;
3008         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3009                         LDAP_OBJ_GROUPMAP);
3010         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3011                          sid_string_talloc(mem_ctx, &map->sid));
3012         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3013                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3014         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3015                          map->nt_name);
3016         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3017                          map->comment);
3018         talloc_autofree_ldapmod(mem_ctx, mods);
3019
3020         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3021         if (rc != LDAP_SUCCESS) {
3022                 return NT_STATUS_ACCESS_DENIED;
3023         }
3024
3025         return NT_STATUS_OK;
3026 }
3027
3028 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3029                                                 GROUP_MAP *map)
3030 {
3031         struct ldapsam_privates *ldap_state =
3032                 (struct ldapsam_privates *)methods->private_data;
3033         LDAPMessage *msg = NULL;
3034         LDAPMod **mods = NULL;
3035         const char *attrs[] = { NULL };
3036         char *filter;
3037
3038         char *dn;
3039         TALLOC_CTX *mem_ctx;
3040         NTSTATUS result;
3041
3042         struct dom_sid sid;
3043
3044         int rc;
3045
3046         mem_ctx = talloc_new(NULL);
3047         if (mem_ctx == NULL) {
3048                 DEBUG(0, ("talloc_new failed\n"));
3049                 return NT_STATUS_NO_MEMORY;
3050         }
3051
3052         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3053                                  sid_string_talloc(mem_ctx, &map->sid));
3054         if (filter == NULL) {
3055                 result = NT_STATUS_NO_MEMORY;
3056                 goto done;
3057         }
3058
3059         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3060                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3061         talloc_autofree_ldapmsg(mem_ctx, msg);
3062
3063         if ((rc == LDAP_SUCCESS) &&
3064             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3065
3066                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3067                           "group mapping entry\n", sid_string_dbg(&map->sid)));
3068                 result = NT_STATUS_GROUP_EXISTS;
3069                 goto done;
3070         }
3071
3072         switch (map->sid_name_use) {
3073
3074         case SID_NAME_DOM_GRP:
3075                 /* To map a domain group we need to have a posix group
3076                    to attach to. */
3077                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3078                 goto done;
3079                 break;
3080
3081         case SID_NAME_ALIAS:
3082                 if (!sid_check_is_in_our_sam(&map->sid) 
3083                         && !sid_check_is_in_builtin(&map->sid) ) 
3084                 {
3085                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3086                                   sid_string_dbg(&map->sid)));
3087                         result = NT_STATUS_INVALID_PARAMETER;
3088                         goto done;
3089                 }
3090                 break;
3091
3092         default:
3093                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3094                           sid_type_lookup(map->sid_name_use)));
3095                 result = NT_STATUS_INVALID_PARAMETER;
3096                 goto done;
3097         }
3098
3099         /* Domain groups have been mapped in a separate routine, we have to
3100          * create an alias now */
3101
3102         if (map->gid == -1) {
3103                 DEBUG(10, ("Refusing to map gid==-1\n"));
3104                 result = NT_STATUS_INVALID_PARAMETER;
3105                 goto done;
3106         }
3107
3108         if (pdb_gid_to_sid(map->gid, &sid)) {
3109                 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3110                           "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3111                 result = NT_STATUS_GROUP_EXISTS;
3112                 goto done;
3113         }
3114
3115         /* Ok, enough checks done. It's still racy to go ahead now, but that's
3116          * the best we can get out of LDAP. */
3117
3118         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3119                              sid_string_talloc(mem_ctx, &map->sid),
3120                              lp_ldap_group_suffix(talloc_tos()));
3121         if (dn == NULL) {
3122                 result = NT_STATUS_NO_MEMORY;
3123                 goto done;
3124         }
3125
3126         mods = NULL;
3127
3128         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3129                          LDAP_OBJ_SID_ENTRY);
3130         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3131                          LDAP_OBJ_GROUPMAP);
3132         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3133                          sid_string_talloc(mem_ctx, &map->sid));
3134         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3135                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3136         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3137  &nb