passdb: Remove pdb_ipa
[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 #include "lib/util_sid_passdb.h"
57
58 #undef DBGC_CLASS
59 #define DBGC_CLASS DBGC_PASSDB
60
61 #include <lber.h>
62 #include <ldap.h>
63
64
65 #include "smbldap.h"
66 #include "passdb/pdb_ldap.h"
67 #include "passdb/pdb_nds.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 SID.
351 ******************************************************************/
352
353 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
354                                  const struct dom_sid *sid, LDAPMessage ** result,
355                                  const char **attr)
356 {
357         char *filter = NULL;
358         int rc;
359         fstring sid_string;
360
361         filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
362                 get_userattr_key2string(ldap_state->schema_ver,
363                         LDAP_ATTR_USER_SID),
364                 sid_to_fstring(sid_string, sid),
365                 get_objclass_filter(ldap_state->schema_ver));
366         if (!filter) {
367                 return LDAP_NO_MEMORY;
368         }
369
370         rc = smbldap_search_suffix(ldap_state->smbldap_state,
371                         filter, attr, result);
372
373         TALLOC_FREE(filter);
374         return rc;
375 }
376
377 /*******************************************************************
378  Delete complete object or objectclass and attrs from
379  object found in search_result depending on lp_ldap_delete_dn
380 ******************************************************************/
381
382 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
383                                 TALLOC_CTX *mem_ctx,
384                                 LDAPMessage *entry,
385                                 const char *objectclass,
386                                 const char **attrs)
387 {
388         LDAPMod **mods = NULL;
389         char *name;
390         const char *dn;
391         BerElement *ptr = NULL;
392
393         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
394         if (dn == NULL) {
395                 return LDAP_NO_MEMORY;
396         }
397
398         if (lp_ldap_delete_dn()) {
399                 return smbldap_delete(priv->smbldap_state, dn);
400         }
401
402         /* Ok, delete only the SAM attributes */
403
404         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
405              name != NULL;
406              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
407                 const char **attrib;
408
409                 /* We are only allowed to delete the attributes that
410                    really exist. */
411
412                 for (attrib = attrs; *attrib != NULL; attrib++) {
413                         if (strequal(*attrib, name)) {
414                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
415                                            "attribute %s\n", name));
416                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
417                                                 NULL);
418                         }
419                 }
420                 ldap_memfree(name);
421         }
422
423         if (ptr != NULL) {
424                 ber_free(ptr, 0);
425         }
426
427         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
428         smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
429
430         return smbldap_modify(priv->smbldap_state, dn, mods);
431 }
432
433 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
434 {
435         char *temp;
436         struct tm tm;
437
438         temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
439                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
440                         talloc_tos());
441         if (!temp) {
442                 return (time_t) 0;
443         }
444
445         if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
446                 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
447                         (char*)temp));
448                 TALLOC_FREE(temp);
449                 return (time_t) 0;
450         }
451         TALLOC_FREE(temp);
452         tzset();
453         return timegm(&tm);
454 }
455
456 /**********************************************************************
457  Initialize struct samu from an LDAP query.
458  (Based on init_sam_from_buffer in pdb_tdb.c)
459 *********************************************************************/
460
461 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
462                                 struct samu * sampass,
463                                 LDAPMessage * entry)
464 {
465         time_t  logon_time,
466                         logoff_time,
467                         kickoff_time,
468                         pass_last_set_time,
469                         pass_can_change_time,
470                         ldap_entry_time,
471                         bad_password_time;
472         char *username = NULL,
473                         *domain = NULL,
474                         *nt_username = NULL,
475                         *fullname = NULL,
476                         *homedir = NULL,
477                         *dir_drive = NULL,
478                         *logon_script = NULL,
479                         *profile_path = NULL,
480                         *acct_desc = NULL,
481                         *workstations = NULL,
482                         *munged_dial = NULL;
483         uint32_t                user_rid;
484         uint8_t         smblmpwd[LM_HASH_LEN],
485                         smbntpwd[NT_HASH_LEN];
486         bool            use_samba_attrs = True;
487         uint32_t                acct_ctrl = 0;
488         uint16_t                logon_divs;
489         uint16_t                bad_password_count = 0,
490                         logon_count = 0;
491         uint32_t hours_len;
492         uint8_t         hours[MAX_HOURS_LEN];
493         char *temp = NULL;
494         struct login_cache cache_entry;
495         uint32_t                pwHistLen;
496         bool expand_explicit = lp_passdb_expand_explicit();
497         bool ret = false;
498         TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
499
500         if (!ctx) {
501                 return false;
502         }
503         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
504                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
505                 goto fn_exit;
506         }
507
508         if (priv2ld(ldap_state) == NULL) {
509                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
510                           "ldap_struct is NULL!\n"));
511                 goto fn_exit;
512         }
513
514         if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
515                                         entry,
516                                         "uid",
517                                         ctx))) {
518                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
519                           "this user!\n"));
520                 goto fn_exit;
521         }
522
523         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
524
525         nt_username = talloc_strdup(ctx, username);
526         if (!nt_username) {
527                 goto fn_exit;
528         }
529
530         domain = talloc_strdup(ctx, ldap_state->domain_name);
531         if (!domain) {
532                 goto fn_exit;
533         }
534
535         pdb_set_username(sampass, username, PDB_SET);
536
537         pdb_set_domain(sampass, domain, PDB_DEFAULT);
538         pdb_set_nt_username(sampass, nt_username, PDB_SET);
539
540         /* deal with different attributes between the schema first */
541
542         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
543                 if ((temp = smbldap_talloc_single_attribute(
544                                 ldap_state->smbldap_state->ldap_struct,
545                                 entry,
546                                 get_userattr_key2string(ldap_state->schema_ver,
547                                         LDAP_ATTR_USER_SID),
548                                 ctx))!=NULL) {
549                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
550                 }
551         } else {
552                 if ((temp = smbldap_talloc_single_attribute(
553                                 ldap_state->smbldap_state->ldap_struct,
554                                 entry,
555                                 get_userattr_key2string(ldap_state->schema_ver,
556                                         LDAP_ATTR_USER_RID),
557                                 ctx))!=NULL) {
558                         user_rid = (uint32_t)atol(temp);
559                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
560                 }
561         }
562
563         if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
564                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
565                         get_userattr_key2string(ldap_state->schema_ver,
566                                 LDAP_ATTR_USER_SID),
567                         get_userattr_key2string(ldap_state->schema_ver,
568                                 LDAP_ATTR_USER_RID),
569                         username));
570                 return False;
571         }
572
573         temp = smbldap_talloc_single_attribute(
574                         ldap_state->smbldap_state->ldap_struct,
575                         entry,
576                         get_userattr_key2string(ldap_state->schema_ver,
577                                 LDAP_ATTR_PWD_LAST_SET),
578                         ctx);
579         if (temp) {
580                 pass_last_set_time = (time_t) atol(temp);
581                 pdb_set_pass_last_set_time(sampass,
582                                 pass_last_set_time, PDB_SET);
583         }
584
585         temp = smbldap_talloc_single_attribute(
586                         ldap_state->smbldap_state->ldap_struct,
587                         entry,
588                         get_userattr_key2string(ldap_state->schema_ver,
589                                 LDAP_ATTR_LOGON_TIME),
590                         ctx);
591         if (temp) {
592                 logon_time = (time_t) atol(temp);
593                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
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_LOGOFF_TIME),
601                         ctx);
602         if (temp) {
603                 logoff_time = (time_t) atol(temp);
604                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
605         }
606
607         temp = smbldap_talloc_single_attribute(
608                         ldap_state->smbldap_state->ldap_struct,
609                         entry,
610                         get_userattr_key2string(ldap_state->schema_ver,
611                                 LDAP_ATTR_KICKOFF_TIME),
612                         ctx);
613         if (temp) {
614                 kickoff_time = (time_t) atol(temp);
615                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
616         }
617
618         temp = smbldap_talloc_single_attribute(
619                         ldap_state->smbldap_state->ldap_struct,
620                         entry,
621                         get_userattr_key2string(ldap_state->schema_ver,
622                                 LDAP_ATTR_PWD_CAN_CHANGE),
623                         ctx);
624         if (temp) {
625                 pass_can_change_time = (time_t) atol(temp);
626                 pdb_set_pass_can_change_time(sampass,
627                                 pass_can_change_time, PDB_SET);
628         }
629
630         /* recommend that 'gecos' and 'displayName' should refer to the same
631          * attribute OID.  userFullName depreciated, only used by Samba
632          * primary rules of LDAP: don't make a new attribute when one is already defined
633          * that fits your needs; using cn then displayName rather than 'userFullName'
634          */
635
636         fullname = smbldap_talloc_single_attribute(
637                         ldap_state->smbldap_state->ldap_struct,
638                         entry,
639                         get_userattr_key2string(ldap_state->schema_ver,
640                                 LDAP_ATTR_DISPLAY_NAME),
641                         ctx);
642         if (fullname) {
643                 pdb_set_fullname(sampass, fullname, PDB_SET);
644         } else {
645                 fullname = smbldap_talloc_single_attribute(
646                                 ldap_state->smbldap_state->ldap_struct,
647                                 entry,
648                                 get_userattr_key2string(ldap_state->schema_ver,
649                                         LDAP_ATTR_CN),
650                                 ctx);
651                 if (fullname) {
652                         pdb_set_fullname(sampass, fullname, PDB_SET);
653                 }
654         }
655
656         dir_drive = smbldap_talloc_single_attribute(
657                         ldap_state->smbldap_state->ldap_struct,
658                         entry,
659                         get_userattr_key2string(ldap_state->schema_ver,
660                                 LDAP_ATTR_HOME_DRIVE),
661                         ctx);
662         if (dir_drive) {
663                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
664         } else {
665                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
666         }
667
668         homedir = smbldap_talloc_single_attribute(
669                         ldap_state->smbldap_state->ldap_struct,
670                         entry,
671                         get_userattr_key2string(ldap_state->schema_ver,
672                                 LDAP_ATTR_HOME_PATH),
673                         ctx);
674         if (homedir) {
675                 if (expand_explicit) {
676                         homedir = talloc_sub_basic(ctx,
677                                                 username,
678                                                 domain,
679                                                 homedir);
680                         if (!homedir) {
681                                 goto fn_exit;
682                         }
683                 }
684                 pdb_set_homedir(sampass, homedir, PDB_SET);
685         } else {
686                 pdb_set_homedir(sampass,
687                         talloc_sub_basic(ctx, username, domain,
688                                          lp_logon_home()),
689                         PDB_DEFAULT);
690         }
691
692         logon_script = smbldap_talloc_single_attribute(
693                         ldap_state->smbldap_state->ldap_struct,
694                         entry,
695                         get_userattr_key2string(ldap_state->schema_ver,
696                                 LDAP_ATTR_LOGON_SCRIPT),
697                         ctx);
698         if (logon_script) {
699                 if (expand_explicit) {
700                         logon_script = talloc_sub_basic(ctx,
701                                                 username,
702                                                 domain,
703                                                 logon_script);
704                         if (!logon_script) {
705                                 goto fn_exit;
706                         }
707                 }
708                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
709         } else {
710                 pdb_set_logon_script(sampass,
711                         talloc_sub_basic(ctx, username, domain,
712                                          lp_logon_script()),
713                         PDB_DEFAULT );
714         }
715
716         profile_path = smbldap_talloc_single_attribute(
717                         ldap_state->smbldap_state->ldap_struct,
718                         entry,
719                         get_userattr_key2string(ldap_state->schema_ver,
720                                 LDAP_ATTR_PROFILE_PATH),
721                         ctx);
722         if (profile_path) {
723                 if (expand_explicit) {
724                         profile_path = talloc_sub_basic(ctx,
725                                                 username,
726                                                 domain,
727                                                 profile_path);
728                         if (!profile_path) {
729                                 goto fn_exit;
730                         }
731                 }
732                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
733         } else {
734                 pdb_set_profile_path(sampass,
735                         talloc_sub_basic(ctx, username, domain,
736                                           lp_logon_path()),
737                         PDB_DEFAULT );
738         }
739
740         acct_desc = smbldap_talloc_single_attribute(
741                         ldap_state->smbldap_state->ldap_struct,
742                         entry,
743                         get_userattr_key2string(ldap_state->schema_ver,
744                                 LDAP_ATTR_DESC),
745                         ctx);
746         if (acct_desc) {
747                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
748         }
749
750         workstations = smbldap_talloc_single_attribute(
751                         ldap_state->smbldap_state->ldap_struct,
752                         entry,
753                         get_userattr_key2string(ldap_state->schema_ver,
754                                 LDAP_ATTR_USER_WKS),
755                         ctx);
756         if (workstations) {
757                 pdb_set_workstations(sampass, workstations, PDB_SET);
758         }
759
760         munged_dial = smbldap_talloc_single_attribute(
761                         ldap_state->smbldap_state->ldap_struct,
762                         entry,
763                         get_userattr_key2string(ldap_state->schema_ver,
764                                 LDAP_ATTR_MUNGED_DIAL),
765                         ctx);
766         if (munged_dial) {
767                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
768         }
769
770         /* FIXME: hours stuff should be cleaner */
771
772         logon_divs = 168;
773         hours_len = 21;
774         memset(hours, 0xff, hours_len);
775
776         if (ldap_state->is_nds_ldap) {
777                 char *user_dn;
778                 size_t pwd_len;
779                 char clear_text_pw[512];
780
781                 /* Make call to Novell eDirectory ldap extension to get clear text password.
782                         NOTE: This will only work if we have an SSL connection to eDirectory. */
783                 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
784                 if (user_dn != NULL) {
785                         DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
786
787                         pwd_len = sizeof(clear_text_pw);
788                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
789                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
790                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
791                                         TALLOC_FREE(user_dn);
792                                         return False;
793                                 }
794                                 ZERO_STRUCT(smblmpwd);
795                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
796                                         TALLOC_FREE(user_dn);
797                                         return False;
798                                 }
799                                 ZERO_STRUCT(smbntpwd);
800                                 use_samba_attrs = False;
801                         }
802
803                         TALLOC_FREE(user_dn);
804
805                 } else {
806                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
807                 }
808         }
809
810         if (use_samba_attrs) {
811                 temp = smbldap_talloc_single_attribute(
812                                 ldap_state->smbldap_state->ldap_struct,
813                                 entry,
814                                 get_userattr_key2string(ldap_state->schema_ver,
815                                         LDAP_ATTR_LMPW),
816                                 ctx);
817                 if (temp) {
818                         pdb_gethexpwd(temp, smblmpwd);
819                         memset((char *)temp, '\0', strlen(temp)+1);
820                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
821                                 goto fn_exit;
822                         }
823                         ZERO_STRUCT(smblmpwd);
824                 }
825
826                 temp = smbldap_talloc_single_attribute(
827                                 ldap_state->smbldap_state->ldap_struct,
828                                 entry,
829                                 get_userattr_key2string(ldap_state->schema_ver,
830                                         LDAP_ATTR_NTPW),
831                                 ctx);
832                 if (temp) {
833                         pdb_gethexpwd(temp, smbntpwd);
834                         memset((char *)temp, '\0', strlen(temp)+1);
835                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
836                                 goto fn_exit;
837                         }
838                         ZERO_STRUCT(smbntpwd);
839                 }
840         }
841
842         pwHistLen = 0;
843
844         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
845         if (pwHistLen > 0){
846                 uint8_t *pwhist = NULL;
847                 int i;
848                 char *history_string = talloc_array(ctx, char,
849                                                 MAX_PW_HISTORY_LEN*64);
850
851                 if (!history_string) {
852                         goto fn_exit;
853                 }
854
855                 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
856
857                 pwhist = talloc_zero_array(ctx, uint8_t,
858                                            pwHistLen * PW_HISTORY_ENTRY_LEN);
859                 if (pwhist == NULL) {
860                         DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
861                         goto fn_exit;
862                 }
863
864                 if (smbldap_get_single_attribute(
865                                 ldap_state->smbldap_state->ldap_struct,
866                                 entry,
867                                 get_userattr_key2string(ldap_state->schema_ver,
868                                         LDAP_ATTR_PWD_HISTORY),
869                                 history_string,
870                                 MAX_PW_HISTORY_LEN*64)) {
871                         bool hex_failed = false;
872                         for (i = 0; i < pwHistLen; i++){
873                                 /* Get the 16 byte salt. */
874                                 if (!pdb_gethexpwd(&history_string[i*64],
875                                         &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
876                                         hex_failed = true;
877                                         break;
878                                 }
879                                 /* Get the 16 byte MD5 hash of salt+passwd. */
880                                 if (!pdb_gethexpwd(&history_string[(i*64)+32],
881                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
882                                                 PW_HISTORY_SALT_LEN])) {
883                                         hex_failed = True;
884                                         break;
885                                 }
886                         }
887                         if (hex_failed) {
888                                 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
889                                         username));
890                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
891                         }
892                 }
893                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
894                         goto fn_exit;
895                 }
896         }
897
898         temp = smbldap_talloc_single_attribute(
899                         ldap_state->smbldap_state->ldap_struct,
900                         entry,
901                         get_userattr_key2string(ldap_state->schema_ver,
902                                 LDAP_ATTR_ACB_INFO),
903                         ctx);
904         if (temp) {
905                 acct_ctrl = pdb_decode_acct_ctrl(temp);
906
907                 if (acct_ctrl == 0) {
908                         acct_ctrl |= ACB_NORMAL;
909                 }
910
911                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
912         } else {
913                 acct_ctrl |= ACB_NORMAL;
914         }
915
916         pdb_set_hours_len(sampass, hours_len, PDB_SET);
917         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
918
919         temp = smbldap_talloc_single_attribute(
920                         ldap_state->smbldap_state->ldap_struct,
921                         entry,
922                         get_userattr_key2string(ldap_state->schema_ver,
923                                 LDAP_ATTR_BAD_PASSWORD_COUNT),
924                         ctx);
925         if (temp) {
926                 bad_password_count = (uint32_t) atol(temp);
927                 pdb_set_bad_password_count(sampass,
928                                 bad_password_count, PDB_SET);
929         }
930
931         temp = smbldap_talloc_single_attribute(
932                         ldap_state->smbldap_state->ldap_struct,
933                         entry,
934                         get_userattr_key2string(ldap_state->schema_ver,
935                                 LDAP_ATTR_BAD_PASSWORD_TIME),
936                         ctx);
937         if (temp) {
938                 bad_password_time = (time_t) atol(temp);
939                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
940         }
941
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_LOGON_COUNT),
948                         ctx);
949         if (temp) {
950                 logon_count = (uint32_t) atol(temp);
951                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
952         }
953
954         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
955
956         temp = smbldap_talloc_single_attribute(
957                         ldap_state->smbldap_state->ldap_struct,
958                         entry,
959                         get_userattr_key2string(ldap_state->schema_ver,
960                                 LDAP_ATTR_LOGON_HOURS),
961                         ctx);
962         if (temp) {
963                 pdb_gethexhours(temp, hours);
964                 memset((char *)temp, '\0', strlen(temp) +1);
965                 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
966                 ZERO_STRUCT(hours);
967         }
968
969         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
970                 struct passwd unix_pw;
971                 bool have_uid = false;
972                 bool have_gid = false;
973                 struct dom_sid mapped_gsid;
974                 const struct dom_sid *primary_gsid;
975                 struct unixid id;
976
977                 ZERO_STRUCT(unix_pw);
978
979                 unix_pw.pw_name = username;
980                 unix_pw.pw_passwd = discard_const_p(char, "x");
981
982                 temp = smbldap_talloc_single_attribute(
983                                 priv2ld(ldap_state),
984                                 entry,
985                                 "uidNumber",
986                                 ctx);
987                 if (temp) {
988                         /* We've got a uid, feed the cache */
989                         unix_pw.pw_uid = strtoul(temp, NULL, 10);
990                         have_uid = true;
991                 }
992                 temp = smbldap_talloc_single_attribute(
993                                 priv2ld(ldap_state),
994                                 entry,
995                                 "gidNumber",
996                                 ctx);
997                 if (temp) {
998                         /* We've got a uid, feed the cache */
999                         unix_pw.pw_gid = strtoul(temp, NULL, 10);
1000                         have_gid = true;
1001                 }
1002                 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1003                                 priv2ld(ldap_state),
1004                                 entry,
1005                                 "gecos",
1006                                 ctx);
1007                 if (unix_pw.pw_gecos == NULL) {
1008                         unix_pw.pw_gecos = fullname;
1009                 }
1010                 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1011                                 priv2ld(ldap_state),
1012                                 entry,
1013                                 "homeDirectory",
1014                                 ctx);
1015                 if (unix_pw.pw_dir == NULL) {
1016                         unix_pw.pw_dir = discard_const_p(char, "");
1017                 }
1018                 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1019                                 priv2ld(ldap_state),
1020                                 entry,
1021                                 "loginShell",
1022                                 ctx);
1023                 if (unix_pw.pw_shell == NULL) {
1024                         unix_pw.pw_shell = discard_const_p(char, "");
1025                 }
1026
1027                 if (have_uid && have_gid) {
1028                         sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1029                 } else {
1030                         sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1031                 }
1032
1033                 if (sampass->unix_pw == NULL) {
1034                         DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1035                                  pdb_get_username(sampass)));
1036                         goto fn_exit;
1037                 }
1038
1039                 id.id = sampass->unix_pw->pw_uid;
1040                 id.type = ID_TYPE_UID;
1041
1042                 idmap_cache_set_sid2unixid(pdb_get_user_sid(sampass), &id);
1043
1044                 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1045                 primary_gsid = pdb_get_group_sid(sampass);
1046                 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1047                         id.id = sampass->unix_pw->pw_gid;
1048                         id.type = ID_TYPE_GID;
1049
1050                         idmap_cache_set_sid2unixid(primary_gsid, &id);
1051                 }
1052         }
1053
1054         /* check the timestamp of the cache vs ldap entry */
1055         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1056                                                             entry))) {
1057                 ret = true;
1058                 goto fn_exit;
1059         }
1060
1061         /* see if we have newer updates */
1062         if (!login_cache_read(sampass, &cache_entry)) {
1063                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1064                            (unsigned int)pdb_get_bad_password_count(sampass),
1065                            (unsigned int)pdb_get_bad_password_time(sampass)));
1066                 ret = true;
1067                 goto fn_exit;
1068         }
1069
1070         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1071                   (unsigned int)ldap_entry_time,
1072                   (unsigned int)cache_entry.entry_timestamp,
1073                   (unsigned int)cache_entry.bad_password_time));
1074
1075         if (ldap_entry_time > cache_entry.entry_timestamp) {
1076                 /* cache is older than directory , so
1077                    we need to delete the entry but allow the
1078                    fields to be written out */
1079                 login_cache_delentry(sampass);
1080         } else {
1081                 /* read cache in */
1082                 pdb_set_acct_ctrl(sampass,
1083                                   pdb_get_acct_ctrl(sampass) |
1084                                   (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1085                                   PDB_SET);
1086                 pdb_set_bad_password_count(sampass,
1087                                            cache_entry.bad_password_count,
1088                                            PDB_SET);
1089                 pdb_set_bad_password_time(sampass,
1090                                           cache_entry.bad_password_time,
1091                                           PDB_SET);
1092         }
1093
1094         ret = true;
1095
1096   fn_exit:
1097
1098         TALLOC_FREE(ctx);
1099         return ret;
1100 }
1101
1102 /**********************************************************************
1103  Initialize the ldap db from a struct samu. Called on update.
1104  (Based on init_buffer_from_sam in pdb_tdb.c)
1105 *********************************************************************/
1106
1107 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1108                                 LDAPMessage *existing,
1109                                 LDAPMod *** mods, struct samu * sampass,
1110                                 bool (*need_update)(const struct samu *,
1111                                                     enum pdb_elements))
1112 {
1113         char *temp = NULL;
1114
1115         if (mods == NULL || sampass == NULL) {
1116                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1117                 return False;
1118         }
1119
1120         *mods = NULL;
1121
1122         /*
1123          * took out adding "objectclass: sambaAccount"
1124          * do this on a per-mod basis
1125          */
1126         if (need_update(sampass, PDB_USERNAME)) {
1127                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1128                               "uid", pdb_get_username(sampass));
1129                 if (ldap_state->is_nds_ldap) {
1130                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1131                                       "cn", pdb_get_username(sampass));
1132                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1133                                       "sn", pdb_get_username(sampass));
1134                 }
1135         }
1136
1137         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1138
1139         /* only update the RID if we actually need to */
1140         if (need_update(sampass, PDB_USERSID)) {
1141                 fstring sid_string;
1142                 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1143
1144                 switch ( ldap_state->schema_ver ) {
1145                         case SCHEMAVER_SAMBASAMACCOUNT:
1146                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1147                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
1148                                         sid_to_fstring(sid_string, user_sid));
1149                                 break;
1150
1151                         default:
1152                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1153                                 break;
1154                 }
1155         }
1156
1157         /* we don't need to store the primary group RID - so leaving it
1158            'free' to hang off the unix primary group makes life easier */
1159
1160         if (need_update(sampass, PDB_GROUPSID)) {
1161                 fstring sid_string;
1162                 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1163
1164                 switch ( ldap_state->schema_ver ) {
1165                         case SCHEMAVER_SAMBASAMACCOUNT:
1166                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1167                                         get_userattr_key2string(ldap_state->schema_ver, 
1168                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1169                                 break;
1170
1171                         default:
1172                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1173                                 break;
1174                 }
1175
1176         }
1177
1178         /* displayName, cn, and gecos should all be the same
1179          *  most easily accomplished by giving them the same OID
1180          *  gecos isn't set here b/c it should be handled by the
1181          *  add-user script
1182          *  We change displayName only and fall back to cn if
1183          *  it does not exist.
1184          */
1185
1186         if (need_update(sampass, PDB_FULLNAME))
1187                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1188                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1189                         pdb_get_fullname(sampass));
1190
1191         if (need_update(sampass, PDB_ACCTDESC))
1192                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1193                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1194                         pdb_get_acct_desc(sampass));
1195
1196         if (need_update(sampass, PDB_WORKSTATIONS))
1197                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1198                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1199                         pdb_get_workstations(sampass));
1200
1201         if (need_update(sampass, PDB_MUNGEDDIAL))
1202                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1203                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1204                         pdb_get_munged_dial(sampass));
1205
1206         if (need_update(sampass, PDB_SMBHOME))
1207                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1208                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1209                         pdb_get_homedir(sampass));
1210
1211         if (need_update(sampass, PDB_DRIVE))
1212                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1213                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1214                         pdb_get_dir_drive(sampass));
1215
1216         if (need_update(sampass, PDB_LOGONSCRIPT))
1217                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1218                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1219                         pdb_get_logon_script(sampass));
1220
1221         if (need_update(sampass, PDB_PROFILE))
1222                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1223                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1224                         pdb_get_profile_path(sampass));
1225
1226         if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1227                 return false;
1228         }
1229         if (need_update(sampass, PDB_LOGONTIME))
1230                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1231                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1232         SAFE_FREE(temp);
1233
1234         if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1235                 return false;
1236         }
1237         if (need_update(sampass, PDB_LOGOFFTIME))
1238                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1239                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1240         SAFE_FREE(temp);
1241
1242         if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1243                 return false;
1244         }
1245         if (need_update(sampass, PDB_KICKOFFTIME))
1246                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1247                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1248         SAFE_FREE(temp);
1249
1250         if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1251                 return false;
1252         }
1253         if (need_update(sampass, PDB_CANCHANGETIME))
1254                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1255                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1256         SAFE_FREE(temp);
1257
1258         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1259                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1260
1261                 if (need_update(sampass, PDB_LMPASSWD)) {
1262                         const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1263                         if (lm_pw) {
1264                                 char pwstr[34];
1265                                 pdb_sethexpwd(pwstr, lm_pw,
1266                                               pdb_get_acct_ctrl(sampass));
1267                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1268                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1269                                                  pwstr);
1270                         } else {
1271                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1272                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1273                                                  NULL);
1274                         }
1275                 }
1276                 if (need_update(sampass, PDB_NTPASSWD)) {
1277                         const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1278                         if (nt_pw) {
1279                                 char pwstr[34];
1280                                 pdb_sethexpwd(pwstr, nt_pw,
1281                                               pdb_get_acct_ctrl(sampass));
1282                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1283                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1284                                                  pwstr);
1285                         } else {
1286                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1287                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1288                                                  NULL);
1289                         }
1290                 }
1291
1292                 if (need_update(sampass, PDB_PWHISTORY)) {
1293                         char *pwstr = NULL;
1294                         uint32_t pwHistLen = 0;
1295                         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1296
1297                         pwstr = SMB_MALLOC_ARRAY(char, 1024);
1298                         if (!pwstr) {
1299                                 return false;
1300                         }
1301                         if (pwHistLen == 0) {
1302                                 /* Remove any password history from the LDAP store. */
1303                                 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1304                                 pwstr[64] = '\0';
1305                         } else {
1306                                 int i;
1307                                 uint32_t currHistLen = 0;
1308                                 const uint8_t *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1309                                 if (pwhist != NULL) {
1310                                         /* We can only store (1024-1/64 password history entries. */
1311                                         pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1312                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1313                                                 /* Store the salt. */
1314                                                 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1315                                                 /* Followed by the md5 hash of salt + md4 hash */
1316                                                 pdb_sethexpwd(&pwstr[(i*64)+32],
1317                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1318                                                 DEBUG(100, ("pwstr=%s\n", pwstr));
1319                                         }
1320                                 }
1321                         }
1322                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1323                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1324                                          pwstr);
1325                         SAFE_FREE(pwstr);
1326                 }
1327
1328                 if (need_update(sampass, PDB_PASSLASTSET)) {
1329                         if (asprintf(&temp, "%li",
1330                                 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1331                                 return false;
1332                         }
1333                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1334                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1335                                 temp);
1336                         SAFE_FREE(temp);
1337                 }
1338         }
1339
1340         if (need_update(sampass, PDB_HOURS)) {
1341                 const uint8_t *hours = pdb_get_hours(sampass);
1342                 if (hours) {
1343                         char hourstr[44];
1344                         pdb_sethexhours(hourstr, hours);
1345                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1346                                 existing,
1347                                 mods,
1348                                 get_userattr_key2string(ldap_state->schema_ver,
1349                                                 LDAP_ATTR_LOGON_HOURS),
1350                                 hourstr);
1351                 }
1352         }
1353
1354         if (need_update(sampass, PDB_ACCTCTRL))
1355                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1356                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1357                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1358
1359         /* password lockout cache:
1360            - If we are now autolocking or clearing, we write to ldap
1361            - If we are clearing, we delete the cache entry
1362            - If the count is > 0, we update the cache
1363
1364            This even means when autolocking, we cache, just in case the
1365            update doesn't work, and we have to cache the autolock flag */
1366
1367         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1368             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1369                 uint16_t badcount = pdb_get_bad_password_count(sampass);
1370                 time_t badtime = pdb_get_bad_password_time(sampass);
1371                 uint32_t pol;
1372                 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1373
1374                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1375                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1376
1377                 if ((badcount >= pol) || (badcount == 0)) {
1378                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1379                                 (unsigned int)badcount, (unsigned int)badtime));
1380                         if (asprintf(&temp, "%li", (long)badcount) < 0) {
1381                                 return false;
1382                         }
1383                         smbldap_make_mod(
1384                                 ldap_state->smbldap_state->ldap_struct,
1385                                 existing, mods,
1386                                 get_userattr_key2string(
1387                                         ldap_state->schema_ver,
1388                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1389                                 temp);
1390                         SAFE_FREE(temp);
1391
1392                         if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1393                                 return false;
1394                         }
1395                         smbldap_make_mod(
1396                                 ldap_state->smbldap_state->ldap_struct,
1397                                 existing, mods,
1398                                 get_userattr_key2string(
1399                                         ldap_state->schema_ver,
1400                                         LDAP_ATTR_BAD_PASSWORD_TIME),
1401                                 temp);
1402                         SAFE_FREE(temp);
1403                 }
1404                 if (badcount == 0) {
1405                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1406                         login_cache_delentry(sampass);
1407                 } else {
1408                         struct login_cache cache_entry;
1409
1410                         cache_entry.entry_timestamp = time(NULL);
1411                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1412                         cache_entry.bad_password_count = badcount;
1413                         cache_entry.bad_password_time = badtime;
1414
1415                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1416                         login_cache_write(sampass, &cache_entry);
1417                 }
1418         }
1419
1420         return True;
1421 }
1422
1423 /**********************************************************************
1424  End enumeration of the LDAP password list.
1425 *********************************************************************/
1426
1427 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1428 {
1429         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1430         if (ldap_state->result) {
1431                 ldap_msgfree(ldap_state->result);
1432                 ldap_state->result = NULL;
1433         }
1434 }
1435
1436 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1437                         const char *new_attr)
1438 {
1439         int i;
1440
1441         if (new_attr == NULL) {
1442                 return;
1443         }
1444
1445         for (i=0; (*attr_list)[i] != NULL; i++) {
1446                 ;
1447         }
1448
1449         (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1450                                             const char *,  i+2);
1451         SMB_ASSERT((*attr_list) != NULL);
1452         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1453         (*attr_list)[i+1] = NULL;
1454 }
1455
1456 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1457                                         const char ***attr_list)
1458 {
1459         append_attr(mem_ctx, attr_list, "uidNumber");
1460         append_attr(mem_ctx, attr_list, "gidNumber");
1461         append_attr(mem_ctx, attr_list, "homeDirectory");
1462         append_attr(mem_ctx, attr_list, "loginShell");
1463         append_attr(mem_ctx, attr_list, "gecos");
1464 }
1465
1466 /**********************************************************************
1467 Get struct samu entry from LDAP by username.
1468 *********************************************************************/
1469
1470 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1471 {
1472         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1473         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1474         LDAPMessage *result = NULL;
1475         LDAPMessage *entry = NULL;
1476         int count;
1477         const char ** attr_list;
1478         int rc;
1479
1480         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1481         append_attr(user, &attr_list,
1482                     get_userattr_key2string(ldap_state->schema_ver,
1483                                             LDAP_ATTR_MOD_TIMESTAMP));
1484         ldapsam_add_unix_attributes(user, &attr_list);
1485         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1486                                            attr_list);
1487         TALLOC_FREE( attr_list );
1488
1489         if ( rc != LDAP_SUCCESS ) 
1490                 return NT_STATUS_NO_SUCH_USER;
1491
1492         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1493
1494         if (count < 1) {
1495                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1496                 ldap_msgfree(result);
1497                 return NT_STATUS_NO_SUCH_USER;
1498         } else if (count > 1) {
1499                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1500                 ldap_msgfree(result);
1501                 return NT_STATUS_NO_SUCH_USER;
1502         }
1503
1504         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1505         if (entry) {
1506                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1507                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1508                         ldap_msgfree(result);
1509                         return NT_STATUS_NO_SUCH_USER;
1510                 }
1511                 pdb_set_backend_private_data(user, result, NULL,
1512                                              my_methods, PDB_CHANGED);
1513                 smbldap_talloc_autofree_ldapmsg(user, result);
1514                 ret = NT_STATUS_OK;
1515         } else {
1516                 ldap_msgfree(result);
1517         }
1518         return ret;
1519 }
1520
1521 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1522                                    const struct dom_sid *sid, LDAPMessage **result)
1523 {
1524         int rc = -1;
1525         const char ** attr_list;
1526
1527         switch ( ldap_state->schema_ver ) {
1528                 case SCHEMAVER_SAMBASAMACCOUNT: {
1529                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1530                         if (tmp_ctx == NULL) {
1531                                 return LDAP_NO_MEMORY;
1532                         }
1533
1534                         attr_list = get_userattr_list(tmp_ctx,
1535                                                       ldap_state->schema_ver);
1536                         append_attr(tmp_ctx, &attr_list,
1537                                     get_userattr_key2string(
1538                                             ldap_state->schema_ver,
1539                                             LDAP_ATTR_MOD_TIMESTAMP));
1540                         ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1541                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1542                                                           result, attr_list);
1543                         TALLOC_FREE(tmp_ctx);
1544
1545                         if ( rc != LDAP_SUCCESS ) 
1546                                 return rc;
1547                         break;
1548                 }
1549
1550                 default:
1551                         DEBUG(0,("Invalid schema version specified\n"));
1552                         break;
1553         }
1554         return rc;
1555 }
1556
1557 /**********************************************************************
1558  Get struct samu entry from LDAP by SID.
1559 *********************************************************************/
1560
1561 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1562 {
1563         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1564         LDAPMessage *result = NULL;
1565         LDAPMessage *entry = NULL;
1566         int count;
1567         int rc;
1568
1569         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1570                                           sid, &result); 
1571         if (rc != LDAP_SUCCESS)
1572                 return NT_STATUS_NO_SUCH_USER;
1573
1574         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1575
1576         if (count < 1) {
1577                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1578                           "count=%d\n", sid_string_dbg(sid), count));
1579                 ldap_msgfree(result);
1580                 return NT_STATUS_NO_SUCH_USER;
1581         }  else if (count > 1) {
1582                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1583                           "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1584                           count));
1585                 ldap_msgfree(result);
1586                 return NT_STATUS_NO_SUCH_USER;
1587         }
1588
1589         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1590         if (!entry) {
1591                 ldap_msgfree(result);
1592                 return NT_STATUS_NO_SUCH_USER;
1593         }
1594
1595         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1596                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1597                 ldap_msgfree(result);
1598                 return NT_STATUS_NO_SUCH_USER;
1599         }
1600
1601         pdb_set_backend_private_data(user, result, NULL,
1602                                      my_methods, PDB_CHANGED);
1603         smbldap_talloc_autofree_ldapmsg(user, result);
1604         return NT_STATUS_OK;
1605 }       
1606
1607 /********************************************************************
1608  Do the actual modification - also change a plaintext passord if 
1609  it it set.
1610 **********************************************************************/
1611
1612 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1613                                      struct samu *newpwd, char *dn,
1614                                      LDAPMod **mods, int ldap_op, 
1615                                      bool (*need_update)(const struct samu *, enum pdb_elements))
1616 {
1617         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1618         int rc;
1619
1620         if (!newpwd || !dn) {
1621                 return NT_STATUS_INVALID_PARAMETER;
1622         }
1623
1624         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1625                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1626                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1627                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1628                 BerElement *ber;
1629                 struct berval *bv;
1630                 char *retoid = NULL;
1631                 struct berval *retdata = NULL;
1632                 char *utf8_password;
1633                 char *utf8_dn;
1634                 size_t converted_size;
1635                 int ret;
1636
1637                 if (!ldap_state->is_nds_ldap) {
1638
1639                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1640                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1641                                 DEBUG(2, ("ldap password change requested, but LDAP "
1642                                           "server does not support it -- ignoring\n"));
1643                                 return NT_STATUS_OK;
1644                         }
1645                 }
1646
1647                 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1648                                         pdb_get_plaintext_passwd(newpwd),
1649                                         &converted_size))
1650                 {
1651                         return NT_STATUS_NO_MEMORY;
1652                 }
1653
1654                 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1655                         TALLOC_FREE(utf8_password);
1656                         return NT_STATUS_NO_MEMORY;
1657                 }
1658
1659                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1660                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1661                         TALLOC_FREE(utf8_password);
1662                         TALLOC_FREE(utf8_dn);
1663                         return NT_STATUS_UNSUCCESSFUL;
1664                 }
1665
1666                 if ((ber_printf (ber, "{") < 0) ||
1667                     (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1668                                  utf8_dn) < 0)) {
1669                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1670                                  "value <0\n"));
1671                         ber_free(ber,1);
1672                         TALLOC_FREE(utf8_dn);
1673                         TALLOC_FREE(utf8_password);
1674                         return NT_STATUS_UNSUCCESSFUL;
1675                 }
1676
1677                 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1678                         ret = ber_printf(ber, "ts}",
1679                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1680                                          utf8_password);
1681                 } else {
1682                         ret = ber_printf(ber, "}");
1683                 }
1684
1685                 if (ret < 0) {
1686                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1687                                  "value <0\n"));
1688                         ber_free(ber,1);
1689                         TALLOC_FREE(utf8_dn);
1690                         TALLOC_FREE(utf8_password);
1691                         return NT_STATUS_UNSUCCESSFUL;
1692                 }
1693
1694                 if ((rc = ber_flatten (ber, &bv))<0) {
1695                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1696                         ber_free(ber,1);
1697                         TALLOC_FREE(utf8_dn);
1698                         TALLOC_FREE(utf8_password);
1699                         return NT_STATUS_UNSUCCESSFUL;
1700                 }
1701
1702                 TALLOC_FREE(utf8_dn);
1703                 TALLOC_FREE(utf8_password);
1704                 ber_free(ber, 1);
1705
1706                 if (!ldap_state->is_nds_ldap) {
1707                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1708                                                         LDAP_EXOP_MODIFY_PASSWD,
1709                                                         bv, NULL, NULL, &retoid, 
1710                                                         &retdata);
1711                 } else {
1712                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1713                                                         pdb_get_plaintext_passwd(newpwd));
1714                 }
1715                 if (rc != LDAP_SUCCESS) {
1716                         char *ld_error = NULL;
1717
1718                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1719                                 DEBUG(3, ("Could not set userPassword "
1720                                           "attribute due to an objectClass "
1721                                           "violation -- ignoring\n"));
1722                                 ber_bvfree(bv);
1723                                 return NT_STATUS_OK;
1724                         }
1725
1726                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1727                                         &ld_error);
1728                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1729                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1730                         SAFE_FREE(ld_error);
1731                         ber_bvfree(bv);
1732 #if defined(LDAP_CONSTRAINT_VIOLATION)
1733                         if (rc == LDAP_CONSTRAINT_VIOLATION)
1734                                 return NT_STATUS_PASSWORD_RESTRICTION;
1735 #endif
1736                         return NT_STATUS_UNSUCCESSFUL;
1737                 } else {
1738                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1739 #ifdef DEBUG_PASSWORD
1740                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1741 #endif    
1742                         if (retdata)
1743                                 ber_bvfree(retdata);
1744                         if (retoid)
1745                                 ldap_memfree(retoid);
1746                 }
1747                 ber_bvfree(bv);
1748         }
1749
1750         if (!mods) {
1751                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1752                 /* may be password change below however */
1753         } else {
1754                 switch(ldap_op) {
1755                         case LDAP_MOD_ADD:
1756                                 if (ldap_state->is_nds_ldap) {
1757                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1758                                                         "objectclass",
1759                                                         "inetOrgPerson");
1760                                 } else {
1761                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1762                                                         "objectclass",
1763                                                         LDAP_OBJ_ACCOUNT);
1764                                 }
1765                                 rc = smbldap_add(ldap_state->smbldap_state,
1766                                                  dn, mods);
1767                                 break;
1768                         case LDAP_MOD_REPLACE:
1769                                 rc = smbldap_modify(ldap_state->smbldap_state,
1770                                                     dn ,mods);
1771                                 break;
1772                         default:
1773                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1774                                          ldap_op));
1775                                 return NT_STATUS_INVALID_PARAMETER;
1776                 }
1777
1778                 if (rc!=LDAP_SUCCESS) {
1779                         return NT_STATUS_UNSUCCESSFUL;
1780                 }
1781         }
1782
1783         return NT_STATUS_OK;
1784 }
1785
1786 /**********************************************************************
1787  Delete entry from LDAP for username.
1788 *********************************************************************/
1789
1790 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1791                                            struct samu * sam_acct)
1792 {
1793         struct ldapsam_privates *priv =
1794                 (struct ldapsam_privates *)my_methods->private_data;
1795         const char *sname;
1796         int rc;
1797         LDAPMessage *msg, *entry;
1798         NTSTATUS result = NT_STATUS_NO_MEMORY;
1799         const char **attr_list;
1800         TALLOC_CTX *mem_ctx;
1801
1802         if (!sam_acct) {
1803                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1804                 return NT_STATUS_INVALID_PARAMETER;
1805         }
1806
1807         sname = pdb_get_username(sam_acct);
1808
1809         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1810                   "LDAP.\n", sname));
1811
1812         mem_ctx = talloc_new(NULL);
1813         if (mem_ctx == NULL) {
1814                 DEBUG(0, ("talloc_new failed\n"));
1815                 goto done;
1816         }
1817
1818         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1819         if (attr_list == NULL) {
1820                 goto done;
1821         }
1822
1823         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1824
1825         if ((rc != LDAP_SUCCESS) ||
1826             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1827             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1828                 DEBUG(5, ("Could not find user %s\n", sname));
1829                 result = NT_STATUS_NO_SUCH_USER;
1830                 goto done;
1831         }
1832
1833         rc = ldapsam_delete_entry(
1834                 priv, mem_ctx, entry,
1835                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1836                 LDAP_OBJ_SAMBASAMACCOUNT : 0,
1837                 attr_list);
1838
1839         result = (rc == LDAP_SUCCESS) ?
1840                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1841
1842  done:
1843         TALLOC_FREE(mem_ctx);
1844         return result;
1845 }
1846
1847 /**********************************************************************
1848  Update struct samu.
1849 *********************************************************************/
1850
1851 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1852 {
1853         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1854         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1855         int rc = 0;
1856         char *dn;
1857         LDAPMessage *result = NULL;
1858         LDAPMessage *entry = NULL;
1859         LDAPMod **mods = NULL;
1860         const char **attr_list;
1861
1862         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1863         if (!result) {
1864                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1865                 if (pdb_get_username(newpwd) == NULL) {
1866                         return NT_STATUS_INVALID_PARAMETER;
1867                 }
1868                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1869                 TALLOC_FREE( attr_list );
1870                 if (rc != LDAP_SUCCESS) {
1871                         return NT_STATUS_UNSUCCESSFUL;
1872                 }
1873                 pdb_set_backend_private_data(newpwd, result, NULL,
1874                                              my_methods, PDB_CHANGED);
1875                 smbldap_talloc_autofree_ldapmsg(newpwd, result);
1876         }
1877
1878         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1879                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1880                 return NT_STATUS_UNSUCCESSFUL;
1881         }
1882
1883         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1884         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1885         if (!dn) {
1886                 return NT_STATUS_UNSUCCESSFUL;
1887         }
1888
1889         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1890
1891         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1892                                 pdb_element_is_changed)) {
1893                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1894                 TALLOC_FREE(dn);
1895                 if (mods != NULL)
1896                         ldap_mods_free(mods,True);
1897                 return NT_STATUS_UNSUCCESSFUL;
1898         }
1899
1900         if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1901             && (mods == NULL)) {
1902                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1903                          pdb_get_username(newpwd)));
1904                 TALLOC_FREE(dn);
1905                 return NT_STATUS_OK;
1906         }
1907
1908         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
1909
1910         if (mods != NULL) {
1911                 ldap_mods_free(mods,True);
1912         }
1913
1914         TALLOC_FREE(dn);
1915
1916         /*
1917          * We need to set the backend private data to NULL here. For example
1918          * setuserinfo level 25 does a pdb_update_sam_account twice on the
1919          * same one, and with the explicit delete / add logic for attribute
1920          * values the second time we would use the wrong "old" value which
1921          * does not exist in LDAP anymore. Thus the LDAP server would refuse
1922          * the update.
1923          * The existing LDAPMessage is still being auto-freed by the
1924          * destructor.
1925          */
1926         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1927                                      PDB_CHANGED);
1928
1929         if (!NT_STATUS_IS_OK(ret)) {
1930                 return ret;
1931         }
1932
1933         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1934                   pdb_get_username(newpwd)));
1935         return NT_STATUS_OK;
1936 }
1937
1938 /***************************************************************************
1939  Renames a struct samu
1940  - The "rename user script" has full responsibility for changing everything
1941 ***************************************************************************/
1942
1943 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
1944                                      TALLOC_CTX *tmp_ctx,
1945                                      uint32_t group_rid,
1946                                      uint32_t member_rid);
1947
1948 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
1949                                                TALLOC_CTX *mem_ctx,
1950                                                struct samu *user,
1951                                                struct dom_sid **pp_sids,
1952                                                gid_t **pp_gids,
1953                                                uint32_t *p_num_groups);
1954
1955 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1956                                            struct samu *old_acct,
1957                                            const char *newname)
1958 {
1959         const char *oldname;
1960         int rc;
1961         char *rename_script = NULL;
1962         fstring oldname_lower, newname_lower;
1963
1964         if (!old_acct) {
1965                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1966                 return NT_STATUS_INVALID_PARAMETER;
1967         }
1968         if (!newname) {
1969                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1970                 return NT_STATUS_INVALID_PARAMETER;
1971         }
1972
1973         oldname = pdb_get_username(old_acct);
1974
1975         /* rename the posix user */
1976         rename_script = lp_rename_user_script(talloc_tos());
1977         if (rename_script == NULL) {
1978                 return NT_STATUS_NO_MEMORY;
1979         }
1980
1981         if (!(*rename_script)) {
1982                 TALLOC_FREE(rename_script);
1983                 return NT_STATUS_ACCESS_DENIED;
1984         }
1985
1986         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
1987                    oldname, newname));
1988
1989         /* We have to allow the account name to end with a '$'.
1990            Also, follow the semantics in _samr_create_user() and lower case the
1991            posix name but preserve the case in passdb */
1992
1993         fstrcpy( oldname_lower, oldname );
1994         if (!strlower_m( oldname_lower )) {
1995                 return NT_STATUS_INVALID_PARAMETER;
1996         }
1997         fstrcpy( newname_lower, newname );
1998         if (!strlower_m( newname_lower )) {
1999                 return NT_STATUS_INVALID_PARAMETER;
2000         }
2001
2002         rename_script = realloc_string_sub2(rename_script,
2003                                         "%unew",
2004                                         newname_lower,
2005                                         true,
2006                                         true);
2007         if (!rename_script) {
2008                 return NT_STATUS_NO_MEMORY;
2009         }
2010         rename_script = realloc_string_sub2(rename_script,
2011                                         "%uold",
2012                                         oldname_lower,
2013                                         true,
2014                                         true);
2015         rc = smbrun(rename_script, NULL, NULL);
2016
2017         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2018                           rename_script, rc));
2019
2020         TALLOC_FREE(rename_script);
2021
2022         if (rc == 0) {
2023                 smb_nscd_flush_user_cache();
2024         }
2025
2026         if (rc)
2027                 return NT_STATUS_UNSUCCESSFUL;
2028
2029         return NT_STATUS_OK;
2030 }
2031
2032 /**********************************************************************
2033  Add struct samu to LDAP.
2034 *********************************************************************/
2035
2036 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2037 {
2038         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2039         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2040         int rc;
2041         LDAPMessage     *result = NULL;
2042         LDAPMessage     *entry  = NULL;
2043         LDAPMod         **mods = NULL;
2044         int             ldap_op = LDAP_MOD_REPLACE;
2045         uint32_t                num_result;
2046         const char      **attr_list;
2047         char *escape_user = NULL;
2048         const char      *username = pdb_get_username(newpwd);
2049         const struct dom_sid    *sid = pdb_get_user_sid(newpwd);
2050         char *filter = NULL;
2051         char *dn = NULL;
2052         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2053         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2054
2055         if (!ctx) {
2056                 return NT_STATUS_NO_MEMORY;
2057         }
2058
2059         if (!username || !*username) {
2060                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2061                 status = NT_STATUS_INVALID_PARAMETER;
2062                 goto fn_exit;
2063         }
2064
2065         /* free this list after the second search or in case we exit on failure */
2066         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2067
2068         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2069
2070         if (rc != LDAP_SUCCESS) {
2071                 goto fn_exit;
2072         }
2073
2074         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2075                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2076                          username));
2077                 goto fn_exit;
2078         }
2079         ldap_msgfree(result);
2080         result = NULL;
2081
2082         if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2083                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2084                                                   sid, &result);
2085                 if (rc == LDAP_SUCCESS) {
2086                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2087                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2088                                          "already in the base, with samba "
2089                                          "attributes\n", sid_string_dbg(sid)));
2090                                 goto fn_exit;
2091                         }
2092                         ldap_msgfree(result);
2093                         result = NULL;
2094                 }
2095         }
2096
2097         /* does the entry already exist but without a samba attributes?
2098            we need to return the samba attributes here */
2099
2100         escape_user = escape_ldap_string(talloc_tos(), username);
2101         filter = talloc_strdup(attr_list, "(uid=%u)");
2102         if (!filter) {
2103                 status = NT_STATUS_NO_MEMORY;
2104                 goto fn_exit;
2105         }
2106         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2107         TALLOC_FREE(escape_user);
2108         if (!filter) {
2109                 status = NT_STATUS_NO_MEMORY;
2110                 goto fn_exit;
2111         }
2112
2113         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2114                                    filter, attr_list, &result);
2115         if ( rc != LDAP_SUCCESS ) {
2116                 goto fn_exit;
2117         }
2118
2119         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2120
2121         if (num_result > 1) {
2122                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2123                 goto fn_exit;
2124         }
2125
2126         /* Check if we need to update an existing entry */
2127         if (num_result == 1) {
2128                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2129                 ldap_op = LDAP_MOD_REPLACE;
2130                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2131                 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2132                 if (!dn) {
2133                         status = NT_STATUS_NO_MEMORY;
2134                         goto fn_exit;
2135                 }
2136
2137         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2138
2139                 /* There might be a SID for this account already - say an idmap entry */
2140
2141                 filter = talloc_asprintf(ctx,
2142                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2143                                  get_userattr_key2string(ldap_state->schema_ver,
2144                                          LDAP_ATTR_USER_SID),
2145                                  sid_string_talloc(ctx, sid),
2146                                  LDAP_OBJ_IDMAP_ENTRY,
2147                                  LDAP_OBJ_SID_ENTRY);
2148                 if (!filter) {
2149                         status = NT_STATUS_NO_MEMORY;
2150                         goto fn_exit;
2151                 }
2152
2153                 /* free old result before doing a new search */
2154                 if (result != NULL) {
2155                         ldap_msgfree(result);
2156                         result = NULL;
2157                 }
2158                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2159                                            filter, attr_list, &result);
2160
2161                 if ( rc != LDAP_SUCCESS ) {
2162                         goto fn_exit;
2163                 }
2164
2165                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2166
2167                 if (num_result > 1) {
2168                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2169                         goto fn_exit;
2170                 }
2171
2172                 /* Check if we need to update an existing entry */
2173                 if (num_result == 1) {
2174
2175                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2176                         ldap_op = LDAP_MOD_REPLACE;
2177                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2178                         dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2179                         if (!dn) {
2180                                 status = NT_STATUS_NO_MEMORY;
2181                                 goto fn_exit;
2182                         }
2183                 }
2184         }
2185
2186         if (num_result == 0) {
2187                 char *escape_username;
2188                 /* Check if we need to add an entry */
2189                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2190                 ldap_op = LDAP_MOD_ADD;
2191
2192                 escape_username = escape_rdn_val_string_alloc(username);
2193                 if (!escape_username) {
2194                         status = NT_STATUS_NO_MEMORY;
2195                         goto fn_exit;
2196                 }
2197
2198                 if (username[strlen(username)-1] == '$') {
2199                         dn = talloc_asprintf(ctx,
2200                                         "uid=%s,%s",
2201                                         escape_username,
2202                                         lp_ldap_machine_suffix(talloc_tos()));
2203                 } else {
2204                         dn = talloc_asprintf(ctx,
2205                                         "uid=%s,%s",
2206                                         escape_username,
2207                                         lp_ldap_user_suffix(talloc_tos()));
2208                 }
2209
2210                 SAFE_FREE(escape_username);
2211                 if (!dn) {
2212                         status = NT_STATUS_NO_MEMORY;
2213                         goto fn_exit;
2214                 }
2215         }
2216
2217         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2218                                 pdb_element_is_set_or_changed)) {
2219                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2220                 if (mods != NULL) {
2221                         ldap_mods_free(mods, true);
2222                 }
2223                 goto fn_exit;
2224         }
2225
2226         if (mods == NULL) {
2227                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2228                 goto fn_exit;
2229         }
2230         switch ( ldap_state->schema_ver ) {
2231                 case SCHEMAVER_SAMBASAMACCOUNT:
2232                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2233                         break;
2234                 default:
2235                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2236                         break;
2237         }
2238
2239         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2240         if (!NT_STATUS_IS_OK(ret)) {
2241                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2242                          pdb_get_username(newpwd),dn));
2243                 ldap_mods_free(mods, true);
2244                 goto fn_exit;
2245         }
2246
2247         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2248         ldap_mods_free(mods, true);
2249
2250         status = NT_STATUS_OK;
2251
2252   fn_exit:
2253
2254         TALLOC_FREE(ctx);
2255         if (result) {
2256                 ldap_msgfree(result);
2257         }
2258         return status;
2259 }
2260
2261 /**********************************************************************
2262  *********************************************************************/
2263
2264 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2265                                      const char *filter,
2266                                      LDAPMessage ** result)
2267 {
2268         int scope = LDAP_SCOPE_SUBTREE;
2269         int rc;
2270         const char **attr_list;
2271
2272         attr_list = get_attr_list(NULL, groupmap_attr_list);
2273         rc = smbldap_search(ldap_state->smbldap_state,
2274                             lp_ldap_suffix (talloc_tos()), scope,
2275                             filter, attr_list, 0, result);
2276         TALLOC_FREE(attr_list);
2277
2278         return rc;
2279 }
2280
2281 /**********************************************************************
2282  *********************************************************************/
2283
2284 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2285                                  GROUP_MAP *map, LDAPMessage *entry)
2286 {
2287         char *temp = NULL;
2288         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2289
2290         if (ldap_state == NULL || map == NULL || entry == NULL ||
2291                         ldap_state->smbldap_state->ldap_struct == NULL) {
2292                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2293                 TALLOC_FREE(ctx);
2294                 return false;
2295         }
2296
2297         temp = smbldap_talloc_single_attribute(
2298                         ldap_state->smbldap_state->ldap_struct,
2299                         entry,
2300                         get_attr_key2string(groupmap_attr_list,
2301                                 LDAP_ATTR_GIDNUMBER),
2302                         ctx);
2303         if (!temp) {
2304                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2305                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2306                 TALLOC_FREE(ctx);
2307                 return false;
2308         }
2309         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2310
2311         map->gid = (gid_t)atol(temp);
2312
2313         TALLOC_FREE(temp);
2314         temp = smbldap_talloc_single_attribute(
2315                         ldap_state->smbldap_state->ldap_struct,
2316                         entry,
2317                         get_attr_key2string(groupmap_attr_list,
2318                                 LDAP_ATTR_GROUP_SID),
2319                         ctx);
2320         if (!temp) {
2321                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2322                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2323                 TALLOC_FREE(ctx);
2324                 return false;
2325         }
2326
2327         if (!string_to_sid(&map->sid, temp)) {
2328                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2329                 TALLOC_FREE(ctx);
2330                 return false;
2331         }
2332
2333         TALLOC_FREE(temp);
2334         temp = smbldap_talloc_single_attribute(
2335                         ldap_state->smbldap_state->ldap_struct,
2336                         entry,
2337                         get_attr_key2string(groupmap_attr_list,
2338                                 LDAP_ATTR_GROUP_TYPE),
2339                         ctx);
2340         if (!temp) {
2341                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2342                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2343                 TALLOC_FREE(ctx);
2344                 return false;
2345         }
2346         map->sid_name_use = (enum lsa_SidType)atol(temp);
2347
2348         if ((map->sid_name_use < SID_NAME_USER) ||
2349                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2350                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2351                 TALLOC_FREE(ctx);
2352                 return false;
2353         }
2354
2355         TALLOC_FREE(temp);
2356         temp = smbldap_talloc_single_attribute(
2357                         ldap_state->smbldap_state->ldap_struct,
2358                         entry,
2359                         get_attr_key2string(groupmap_attr_list,
2360                                 LDAP_ATTR_DISPLAY_NAME),
2361                         ctx);
2362         if (!temp) {
2363                 temp = smbldap_talloc_single_attribute(
2364                                 ldap_state->smbldap_state->ldap_struct,
2365                                 entry,
2366                                 get_attr_key2string(groupmap_attr_list,
2367                                         LDAP_ATTR_CN),
2368                                 ctx);
2369                 if (!temp) {
2370                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2371 for gidNumber(%lu)\n",(unsigned long)map->gid));
2372                         TALLOC_FREE(ctx);
2373                         return false;
2374                 }
2375         }
2376         map->nt_name = talloc_strdup(map, temp);
2377         if (!map->nt_name) {
2378                 TALLOC_FREE(ctx);
2379                 return false;
2380         }
2381
2382         TALLOC_FREE(temp);
2383         temp = smbldap_talloc_single_attribute(
2384                         ldap_state->smbldap_state->ldap_struct,
2385                         entry,
2386                         get_attr_key2string(groupmap_attr_list,
2387                                 LDAP_ATTR_DESC),
2388                         ctx);
2389         if (!temp) {
2390                 temp = talloc_strdup(ctx, "");
2391                 if (!temp) {
2392                         TALLOC_FREE(ctx);
2393                         return false;
2394                 }
2395         }
2396         map->comment = talloc_strdup(map, temp);
2397         if (!map->comment) {
2398                 TALLOC_FREE(ctx);
2399                 return false;
2400         }
2401
2402         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2403                 struct unixid id;
2404                 id.id = map->gid;
2405                 id.type = ID_TYPE_GID;
2406
2407                 idmap_cache_set_sid2unixid(&map->sid, &id);
2408         }
2409
2410         TALLOC_FREE(ctx);
2411         return true;
2412 }
2413
2414 /**********************************************************************
2415  *********************************************************************/
2416
2417 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2418                                  const char *filter,
2419                                  GROUP_MAP *map)
2420 {
2421         struct ldapsam_privates *ldap_state =
2422                 (struct ldapsam_privates *)methods->private_data;
2423         LDAPMessage *result = NULL;
2424         LDAPMessage *entry = NULL;
2425         int count;
2426
2427         if (ldapsam_search_one_group(ldap_state, filter, &result)
2428             != LDAP_SUCCESS) {
2429                 return NT_STATUS_NO_SUCH_GROUP;
2430         }
2431
2432         count = ldap_count_entries(priv2ld(ldap_state), result);
2433
2434         if (count < 1) {
2435                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2436                           "%s\n", filter));
2437                 ldap_msgfree(result);
2438                 return NT_STATUS_NO_SUCH_GROUP;
2439         }
2440
2441         if (count > 1) {
2442                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2443                           "count=%d\n", filter, count));
2444                 ldap_msgfree(result);
2445                 return NT_STATUS_NO_SUCH_GROUP;
2446         }
2447
2448         entry = ldap_first_entry(priv2ld(ldap_state), result);
2449
2450         if (!entry) {
2451                 ldap_msgfree(result);
2452                 return NT_STATUS_UNSUCCESSFUL;
2453         }
2454
2455         if (!init_group_from_ldap(ldap_state, map, entry)) {
2456                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2457                           "group filter %s\n", filter));
2458                 ldap_msgfree(result);
2459                 return NT_STATUS_NO_SUCH_GROUP;
2460         }
2461
2462         ldap_msgfree(result);
2463         return NT_STATUS_OK;
2464 }
2465
2466 /**********************************************************************
2467  *********************************************************************/
2468
2469 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2470                                  struct dom_sid sid)
2471 {
2472         char *filter = NULL;
2473         NTSTATUS status;
2474         fstring tmp;
2475
2476         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2477                 LDAP_OBJ_GROUPMAP,
2478                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2479                 sid_to_fstring(tmp, &sid)) < 0) {
2480                 return NT_STATUS_NO_MEMORY;
2481         }
2482
2483         status = ldapsam_getgroup(methods, filter, map);
2484         SAFE_FREE(filter);
2485         return status;
2486 }
2487
2488 /**********************************************************************
2489  *********************************************************************/
2490
2491 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2492                                  gid_t gid)
2493 {
2494         char *filter = NULL;
2495         NTSTATUS status;
2496
2497         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2498                 LDAP_OBJ_GROUPMAP,
2499                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2500                 (unsigned long)gid) < 0) {
2501                 return NT_STATUS_NO_MEMORY;
2502         }
2503
2504         status = ldapsam_getgroup(methods, filter, map);
2505         SAFE_FREE(filter);
2506         return status;
2507 }
2508
2509 /**********************************************************************
2510  *********************************************************************/
2511
2512 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2513                                  const char *name)
2514 {
2515         char *filter = NULL;
2516         char *escape_name = escape_ldap_string(talloc_tos(), name);
2517         NTSTATUS status;
2518
2519         if (!escape_name) {
2520                 return NT_STATUS_NO_MEMORY;
2521         }
2522
2523         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2524                 LDAP_OBJ_GROUPMAP,
2525                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2526                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2527                 escape_name) < 0) {
2528                 TALLOC_FREE(escape_name);
2529                 return NT_STATUS_NO_MEMORY;
2530         }
2531
2532         TALLOC_FREE(escape_name);
2533         status = ldapsam_getgroup(methods, filter, map);
2534         SAFE_FREE(filter);
2535         return status;
2536 }
2537
2538 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2539                                            LDAPMessage *entry,
2540                                            const struct dom_sid *domain_sid,
2541                                            uint32_t *rid)
2542 {
2543         fstring str;
2544         struct dom_sid sid;
2545
2546         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2547                                           str, sizeof(str)-1)) {
2548                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2549                 return False;
2550         }
2551
2552         if (!string_to_sid(&sid, str)) {
2553                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2554                 return False;
2555         }
2556
2557         if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2558                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2559                            str, sid_string_dbg(domain_sid)));
2560                 return False;
2561         }
2562
2563         if (!sid_peek_rid(&sid, rid)) {
2564                 DEBUG(10, ("Could not peek into RID\n"));
2565                 return False;
2566         }
2567
2568         return True;
2569 }
2570
2571 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2572                                            TALLOC_CTX *mem_ctx,
2573                                            const struct dom_sid *group,
2574                                            uint32_t **pp_member_rids,
2575                                            size_t *p_num_members)
2576 {
2577         struct ldapsam_privates *ldap_state =
2578                 (struct ldapsam_privates *)methods->private_data;
2579         struct smbldap_state *conn = ldap_state->smbldap_state;
2580         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2581         const char *sid_attrs[] = { "sambaSID", NULL };
2582         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2583         LDAPMessage *result = NULL;
2584         LDAPMessage *entry;
2585         char *filter;
2586         char **values = NULL;
2587         char **memberuid;
2588         char *gidstr;
2589         int rc, count;
2590
2591         *pp_member_rids = NULL;
2592         *p_num_members = 0;
2593
2594         filter = talloc_asprintf(mem_ctx,
2595                                  "(&(objectClass=%s)"
2596                                  "(objectClass=%s)"
2597                                  "(sambaSID=%s))",
2598                                  LDAP_OBJ_POSIXGROUP,
2599                                  LDAP_OBJ_GROUPMAP,
2600                                  sid_string_talloc(mem_ctx, group));
2601         if (filter == NULL) {
2602                 ret = NT_STATUS_NO_MEMORY;
2603                 goto done;
2604         }
2605
2606         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2607                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2608                             &result);
2609
2610         if (rc != LDAP_SUCCESS)
2611                 goto done;
2612
2613         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2614
2615         count = ldap_count_entries(conn->ldap_struct, result);
2616
2617         if (count > 1) {
2618                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2619                           sid_string_dbg(group)));
2620                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2621                 goto done;
2622         }
2623
2624         if (count == 0) {
2625                 ret = NT_STATUS_NO_SUCH_GROUP;
2626                 goto done;
2627         }
2628
2629         entry = ldap_first_entry(conn->ldap_struct, result);
2630         if (entry == NULL)
2631                 goto done;
2632
2633         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2634         if (!gidstr) {
2635                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2636                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2637                 goto done;
2638         }
2639
2640         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2641
2642         if ((values != NULL) && (values[0] != NULL)) {
2643
2644                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2645                 if (filter == NULL) {
2646                         ret = NT_STATUS_NO_MEMORY;
2647                         goto done;
2648                 }
2649
2650                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2651                         char *escape_memberuid;
2652
2653                         escape_memberuid = escape_ldap_string(talloc_tos(),
2654                                                               *memberuid);
2655                         if (escape_memberuid == NULL) {
2656                                 ret = NT_STATUS_NO_MEMORY;
2657                                 goto done;
2658                         }
2659
2660                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2661                         TALLOC_FREE(escape_memberuid);
2662                         if (filter == NULL) {
2663                                 ret = NT_STATUS_NO_MEMORY;
2664                                 goto done;
2665                         }
2666                 }
2667
2668                 filter = talloc_asprintf_append_buffer(filter, "))");
2669                 if (filter == NULL) {
2670                         ret = NT_STATUS_NO_MEMORY;
2671                         goto done;
2672                 }
2673
2674                 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2675                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2676                                     &result);
2677
2678                 if (rc != LDAP_SUCCESS)
2679                         goto done;
2680
2681                 count = ldap_count_entries(conn->ldap_struct, result);
2682                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2683
2684                 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2685
2686                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2687                      entry != NULL;
2688                      entry = ldap_next_entry(conn->ldap_struct, entry))
2689                 {
2690                         char *sidstr;
2691                         struct dom_sid sid;
2692                         uint32_t rid;
2693
2694                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2695                                                                  entry, "sambaSID",
2696                                                                  mem_ctx);
2697                         if (!sidstr) {
2698                                 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2699                                           "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2700                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2701                                 goto done;
2702                         }
2703
2704                         if (!string_to_sid(&sid, sidstr))
2705                                 goto done;
2706
2707                         if (!sid_check_is_in_our_sam(&sid)) {
2708                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2709                                           "in our domain\n"));
2710                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2711                                 goto done;
2712                         }
2713
2714                         sid_peek_rid(&sid, &rid);
2715
2716                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2717                                                 p_num_members)) {
2718                                 ret = NT_STATUS_NO_MEMORY;
2719                                 goto done;
2720                         }
2721                 }
2722         }
2723
2724         filter = talloc_asprintf(mem_ctx,
2725                                  "(&(objectClass=%s)"
2726                                  "(gidNumber=%s))",
2727                                  LDAP_OBJ_SAMBASAMACCOUNT,
2728                                  gidstr);
2729
2730         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2731                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2732                             &result);
2733
2734         if (rc != LDAP_SUCCESS)
2735                 goto done;
2736
2737         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2738
2739         for (entry = ldap_first_entry(conn->ldap_struct, result);
2740              entry != NULL;
2741              entry = ldap_next_entry(conn->ldap_struct, entry))
2742         {
2743                 uint32_t rid;
2744
2745                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2746                                                     entry,
2747                                                     get_global_sam_sid(),
2748                                                     &rid)) {
2749                         DEBUG(0, ("Severe DB error, %s can't miss the samba SID"                                                                "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2750                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2751                         goto done;
2752                 }
2753
2754                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2755                                         p_num_members)) {
2756                         ret = NT_STATUS_NO_MEMORY;
2757                         goto done;
2758                 }
2759         }
2760
2761         ret = NT_STATUS_OK;
2762
2763  done:
2764
2765         if (values)
2766                 ldap_value_free(values);
2767
2768         return ret;
2769 }
2770
2771 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2772                                                TALLOC_CTX *mem_ctx,
2773                                                struct samu *user,
2774                                                struct dom_sid **pp_sids,
2775                                                gid_t **pp_gids,
2776                                                uint32_t *p_num_groups)
2777 {
2778         struct ldapsam_privates *ldap_state =
2779                 (struct ldapsam_privates *)methods->private_data;
2780         struct smbldap_state *conn = ldap_state->smbldap_state;
2781         char *filter;
2782         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2783         char *escape_name;
2784         int rc, count;
2785         LDAPMessage *result = NULL;
2786         LDAPMessage *entry;
2787         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2788         uint32_t num_sids;
2789         uint32_t num_gids;
2790         char *gidstr;
2791         gid_t primary_gid = -1;
2792
2793         *pp_sids = NULL;
2794         num_sids = 0;
2795
2796         if (pdb_get_username(user) == NULL) {
2797                 return NT_STATUS_INVALID_PARAMETER;
2798         }
2799
2800         escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2801         if (escape_name == NULL)
2802                 return NT_STATUS_NO_MEMORY;
2803
2804         if (user->unix_pw) {
2805                 primary_gid = user->unix_pw->pw_gid;
2806         } else {
2807                 /* retrieve the users primary gid */
2808                 filter = talloc_asprintf(mem_ctx,
2809                                          "(&(objectClass=%s)(uid=%s))",
2810                                          LDAP_OBJ_SAMBASAMACCOUNT,
2811                                          escape_name);
2812                 if (filter == NULL) {
2813                         ret = NT_STATUS_NO_MEMORY;
2814                         goto done;
2815                 }
2816
2817                 rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2818                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2819
2820                 if (rc != LDAP_SUCCESS)
2821                         goto done;
2822
2823                 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2824
2825                 count = ldap_count_entries(priv2ld(ldap_state), result);
2826
2827                 switch (count) {
2828                 case 0:
2829                         DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2830                         ret = NT_STATUS_NO_SUCH_USER;
2831                         goto done;
2832                 case 1:
2833                         entry = ldap_first_entry(priv2ld(ldap_state), result);
2834
2835                         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2836                         if (!gidstr) {
2837                                 DEBUG (1, ("Unable to find the member's gid!\n"));
2838                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2839                                 goto done;
2840                         }
2841                         primary_gid = strtoul(gidstr, NULL, 10);
2842                         break;
2843                 default:
2844                         DEBUG(1, ("found more than one account with the same user name ?!\n"));
2845                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2846                         goto done;
2847                 }
2848         }
2849
2850         filter = talloc_asprintf(mem_ctx,
2851                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2852                                  LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2853         if (filter == NULL) {
2854                 ret = NT_STATUS_NO_MEMORY;
2855                 goto done;
2856         }
2857
2858         rc = smbldap_search(conn, lp_ldap_suffix(talloc_tos()),
2859                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2860
2861         if (rc != LDAP_SUCCESS)
2862                 goto done;
2863
2864         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
2865
2866         num_gids = 0;
2867         *pp_gids = NULL;
2868
2869         num_sids = 0;
2870         *pp_sids = NULL;
2871
2872         /* We need to add the primary group as the first gid/sid */
2873
2874         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2875                 ret = NT_STATUS_NO_MEMORY;
2876                 goto done;
2877         }
2878
2879         /* This sid will be replaced later */
2880
2881         ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2882                                       &num_sids);
2883         if (!NT_STATUS_IS_OK(ret)) {
2884                 goto done;
2885         }
2886
2887         for (entry = ldap_first_entry(conn->ldap_struct, result);
2888              entry != NULL;
2889              entry = ldap_next_entry(conn->ldap_struct, entry))
2890         {
2891                 fstring str;
2892                 struct dom_sid sid;
2893                 gid_t gid;
2894                 char *end;
2895
2896                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2897                                                   entry, "sambaSID",
2898                                                   str, sizeof(str)-1))
2899                         continue;
2900
2901                 if (!string_to_sid(&sid, str))
2902                         goto done;
2903
2904                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2905                                                   entry, "gidNumber",
2906                                                   str, sizeof(str)-1))
2907                         continue;
2908
2909                 gid = strtoul(str, &end, 10);
2910
2911                 if (PTR_DIFF(end, str) != strlen(str))
2912                         goto done;
2913
2914                 if (gid == primary_gid) {
2915                         sid_copy(&(*pp_sids)[0], &sid);
2916                 } else {
2917                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2918                                                 &num_gids)) {
2919                                 ret = NT_STATUS_NO_MEMORY;
2920                                 goto done;
2921                         }
2922                         ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2923                                                       &num_sids);
2924                         if (!NT_STATUS_IS_OK(ret)) {
2925                                 goto done;
2926                         }
2927                 }
2928         }
2929
2930         if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2931                 DEBUG(3, ("primary group of [%s] not found\n",
2932                           pdb_get_username(user)));
2933                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2934                 goto done;
2935         }
2936
2937         *p_num_groups = num_sids;
2938
2939         ret = NT_STATUS_OK;
2940
2941  done:
2942
2943         TALLOC_FREE(escape_name);
2944         return ret;
2945 }
2946
2947 /**********************************************************************
2948  * Augment a posixGroup object with a sambaGroupMapping domgroup
2949  *********************************************************************/
2950
2951 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2952                                        struct ldapsam_privates *ldap_state,
2953                                        GROUP_MAP *map)
2954 {
2955         const char *filter, *dn;
2956         LDAPMessage *msg, *entry;
2957         LDAPMod **mods;
2958         int rc;
2959
2960         filter = talloc_asprintf(mem_ctx,
2961                                  "(&(objectClass=%s)(gidNumber=%u))",
2962                                  LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2963         if (filter == NULL) {
2964                 return NT_STATUS_NO_MEMORY;
2965         }
2966
2967         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2968                                    get_attr_list(mem_ctx, groupmap_attr_list),
2969                                    &msg);
2970         smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
2971
2972         if ((rc != LDAP_SUCCESS) ||
2973             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2974             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2975                 return NT_STATUS_NO_SUCH_GROUP;
2976         }
2977
2978         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2979         if (dn == NULL) {
2980                 return NT_STATUS_NO_MEMORY;
2981         }
2982
2983         mods = NULL;
2984         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2985                         LDAP_OBJ_GROUPMAP);
2986         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2987                          sid_string_talloc(mem_ctx, &map->sid));
2988         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2989                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2990         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2991                          map->nt_name);
2992         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2993                          map->comment);
2994         smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
2995
2996         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2997         if (rc != LDAP_SUCCESS) {
2998                 return NT_STATUS_ACCESS_DENIED;
2999         }
3000
3001         return NT_STATUS_OK;
3002 }
3003
3004 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3005                                                 GROUP_MAP *map)
3006 {
3007         struct ldapsam_privates *ldap_state =
3008                 (struct ldapsam_privates *)methods->private_data;
3009         LDAPMessage *msg = NULL;
3010         LDAPMod **mods = NULL;
3011         const char *attrs[] = { NULL };
3012         char *filter;
3013
3014         char *dn;
3015         TALLOC_CTX *mem_ctx;
3016         NTSTATUS result;
3017
3018         struct dom_sid sid;
3019         struct unixid id;
3020
3021         int rc;
3022
3023         mem_ctx = talloc_new(NULL);
3024         if (mem_ctx == NULL) {
3025                 DEBUG(0, ("talloc_new failed\n"));
3026                 return NT_STATUS_NO_MEMORY;
3027         }
3028
3029         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3030                                  sid_string_talloc(mem_ctx, &map->sid));
3031         if (filter == NULL) {
3032                 result = NT_STATUS_NO_MEMORY;
3033                 goto done;
3034         }
3035
3036         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3037                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3038         smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3039
3040         if ((rc == LDAP_SUCCESS) &&
3041             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3042
3043                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3044                           "group mapping entry\n", sid_string_dbg(&map->sid)));
3045                 result = NT_STATUS_GROUP_EXISTS;
3046                 goto done;
3047         }
3048
3049         switch (map->sid_name_use) {
3050
3051         case SID_NAME_DOM_GRP:
3052                 /* To map a domain group we need to have a posix group
3053                    to attach to. */
3054                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3055                 goto done;
3056                 break;
3057
3058         case SID_NAME_ALIAS:
3059                 if (!sid_check_is_in_our_sam(&map->sid) 
3060                         && !sid_check_is_in_builtin(&map->sid) ) 
3061                 {
3062                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3063                                   sid_string_dbg(&map->sid)));
3064                         result = NT_STATUS_INVALID_PARAMETER;
3065                         goto done;
3066                 }
3067                 break;
3068
3069         default:
3070                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3071                           sid_type_lookup(map->sid_name_use)));
3072                 result = NT_STATUS_INVALID_PARAMETER;
3073                 goto done;
3074         }
3075
3076         /* Domain groups have been mapped in a separate routine, we have to
3077          * create an alias now */
3078
3079         if (map->gid == -1) {
3080                 DEBUG(10, ("Refusing to map gid==-1\n"));
3081                 result = NT_STATUS_INVALID_PARAMETER;
3082                 goto done;
3083         }
3084
3085         id.id = map->gid;
3086         id.type = ID_TYPE_GID;
3087
3088         if (pdb_id_to_sid(&id, &sid)) {
3089                 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3090                           "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3091                 result = NT_STATUS_GROUP_EXISTS;
3092                 goto done;
3093         }
3094
3095         /* Ok, enough checks done. It's still racy to go ahead now, but that's
3096          * the best we can get out of LDAP. */
3097
3098         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3099                              sid_string_talloc(mem_ctx, &map->sid),
3100                              lp_ldap_group_suffix(talloc_tos()));
3101         if (dn == NULL) {
3102                 result = NT_STATUS_NO_MEMORY;
3103                 goto done;
3104         }
3105
3106         mods = NULL;
3107
3108         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3109                          LDAP_OBJ_SID_ENTRY);
3110         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3111                          LDAP_OBJ_GROUPMAP);
3112         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3113                          sid_string_talloc(mem_ctx, &map->sid));
3114         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3115                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3116         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3117                          map->nt_name);
3118         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3119                          map->comment);
3120         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3121                          talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3122         smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3123
3124         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3125
3126         result = (rc == LDAP_SUCCESS) ?
3127                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3128
3129  done:
3130         TALLOC_FREE(mem_ctx);
3131         return result;
3132 }
3133
3134 /**********************************************************************
3135  * Update a group mapping entry. We're quite strict about what can be changed:
3136  * Only the description and displayname may be changed. It simply does not
3137  * make any sense to change the SID, gid or the type in a mapping.
3138  *********************************************************************/
3139
3140 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3141                                                    GROUP_MAP *map)
3142 {
3143         struct ldapsam_privates *ldap_state =
3144                 (struct ldapsam_privates *)methods->private_data;
3145         int rc;
3146         const char *filter, *dn;
3147         LDAPMessage *msg = NULL;
3148         LDAPMessage *entry = NULL;
3149         LDAPMod **mods = NULL;
3150         TALLOC_CTX *mem_ctx;
3151         NTSTATUS result;
3152
3153         mem_ctx = talloc_new(NULL);
3154         if (mem_ctx == NULL) {
3155                 DEBUG(0, ("talloc_new failed\n"));
3156                 return NT_STATUS_NO_MEMORY;
3157         }
3158
3159         /* Make 100% sure that sid, gid and type are not changed by looking up
3160          * exactly the values we're given in LDAP. */
3161
3162         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3163                                  "(sambaSid=%s)(gidNumber=%u)"
3164                                  "(sambaGroupType=%d))",
3165                                  LDAP_OBJ_GROUPMAP,
3166                                  sid_string_talloc(mem_ctx, &map->sid),
3167                                  (unsigned int)map->gid, map->sid_name_use);
3168         if (filter == NULL) {
3169                 result = NT_STATUS_NO_MEMORY;
3170                 goto done;
3171         }
3172
3173         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3174                                    get_attr_list(mem_ctx, groupmap_attr_list),
3175                                    &msg);
3176         smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3177
3178         if ((rc != LDAP_SUCCESS) ||
3179             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3180             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3181                 result = NT_STATUS_NO_SUCH_GROUP;
3182                 goto done;
3183         }
3184
3185         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3186
3187         if (dn == NULL) {
3188                 result = NT_STATUS_NO_MEMORY;
3189                 goto done;
3190         }
3191
3192         mods = NULL;
3193         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3194                          map->nt_name);
3195         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3196                          map->comment);
3197         smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
3198
3199         if (mods == NULL) {
3200                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3201                           "nothing to do\n"));
3202                 result = NT_STATUS_OK;
3203                 goto done;
3204         }
3205
3206         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3207
3208         if (rc != LDAP_SUCCESS) {
3209                 result = NT_STATUS_ACCESS_DENIED;
3210                 goto done;
3211         }
3212
3213         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3214                   "group %lu in LDAP\n", (unsigned long)map->gid));
3215
3216         result = NT_STATUS_OK;
3217
3218  done:
3219         TALLOC_FREE(mem_ctx);
3220         return result;
3221 }
3222
3223 /**********************************************************************
3224  *********************************************************************/
3225
3226 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3227                                                    struct dom_sid sid)
3228 {
3229         struct ldapsam_privates *priv =
3230                 (struct ldapsam_privates *)methods->private_data;
3231         LDAPMessage *msg, *entry;
3232         int rc;
3233         NTSTATUS result;
3234         TALLOC_CTX *mem_ctx;
3235         char *filter;
3236
3237         mem_ctx = talloc_new(NULL);
3238         if (mem_ctx == NULL) {
3239                 DEBUG(0, ("talloc_new failed\n"));
3240                 return NT_STATUS_NO_MEMORY;
3241         }
3242
3243         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3244                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3245                                  sid_string_talloc(mem_ctx, &sid));
3246         if (filter == NULL) {
3247                 result = NT_STATUS_NO_MEMORY;
3248                 goto done;
3249         }
3250         rc = smbldap_search_suffix(priv->smbldap_state, filter,
3251                                    get_attr_list(mem_ctx, groupmap_attr_list),
3252                                    &msg);
3253         smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
3254
3255         if ((rc != LDAP_SUCCESS) ||
3256             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3257             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3258                 result = NT_STATUS_NO_SUCH_GROUP;
3259                 goto done;
3260         }
3261
3262         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3263                                   get_attr_list(mem_ctx,
3264                                                 groupmap_attr_list_to_delete));
3265
3266         if ((rc == LDAP_NAMING_VIOLATION) ||
3267             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3268             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3269                 const char *attrs[] = { "sambaGroupType", "description",
3270                                         "displayName", "sambaSIDList",
3271                                         NULL };
3272
3273                 /* Second try. Don't delete the sambaSID attribute, this is
3274                    for "old" entries that are tacked on a winbind
3275                    sambaIdmapEntry. */
3276
3277                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3278                                           LDAP_OBJ_GROUPMAP, attrs);
3279         }
3280
3281         if ((rc == LDAP_NAMING_VIOLATION) ||
3282             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3283             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3284                 const char *attrs[] = { "sambaGroupType", "description",
3285                                         "displayName", "sambaSIDList",
3286                                         "gidNumber", NULL };
3287
3288                 /* Third try. This is a post-3.0.21 alias (containing only
3289                  * sambaSidEntry and sambaGroupMapping classes), we also have
3290                  * to delete the gidNumber attribute, only the sambaSidEntry
3291                  * remains */
3292
3293                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3294                                           LDAP_OBJ_GROUPMAP, attrs);
3295         }
3296
3297         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3298
3299  done:
3300         TALLOC_FREE(mem_ctx);
3301         return result;
3302  }
3303
3304 /**********************************************************************
3305  *********************************************************************/
3306
3307 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3308                                     bool update)
3309 {
3310         struct ldapsam_privates *ldap_state =
3311                 (struct ldapsam_privates *)my_methods->private_data;
3312         char *filter = NULL;
3313         int rc;
3314         const char **attr_list;
3315
3316         filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3317         if (!filter) {
3318                 return NT_STATUS_NO_MEMORY;
3319         }
3320         attr_list = get_attr_list( NULL, groupmap_attr_list );
3321         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3322                             LDAP_SCOPE_SUBTREE, filter,
3323                             attr_list, 0, &ldap_state->result);
3324         TALLOC_FREE(attr_list);
3325
3326         if (rc != LDAP_SUCCESS) {
3327                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3328                           ldap_err2string(rc)));
3329                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3330                           lp_ldap_suffix(talloc_tos()), filter));
3331                 ldap_msgfree(ldap_state->result);
3332                 ldap_state->result = NULL;
3333                 TALLOC_FREE(filter);
3334                 return NT_STATUS_UNSUCCESSFUL;
3335         }
3336
3337         TALLOC_FREE(filter);
3338
3339         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3340                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3341                                      ldap_state->result)));
3342
3343         ldap_state->entry =
3344                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3345                                  ldap_state->result);
3346         ldap_state->index = 0;
3347
3348         return NT_STATUS_OK;
3349 }
3350
3351 /**********************************************************************
3352  *********************************************************************/
3353
3354 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3355 {
3356         ldapsam_endsampwent(my_methods);
3357 }
3358
3359 /**********************************************************************
3360  *********************************************************************/
3361
3362 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3363                                     GROUP_MAP *map)
3364 {
3365         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3366         struct ldapsam_privates *ldap_state =
3367                 (struct ldapsam_privates *)my_methods->private_data;
3368         bool bret = False;
3369
3370         while (!bret) {
3371                 if (!ldap_state->entry)
3372                         return ret;
3373
3374                 ldap_state->index++;
3375                 bret = init_group_from_ldap(ldap_state, map,
3376                                             ldap_state->entry);
3377
3378                 ldap_state->entry =
3379                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3380                                         ldap_state->entry);     
3381         }
3382
3383         return NT_STATUS_OK;
3384 }
3385
3386 /**********************************************************************
3387  *********************************************************************/
3388
3389 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3390                                            const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3391                                            GROUP_MAP ***pp_rmap,
3392                                            size_t *p_num_entries,
3393                                            bool unix_only)
3394 {
3395         GROUP_MAP *map = NULL;
3396         size_t entries = 0;
3397
3398         *p_num_entries = 0;
3399         *pp_rmap = NULL;
3400
3401         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3402                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3403                           "passdb\n"));
3404                 return NT_STATUS_ACCESS_DENIED;
3405         }
3406
3407         while (true) {
3408
3409                 map = talloc_zero(NULL, GROUP_MAP);
3410                 if (!map) {
3411                         return NT_STATUS_NO_MEMORY;
3412                 }
3413
3414                 if (!NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, map))) {
3415                         TALLOC_FREE(map);
3416                         break;
3417                 }
3418
3419                 if (sid_name_use != SID_NAME_UNKNOWN &&
3420                     sid_name_use != map->sid_name_use) {
3421                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3422                                   "not of the requested type\n",
3423                                   map->nt_name));
3424                         continue;
3425                 }
3426                 if (unix_only == ENUM_ONLY_MAPPED && map->gid == -1) {
3427                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3428                                   "non mapped\n", map->nt_name));
3429                         continue;
3430                 }
3431
3432                 *pp_rmap = talloc_realloc(NULL, *pp_rmap,
3433                                                 GROUP_MAP *, entries + 1);
3434                 if (!(*pp_rmap)) {
3435                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3436                                  "enlarge group map!\n"));
3437                         return NT_STATUS_UNSUCCESSFUL;
3438                 }
3439
3440                 (*pp_rmap)[entries] = talloc_move((*pp_rmap), &map);
3441
3442                 entries += 1;
3443         }
3444
3445         ldapsam_endsamgrent(methods);
3446
3447         *p_num_entries = entries;
3448
3449         return NT_STATUS_OK;
3450 }
3451
3452 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3453                                         const struct dom_sid *alias,
3454                                         const struct dom_sid *member,
3455                                         int modop)
3456 {
3457         struct ldapsam_privates *ldap_state =
3458                 (struct ldapsam_privates *)methods->private_data;
3459         char *dn = NULL;
3460         LDAPMessage *result = NULL;
3461         LDAPMessage *entry = NULL;
3462         int count;
3463         LDAPMod **mods = NULL;
3464         int rc;
3465         enum lsa_SidType type = SID_NAME_USE_NONE;
3466         fstring tmp;
3467
3468         char *filter = NULL;
3469
3470         if (sid_check_is_in_builtin(alias)) {
3471                 type = SID_NAME_ALIAS;
3472         }
3473
3474         if (sid_check_is_in_our_sam(alias)) {
3475                 type = SID_NAME_ALIAS;
3476         }
3477
3478         if (type == SID_NAME_USE_NONE) {
3479                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3480                           sid_string_dbg(alias)));
3481                 return NT_STATUS_NO_SUCH_ALIAS;
3482         }
3483
3484         if (asprintf(&filter,
3485                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3486                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3487                      type) < 0) {
3488                 return NT_STATUS_NO_MEMORY;
3489         }
3490
3491         if (ldapsam_search_one_group(ldap_state, filter,
3492                                      &result) != LDAP_SUCCESS) {
3493                 SAFE_FREE(filter);
3494                 return NT_STATUS_NO_SUCH_ALIAS;
3495         }
3496
3497         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3498                                    result);
3499
3500         if (count < 1) {
3501                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3502                 ldap_msgfree(result);
3503                 SAFE_FREE(filter);
3504                 return NT_STATUS_NO_SUCH_ALIAS;
3505         }
3506
3507         if (count > 1) {
3508                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3509                           "filter %s: count=%d\n", filter, count));
3510                 ldap_msgfree(result);
3511                 SAFE_FREE(filter);
3512                 return NT_STATUS_NO_SUCH_ALIAS;
3513         }
3514
3515         SAFE_FREE(filter);
3516
3517         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3518                                  result);
3519
3520         if (!entry) {
3521                 ldap_msgfree(result);
3522                 return NT_STATUS_UNSUCCESSFUL;
3523         }
3524
3525         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3526         if (!dn) {
3527                 ldap_msgfree(result);
3528                 return NT_STATUS_UNSUCCESSFUL;
3529         }
3530
3531         smbldap_set_mod(&mods, modop,
3532                         get_attr_key2string(groupmap_attr_list,
3533                                             LDAP_ATTR_SID_LIST),
3534                         sid_to_fstring(tmp, member));
3535
3536         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3537
3538         ldap_mods_free(mods, True);
3539         ldap_msgfree(result);
3540         TALLOC_FREE(dn);
3541
3542         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3543                 return NT_STATUS_MEMBER_IN_ALIAS;
3544         }
3545
3546         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3547                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3548         }
3549
3550         if (rc != LDAP_SUCCESS) {
3551                 return NT_STATUS_UNSUCCESSFUL;
3552         }
3553
3554         return NT_STATUS_OK;
3555 }
3556
3557 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3558                                      const struct dom_sid *alias,
3559                                      const struct dom_sid *member)
3560 {
3561         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3562 }
3563
3564 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3565                                      const struct dom_sid *alias,
3566                                      const struct dom_sid *member)
3567 {
3568         return ldapsam_modify_aliasmem(methods, alias, member,
3569                                        LDAP_MOD_DELETE);
3570 }
3571
3572 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3573                                       const struct dom_sid *alias,
3574                                       TALLOC_CTX *mem_ctx,
3575                                       struct dom_sid **pp_members,
3576                                       size_t *p_num_members)
3577 {
3578         struct ldapsam_privates *ldap_state =
3579                 (struct ldapsam_privates *)methods->private_data;
3580         LDAPMessage *result = NULL;
3581         LDAPMessage *entry = NULL;
3582         int count;
3583         char **values = NULL;
3584         int i;
3585         char *filter = NULL;
3586         uint32_t num_members = 0;
3587         enum lsa_SidType type = SID_NAME_USE_NONE;
3588         fstring tmp;
3589
3590         *pp_members = NULL;
3591         *p_num_members = 0;
3592
3593         if (sid_check_is_in_builtin(alias)) {
3594                 type = SID_NAME_ALIAS;
3595         }
3596
3597         if (sid_check_is_in_our_sam(alias)) {
3598                 type = SID_NAME_ALIAS;
3599         }
3600
3601         if (type == SID_NAME_USE_NONE) {
3602                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3603                           sid_string_dbg(alias)));
3604                 return NT_STATUS_NO_SUCH_ALIAS;
3605         }
3606
3607         if (asprintf(&filter,
3608                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3609                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3610                      type) < 0) {
3611                 return NT_STATUS_NO_MEMORY;
3612         }
3613
3614         if (ldapsam_search_one_group(ldap_state, filter,
3615                                      &result) != LDAP_SUCCESS) {
3616                 SAFE_FREE(filter);
3617                 return NT_STATUS_NO_SUCH_ALIAS;
3618         }
3619
3620         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3621                                    result);
3622
3623         if (count < 1) {
3624                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3625                 ldap_msgfree(result);
3626                 SAFE_FREE(filter);
3627                 return NT_STATUS_NO_SUCH_ALIAS;
3628         }
3629
3630         if (count > 1) {
3631                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3632                           "filter %s: count=%d\n", filter, count));
3633                 ldap_msgfree(result);
3634                 SAFE_FREE(filter);
3635                 return NT_STATUS_NO_SUCH_ALIAS;
3636         }
3637
3638         SAFE_FREE(filter);
3639
3640         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3641                                  result);
3642
3643         if (!entry) {
3644                 ldap_msgfree(result);
3645                 return NT_STATUS_UNSUCCESSFUL;
3646         }
3647
3648         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3649                                  entry,
3650                                  get_attr_key2string(groupmap_attr_list,
3651                                                      LDAP_ATTR_SID_LIST));
3652
3653         if (values == NULL) {
3654                 ldap_msgfree(result);
3655                 return NT_STATUS_OK;
3656         }
3657
3658         count = ldap_count_values(values);
3659
3660         for (i=0; i<count; i++) {
3661                 struct dom_sid member;
3662                 NTSTATUS status;
3663
3664                 if (!string_to_sid(&member, values[i]))
3665                         continue;
3666
3667                 status = add_sid_to_array(mem_ctx, &member, pp_members,
3668                                           &num_members);
3669                 if (!NT_STATUS_IS_OK(status)) {
3670                         ldap_value_free(values);
3671                         ldap_msgfree(result);
3672                         return status;
3673                 }
3674         }
3675
3676         *p_num_members = num_members;
3677         ldap_value_free(values);
3678         ldap_msgfree(result);
3679
3680         return NT_STATUS_OK;
3681 }
3682
3683 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3684                                           TALLOC_CTX *mem_ctx,
3685                                           const struct dom_sid *domain_sid,
3686                                           const struct dom_sid *members,
3687                                           size_t num_members,
3688                                           uint32_t **pp_alias_rids,
3689                                           size_t *p_num_alias_rids)
3690 {
3691         struct ldapsam_privates *ldap_state =
3692                 (struct ldapsam_privates *)methods->private_data;
3693         LDAP *ldap_struct;
3694
3695         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3696
3697         LDAPMessage *result = NULL;
3698         LDAPMessage *entry = NULL;
3699         int i;
3700         int rc;
3701         char *filter;
3702         enum lsa_SidType type = SID_NAME_USE_NONE;
3703         bool is_builtin = false;
3704         bool sid_added = false;
3705
3706         *pp_alias_rids = NULL;
3707         *p_num_alias_rids = 0;
3708
3709         if (sid_check_is_builtin(domain_sid)) {
3710                 is_builtin = true;
3711                 type = SID_NAME_ALIAS;
3712         }
3713
3714         if (sid_check_is_our_sam(domain_sid)) {
3715                 type = SID_NAME_ALIAS;
3716         }
3717
3718         if (type == SID_NAME_USE_NONE) {
3719                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3720                           sid_string_dbg(domain_sid)));
3721                 return NT_STATUS_UNSUCCESSFUL;
3722         }
3723
3724         if (num_members == 0) {
3725                 return NT_STATUS_OK;
3726         }
3727
3728         filter = talloc_asprintf(mem_ctx,
3729                                  "(&(objectclass=%s)(sambaGroupType=%d)(|",
3730                                  LDAP_OBJ_GROUPMAP, type);
3731
3732         for (i=0; i<num_members; i++)
3733                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3734                                          filter,
3735                                          sid_string_talloc(mem_ctx,
3736                                                            &members[i]));
3737
3738         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3739
3740         if (filter == NULL) {
3741                 return NT_STATUS_NO_MEMORY;
3742         }
3743
3744         if (is_builtin &&
3745             ldap_state->search_cache.filter &&
3746             strcmp(ldap_state->search_cache.filter, filter) == 0) {
3747                 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3748                 result = ldap_state->search_cache.result;
3749                 ldap_state->search_cache.result = NULL;
3750         } else {
3751                 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(talloc_tos()),
3752                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3753                 if (rc != LDAP_SUCCESS) {
3754                         return NT_STATUS_UNSUCCESSFUL;
3755                 }
3756                 smbldap_talloc_autofree_ldapmsg(filter, result);
3757         }
3758
3759         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3760
3761         for (entry = ldap_first_entry(ldap_struct, result);
3762              entry != NULL;
3763              entry = ldap_next_entry(ldap_struct, entry))
3764         {
3765                 fstring sid_str;
3766                 struct dom_sid sid;
3767                 uint32_t rid;
3768
3769                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3770                                                   LDAP_ATTRIBUTE_SID,
3771                                                   sid_str,
3772                                                   sizeof(sid_str)-1))
3773                         continue;
3774
3775                 if (!string_to_sid(&sid, sid_str))
3776                         continue;
3777
3778                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3779                         continue;
3780
3781                 sid_added = true;
3782
3783                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3784                                         p_num_alias_rids)) {
3785                         return NT_STATUS_NO_MEMORY;
3786                 }
3787         }
3788
3789         if (!is_builtin && !sid_added) {
3790                 TALLOC_FREE(ldap_state->search_cache.filter);
3791                 /*
3792                  * Note: result is a talloc child of filter because of the
3793                  * smbldap_talloc_autofree_ldapmsg() usage
3794                  */
3795                 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3796                 ldap_state->search_cache.result = result;
3797         }
3798
3799         return NT_STATUS_OK;
3800 }
3801
3802 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3803                                                    enum pdb_policy_type type,
3804                                                    uint32_t value)
3805 {
3806         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3807         int rc;
3808         LDAPMod **mods = NULL;
3809         fstring value_string;
3810         const char *policy_attr = NULL;
3811
3812         struct ldapsam_privates *ldap_state =
3813                 (struct ldapsam_privates *)methods->private_data;
3814
3815         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3816
3817         if (!ldap_state->domain_dn) {
3818                 return NT_STATUS_INVALID_PARAMETER;
3819         }
3820
3821         policy_attr = get_account_policy_attr(type);
3822         if (policy_attr == NULL) {
3823                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3824                          "policy\n"));
3825                 return ntstatus;
3826         }
3827
3828         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3829
3830         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3831
3832         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3833                             mods);
3834
3835         ldap_mods_free(mods, True);
3836
3837         if (rc != LDAP_SUCCESS) {
3838                 return ntstatus;
3839         }
3840
3841         if (!cache_account_policy_set(type, value)) {
3842                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3843                          "update local tdb cache\n"));
3844                 return ntstatus;
3845         }
3846
3847         return NT_STATUS_OK;
3848 }
3849
3850 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3851                                            enum pdb_policy_type type,
3852                                            uint32_t value)
3853 {
3854         return ldapsam_set_account_policy_in_ldap(methods, type,
3855                                                   value);
3856 }
3857
3858 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3859                                                      enum pdb_policy_type type,
3860                                                      uint32_t *value)
3861 {
3862         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3863         LDAPMessage *result = NULL;
3864         LDAPMessage *entry = NULL;
3865         int count;
3866         int rc;
3867         char **vals = NULL;
3868         char *filter;
3869         const char *policy_attr = NULL;
3870
3871         struct ldapsam_privates *ldap_state =
3872                 (struct ldapsam_privates *)methods->private_data;
3873
3874         const char *attrs[2];
3875
3876         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3877
3878         if (!ldap_state->domain_dn) {
3879                 return NT_STATUS_INVALID_PARAMETER;
3880         }
3881
3882         policy_attr = get_account_policy_attr(type);
3883         if (!policy_attr) {
3884                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3885                          "policy index: %d\n", type));
3886                 return ntstatus;
3887         }
3888
3889         attrs[0] = policy_attr;
3890         attrs[1] = NULL;
3891
3892         filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3893         if (filter == NULL) {
3894                 return NT_STATUS_NO_MEMORY;
3895         }
3896         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3897                             LDAP_SCOPE_BASE, filter, attrs, 0,
3898                             &result);
3899         TALLOC_FREE(filter);
3900         if (rc != LDAP_SUCCESS) {
3901                 return ntstatus;
3902         }
3903
3904         count = ldap_count_entries(priv2ld(ldap_state), result);
3905         if (count < 1) {
3906                 goto out;
3907         }
3908
3909         entry = ldap_first_entry(priv2ld(ldap_state), result);
3910         if (entry == NULL) {
3911                 goto out;
3912         }
3913
3914         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3915         if (vals == NULL) {
3916                 goto out;
3917         }
3918
3919         *value = (uint32_t)atol(vals[0]);
3920
3921         ntstatus = NT_STATUS_OK;
3922
3923 out:
3924         if (vals)
3925                 ldap_value_free(vals);
3926         ldap_msgfree(result);
3927
3928         return ntstatus;
3929 }
3930
3931 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3932
3933    - if user hasn't decided to use account policies inside LDAP just reuse the
3934      old tdb values
3935
3936    - if there is a valid cache entry, return that
3937    - if there is an LDAP entry, update cache and return 
3938    - otherwise set to default, update cache and return
3939
3940    Guenther
3941 */
3942 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3943                                            enum pdb_policy_type type,
3944                                            uint32_t *value)
3945 {
3946         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3947
3948         if (cache_account_policy_get(type, value)) {
3949                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3950                           "cache\n"));
3951                 return NT_STATUS_OK;
3952         }
3953
3954         ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3955                                                         value);
3956         if (NT_STATUS_IS_OK(ntstatus)) {
3957                 goto update_cache;
3958         }
3959
3960         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3961                   "ldap\n"));
3962
3963 #if 0
3964         /* should we automagically migrate old tdb value here ? */
3965         if (account_policy_get(type, value))
3966                 goto update_ldap;
3967
3968         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3969                   "default\n", type));
3970 #endif
3971
3972         if (!account_policy_get_default(type, value)) {
3973                 return ntstatus;
3974         }
3975
3976 /* update_ldap: */
3977
3978         ntstatus = ldapsam_set_account_policy(methods, type, *value);
3979         if (!NT_STATUS_IS_OK(ntstatus)) {
3980                 return ntstatus;
3981         }
3982
3983  update_cache:
3984
3985         if (!cache_account_policy_set(type, *value)) {
3986                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3987                          "tdb as a cache\n"));
3988                 return NT_STATUS_UNSUCCESSFUL;
3989         }
3990
3991         return NT_STATUS_OK;
3992 }
3993
3994 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3995                                     const struct dom_sid *domain_sid,
3996                                     int num_rids,
3997                                     uint32_t *rids,
3998                                     const char **names,
3999                                     enum lsa_SidType *attrs)
4000 {
4001         struct ldapsam_privates *ldap_state =
4002                 (struct ldapsam_privates *)methods->private_data;
4003         LDAPMessage *msg = NULL;
4004         LDAPMessage *entry;
4005         char *allsids = NULL;
4006         int i, rc, num_mapped;
4007         NTSTATUS result = NT_STATUS_NO_MEMORY;
4008         TALLOC_CTX *mem_ctx;
4009         LDAP *ld;
4010         bool is_builtin;
4011
4012         mem_ctx = talloc_new(NULL);
4013         if (mem_ctx == NULL) {
4014                 DEBUG(0, ("talloc_new failed\n"));
4015                 goto done;
4016         }
4017
4018         if (!sid_check_is_builtin(domain_sid) &&
4019             !sid_check_is_our_sam(domain_sid)) {
4020                 result = NT_STATUS_INVALID_PARAMETER;
4021                 goto done;
4022         }
4023
4024         if (num_rids == 0) {
4025                 result = NT_STATUS_NONE_MAPPED;
4026                 goto done;
4027         }
4028
4029         for (i=0; i<num_rids; i++)
4030                 attrs[i] = SID_NAME_UNKNOWN;
4031
4032         allsids = talloc_strdup(mem_ctx, "");
4033         if (allsids == NULL) {
4034                 goto done;
4035         }
4036
4037         for (i=0; i<num_rids; i++) {
4038                 struct dom_sid sid;
4039                 sid_compose(&sid, domain_sid, rids[i]);
4040                 allsids = talloc_asprintf_append_buffer(
4041                         allsids, "(sambaSid=%s)",
4042                         sid_string_talloc(mem_ctx, &sid));
4043                 if (allsids == NULL) {
4044                         goto done;
4045                 }
4046         }
4047
4048         /* First look for users */
4049
4050         {
4051                 char *filter;
4052                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4053
4054                 filter = talloc_asprintf(
4055                         mem_ctx, ("(&(objectClass=%s)(|%s))"),
4056                         LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4057
4058                 if (filter == NULL) {
4059                         goto done;
4060                 }
4061
4062                 rc = smbldap_search(ldap_state->smbldap_state,
4063                                     lp_ldap_user_suffix(talloc_tos()),
4064                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4065                                     &msg);
4066                 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4067         }
4068
4069         if (rc != LDAP_SUCCESS)
4070                 goto done;
4071
4072         ld = ldap_state->smbldap_state->ldap_struct;
4073         num_mapped = 0;
4074
4075         for (entry = ldap_first_entry(ld, msg);
4076              entry != NULL;
4077              entry = ldap_next_entry(ld, entry)) {
4078                 uint32_t rid;
4079                 int rid_index;
4080                 const char *name;
4081
4082                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4083                                                     &rid)) {
4084                         DEBUG(2, ("Could not find sid from ldap entry\n"));
4085                         continue;
4086                 }
4087
4088                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4089                                                        names);
4090                 if (name == NULL) {
4091                         DEBUG(2, ("Could not retrieve uid attribute\n"));
4092                         continue;
4093                 }
4094
4095                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4096                         if (rid == rids[rid_index])
4097                                 break;
4098                 }
4099
4100                 if (rid_index == num_rids) {
4101                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4102                         continue;
4103                 }
4104
4105                 attrs[rid_index] = SID_NAME_USER;
4106                 names[rid_index] = name;
4107                 num_mapped += 1;
4108         }
4109
4110         if (num_mapped == num_rids) {
4111                 /* No need to look for groups anymore -- we're done */
4112                 result = NT_STATUS_OK;
4113                 goto done;
4114         }
4115
4116         /* Same game for groups */
4117
4118         {
4119                 char *filter;
4120                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4121                                              "sambaGroupType", NULL };
4122
4123                 filter = talloc_asprintf(
4124                         mem_ctx, "(&(objectClass=%s)(|%s))",
4125                         LDAP_OBJ_GROUPMAP, allsids);
4126                 if (filter == NULL) {
4127                         goto done;
4128                 }
4129
4130                 rc = smbldap_search(ldap_state->smbldap_state,
4131                                     lp_ldap_suffix(talloc_tos()),
4132                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4133                                     &msg);
4134                 smbldap_talloc_autofree_ldapmsg(mem_ctx, msg);
4135         }
4136
4137         if (rc != LDAP_SUCCESS)
4138                 goto done;
4139
4140         /* ldap_struct might have changed due to a reconnect */
4141
4142         ld = ldap_state->smbldap_state->ldap_struct;
4143
4144         /* For consistency checks, we already checked we're only domain or builtin */
4145
4146         is_builtin = sid_check_is_builtin(domain_sid);
4147
4148         for (entry = ldap_first_entry(ld, msg);
4149              entry != NULL;
4150              entry = ldap_next_entry(ld, entry))
4151         {
4152                 uint32_t rid;
4153                 int rid_index;
4154                 const char *attr;
4155                 enum lsa_SidType type;
4156                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4157
4158                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4159                                                        mem_ctx);
4160                 if (attr == NULL) {
4161                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
4162                                   dn));
4163                         continue;
4164                 }
4165
4166                 type = (enum lsa_SidType)atol(attr);
4167
4168                 /* Consistency checks */
4169                 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4170                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
4171                                      (type != SID_NAME_DOM_GRP)))) {
4172                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4173                 }
4174
4175                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4176                                                     &rid)) {
4177                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4178                         continue;
4179                 }
4180
4181                 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4182
4183                 if (attr == NULL) {
4184                         DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4185                                    dn));
4186                         attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4187                 }
4188
4189                 if (attr == NULL) {
4190                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4191                                   dn));
4192                         continue;
4193                 }
4194
4195                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4196                         if (rid == rids[rid_index])
4197                                 break;
4198                 }
4199
4200                 if (rid_index == num_rids) {
4201                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4202                         continue;
4203                 }
4204
4205                 attrs[rid_index] = type;
4206                 names[rid_index] = attr;
4207                 num_mapped += 1;
4208         }
4209
4210         result = NT_STATUS_NONE_MAPPED;
4211
4212         if (num_mapped > 0)
4213                 result = (num_mapped == num_rids) ?
4214                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4215  done:
4216         TALLOC_FREE(mem_ctx);
4217         return result;
4218 }
4219
4220 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4221 {
4222         char *filter = NULL;
4223         char *escaped = NULL;
4224         char *result = NULL;
4225
4226         if (asprintf(&filter, "(&%s(objectclass=%s))",
4227                           "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4228                 goto done;
4229         }
4230
4231         escaped = escape_ldap_string(talloc_tos(), username);
4232         if (escaped == NULL) goto done;
4233
4234         result = talloc_string_sub(mem_ctx, filter, "%u", username);
4235
4236  done:
4237         SAFE_FREE(filter);
4238         TALLOC_FREE(escaped);
4239
4240         return result;
4241 }
4242
4243 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4244 {
4245         int i, num = 0;
4246         va_list ap;
4247         const char **result;
4248
4249         va_start(ap, mem_ctx);
4250         while (va_arg(ap, const char *) != NULL)
4251                 num += 1;
4252         va_end(ap);
4253
4254         if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4255                 return NULL;
4256         }
4257
4258         va_start(ap, mem_ctx);
4259         for (i=0; i<num; i++) {
4260                 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4261                 if (result[i] == NULL) {
4262                         talloc_free(result);
4263                         va_end(ap);
4264                         return NULL;
4265                 }
4266         }
4267         va_end(ap);
4268
4269         result[num] = NULL;
4270         return result;
4271 }
4272
4273 struct ldap_search_state {
4274         struct smbldap_state *connection;
4275
4276         uint32_t acct_flags;
4277         uint16_t group_type;
4278
4279         const char *base;
4280         int scope;
4281         const char *filter;
4282         const char **attrs;
4283         int attrsonly;
4284         void *pagedresults_cookie;
4285
4286         LDAPMessage *entries, *current_entry;
4287         bool (*ldap2displayentry)(struct ldap_search_state *state,
4288                                   TALLOC_CTX *mem_ctx,
4289                                   LDAP *ld, LDAPMessage *entry,
4290                                   struct samr_displayentry *result);
4291 };
4292
4293 static bool ldapsam_search_firstpage(struct pdb_search *search)
4294 {
4295         struct ldap_search_state *state =
4296                 (struct ldap_search_state *)search->private_data;
4297         LDAP *ld;
4298         int rc = LDAP_OPERATIONS_ERROR;
4299
4300         state->entries = NULL;
4301
4302         if (state->connection->paged_results) {
4303                 rc = smbldap_search_paged(state->connection, state->base,
4304                                           state->scope, state->filter,
4305                                           state->attrs, state->attrsonly,
4306                                           lp_ldap_page_size(), &state->entries,
4307                                           &state->pagedresults_cookie);
4308         }
4309
4310         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4311
4312                 if (state->entries != NULL) {
4313                         /* Left over from unsuccessful paged attempt */
4314                         ldap_msgfree(state->entries);
4315                         state->entries = NULL;
4316                 }
4317
4318                 rc = smbldap_search(state->connection, state->base,
4319                                     state->scope, state->filter, state->attrs,
4320                                     state->attrsonly, &state->entries);
4321
4322                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4323                         return False;
4324
4325                 /* Ok, the server was lying. It told us it could do paged
4326                  * searches when it could not. */
4327                 state->connection->paged_results = False;
4328         }
4329
4330         ld = state->connection->ldap_struct;
4331         if ( ld == NULL) {
4332                 DEBUG(5, ("Don't have an LDAP connection right after a "
4333                           "search\n"));
4334                 return False;
4335         }
4336         state->current_entry = ldap_first_entry(ld, state->entries);
4337
4338         return True;
4339 }
4340
4341 static bool ldapsam_search_nextpage(struct pdb_search *search)
4342 {
4343         struct ldap_search_state *state =
4344                 (struct ldap_search_state *)search->private_data;
4345         int rc;
4346
4347         if (!state->connection->paged_results) {
4348                 /* There is no next page when there are no paged results */
4349                 return False;
4350         }
4351
4352         rc = smbldap_search_paged(state->connection, state->base,
4353                                   state->scope, state->filter, state->attrs,
4354                                   state->attrsonly, lp_ldap_page_size(),
4355                                   &state->entries,
4356                                   &state->pagedresults_cookie);
4357
4358         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4359                 return False;
4360
4361         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4362
4363         if (state->current_entry == NULL) {
4364                 ldap_msgfree(state->entries);
4365                 state->entries = NULL;
4366                 return false;
4367         }
4368
4369         return True;
4370 }
4371
4372 static bool ldapsam_search_next_entry(struct pdb_search *search,
4373                                       struct samr_displayentry *entry)
4374 {
4375         struct ldap_search_state *state =
4376                 (struct ldap_search_state *)search->private_data;
4377         bool result;
4378
4379  retry:
4380         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4381                 return False;
4382
4383         if ((state->entries == NULL) &&
4384             !ldapsam_search_nextpage(search))
4385                     return False;
4386
4387         if (state->current_entry == NULL) {
4388                 return false;
4389         }
4390
4391         result = state->ldap2displayentry(state, search,
4392                                           state->connection->ldap_struct,
4393                                           state->current_entry, entry);
4394
4395         if (!result) {
4396                 char *dn;
4397                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4398                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4399                 if (dn != NULL) ldap_memfree(dn);
4400         }
4401
4402         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4403
4404         if (state->current_entry == NULL) {
4405                 ldap_msgfree(state->entries);
4406                 state->entries = NULL;
4407         }
4408
4409         if (!result) goto retry;
4410
4411         return True;
4412 }
4413
4414 static void ldapsam_search_end(struct pdb_search *search)
4415 {
4416         struct ldap_search_state *state =
4417                 (struct ldap_search_state *)search->private_data;
4418         int rc;
4419
4420         if (state->pagedresults_cookie == NULL)
4421                 return;
4422
4423         if (state->entries != NULL)
4424                 ldap_msgfree(state->entries);
4425
4426         state->entries = NULL;
4427         state->current_entry = NULL;
4428
4429         if (!state->connection->paged_results)
4430                 return;
4431
4432         /* Tell the LDAP server we're not interested in the rest anymore. */
4433
4434         rc = smbldap_search_paged(state->connection, state->base, state->scope,
4435                                   state->filter, state->attrs,
4436                                   state->attrsonly, 0, &state->entries,
4437                                   &state->pagedresults_cookie);
4438
4439         if (rc != LDAP_SUCCESS)
4440                 DEBUG(5, ("Could not end search properly\n"));
4441
4442         return;
4443 }
4444
4445 static bool ldapuser2displayentry(struct ldap_search_state *state,
4446                                   TALLOC_CTX *mem_ctx,
4447                                   LDAP *ld, LDAPMessage *entry,
4448                                   struct samr_displayentry *result)
4449 {
4450         char **vals;
4451         size_t converted_size;
4452         struct dom_sid sid;
4453         uint32_t acct_flags;
4454
4455         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4456         if ((vals == NULL) || (vals[0] == NULL)) {
4457                 acct_flags = ACB_NORMAL;
4458         } else {
4459                 acct_flags = pdb_decode_acct_ctrl(vals[0]);
4460                 ldap_value_free(vals);
4461         }
4462
4463         if ((state->acct_flags != 0) &&
4464             ((state->acct_flags & acct_flags) == 0))
4465                 return False;           
4466
4467         result->acct_flags = acct_flags;
4468         result->account_name = "";
4469         result->fullname = "";
4470         result->description = "";
4471
4472         vals = ldap_get_values(ld, entry, "uid");
4473         if ((vals == NULL) || (vals[0] == NULL)) {
4474                 DEBUG(5, ("\"uid\" not found\n"));
4475                 return False;
4476         }
4477         if (!pull_utf8_talloc(mem_ctx,
4478                               discard_const_p(char *, &result->account_name),
4479                               vals[0], &converted_size))
4480         {
4481                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4482                          strerror(errno)));
4483         }
4484
4485         ldap_value_free(vals);
4486
4487         vals = ldap_get_values(ld, entry, "displayName");
4488         if ((vals == NULL) || (vals[0] == NULL))
4489                 DEBUG(8, ("\"displayName\" not found\n"));
4490         else if (!pull_utf8_talloc(mem_ctx,
4491                                    discard_const_p(char *, &result->fullname),
4492                                    vals[0], &converted_size))
4493         {
4494                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4495                          strerror(errno)));
4496         }
4497
4498         ldap_value_free(vals);
4499
4500         vals = ldap_get_values(ld, entry, "description");
4501         if ((vals == NULL) || (vals[0] == NULL))
4502                 DEBUG(8, ("\"description\" not found\n"));
4503         else if (!pull_utf8_talloc(mem_ctx,
4504                                    discard_const_p(char *, &result->description),
4505                                    vals[0], &converted_size))
4506         {
4507                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4508                          strerror(errno)));
4509         }
4510
4511         ldap_value_free(vals);
4512
4513         if ((result->account_name == NULL) ||
4514             (result->fullname == NULL) ||
4515             (result->description == NULL)) {
4516                 DEBUG(0, ("talloc failed\n"));
4517                 return False;
4518         }
4519
4520         vals = ldap_get_values(ld, entry, "sambaSid");
4521         if ((vals == NULL) || (vals[0] == NULL)) {
4522                 DEBUG(0, ("\"objectSid\" not found\n"));
4523                 return False;
4524         }
4525
4526         if (!string_to_sid(&sid, vals[0])) {
4527                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4528                 ldap_value_free(vals);
4529                 return False;
4530         }
4531         ldap_value_free(vals);
4532
4533         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4534                 DEBUG(0, ("sid %s does not belong to our domain\n",
4535                           sid_string_dbg(&sid)));
4536                 return False;
4537         }
4538
4539         return True;
4540 }
4541
4542
4543 static bool ldapsam_search_users(struct pdb_methods *methods,
4544                                  struct pdb_search *search,
4545                                  uint32_t acct_flags)
4546 {
4547         struct ldapsam_privates *ldap_state =
4548                 (struct ldapsam_privates *)methods->private_data;
4549         struct ldap_search_state *state;
4550
4551         state = talloc(search, struct ldap_search_state);
4552         if (state == NULL) {
4553                 DEBUG(0, ("talloc failed\n"));
4554                 return False;
4555         }
4556
4557         state->connection = ldap_state->smbldap_state;
4558
4559         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4560                 state->base = lp_ldap_user_suffix(talloc_tos());
4561         else if ((acct_flags != 0) &&
4562                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4563                 state->base = lp_ldap_machine_suffix(talloc_tos());
4564         else
4565                 state->base = lp_ldap_suffix(talloc_tos());
4566
4567         state->acct_flags = acct_flags;
4568         state->base = talloc_strdup(search, state->base);
4569         state->scope = LDAP_SCOPE_SUBTREE;
4570         state->filter = get_ldap_filter(search, "*");
4571         state->attrs = talloc_attrs(search, "uid", "sambaSid",
4572                                     "displayName", "description",
4573                                     "sambaAcctFlags", NULL);
4574         state->attrsonly = 0;
4575         state->pagedresults_cookie = NULL;
4576         state->entries = NULL;
4577         state->ldap2displayentry = ldapuser2displayentry;
4578
4579         if ((state->filter == NULL) || (state->attrs == NULL)) {
4580                 DEBUG(0, ("talloc failed\n"));
4581                 return False;
4582         }
4583
4584         search->private_data = state;
4585         search->next_entry = ldapsam_search_next_entry;
4586         search->search_end = ldapsam_search_end;
4587
4588         return ldapsam_search_firstpage(search);
4589 }
4590
4591 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4592                                    TALLOC_CTX *mem_ctx,
4593                                    LDAP *ld, LDAPMessage *entry,
4594                                    struct samr_displayentry *result)
4595 {
4596         char **vals;
4597         size_t converted_size;
4598         struct dom_sid sid;
4599         uint16_t group_type;
4600
4601         result->account_name = "";
4602         result->fullname = "";
4603         result->description = "";
4604
4605
4606         vals = ldap_get_values(ld, entry, "sambaGroupType");
4607         if ((vals == NULL) || (vals[0] == NULL)) {
4608                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4609                 if (vals != NULL) {
4610                         ldap_value_free(vals);
4611                 }
4612                 return False;
4613         }
4614
4615         group_type = atoi(vals[0]);
4616
4617         if ((state->group_type != 0) &&
4618             ((state->group_type != group_type))) {
4619                 ldap_value_free(vals);
4620                 return False;
4621         }
4622
4623         ldap_value_free(vals);
4624
4625         /* display name is the NT group name */
4626
4627         vals = ldap_get_values(ld, entry, "displayName");
4628         if ((vals == NULL) || (vals[0] == NULL)) {
4629                 DEBUG(8, ("\"displayName\" not found\n"));
4630
4631                 /* fallback to the 'cn' attribute */
4632                 vals = ldap_get_values(ld, entry, "cn");
4633                 if ((vals == NULL) || (vals[0] == NULL)) {
4634                         DEBUG(5, ("\"cn\" not found\n"));
4635                         return False;
4636                 }
4637                 if (!pull_utf8_talloc(mem_ctx,
4638                                       discard_const_p(char *,
4639                                                     &result->account_name),
4640                                       vals[0], &converted_size))
4641                 {
4642                         DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4643                                   "failed: %s", strerror(errno)));
4644                 }
4645         }
4646         else if (!pull_utf8_talloc(mem_ctx,
4647                                    discard_const_p(char *,
4648                                                  &result->account_name),
4649                                    vals[0], &converted_size))
4650         {
4651                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4652                           strerror(errno)));
4653         }
4654
4655         ldap_value_free(vals);
4656
4657         vals = ldap_get_values(ld, entry, "description");
4658         if ((vals == NULL) || (vals[0] == NULL))
4659                 DEBUG(8, ("\"description\" not found\n"));
4660         else if (!pull_utf8_talloc(mem_ctx,
4661                                    discard_const_p(char *, &result->description),
4662                                    vals[0], &converted_size))
4663         {
4664                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4665                           strerror(errno)));
4666         }
4667         ldap_value_free(vals);
4668
4669         if ((result->account_name == NULL) ||
4670             (result->fullname == NULL) ||
4671             (result->description == NULL)) {
4672                 DEBUG(0, ("talloc failed\n"));
4673                 return False;
4674         }
4675
4676         vals = ldap_get_values(ld, entry, "sambaSid");
4677         if ((vals == NULL) || (vals[0] == NULL)) {
4678                 DEBUG(0, ("\"objectSid\" not found\n"));
4679                 if (vals != NULL) {
4680                         ldap_value_free(vals);
4681                 }
4682                 return False;
4683         }
4684
4685         if (!string_to_sid(&sid, vals[0])) {
4686                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4687                 return False;
4688         }
4689
4690         ldap_value_free(vals);
4691
4692         switch (group_type) {
4693                 case SID_NAME_DOM_GRP:
4694                 case SID_NAME_ALIAS:
4695
4696                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid) 
4697                                 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid)) 
4698                         {
4699                                 DEBUG(0, ("%s is not in our domain\n",
4700                                           sid_string_dbg(&sid)));
4701                                 return False;
4702                         }
4703                         break;
4704
4705                 default:
4706                         DEBUG(0,("unknown group type: %d\n", group_type));
4707                         return False;
4708         }
4709
4710         result->acct_flags = 0;
4711
4712         return True;
4713 }
4714
4715 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4716                                      struct pdb_search *search,
4717                                      const struct dom_sid *sid,
4718                                      enum lsa_SidType type)
4719 {
4720         struct ldapsam_privates *ldap_state =
4721                 (struct ldapsam_privates *)methods->private_data;
4722         struct ldap_search_state *state;
4723         fstring tmp;
4724
4725         state = talloc(search, struct ldap_search_state);
4726         if (state == NULL) {
4727                 DEBUG(0, ("talloc failed\n"));
4728                 return False;
4729         }
4730
4731         state->connection = ldap_state->smbldap_state;
4732
4733         state->base = lp_ldap_suffix(search);
4734         state->connection = ldap_state->smbldap_state;
4735         state->scope = LDAP_SCOPE_SUBTREE;
4736         state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4737                                         "(sambaGroupType=%d)(sambaSID=%s*))",
4738                                          LDAP_OBJ_GROUPMAP,
4739                                          type, sid_to_fstring(tmp, sid));
4740         state->attrs = talloc_attrs(search, "cn", "sambaSid",
4741                                     "displayName", "description",
4742                                     "sambaGroupType", NULL);
4743         state->attrsonly = 0;
4744         state->pagedresults_cookie = NULL;
4745         state->entries = NULL;
4746         state->group_type = type;
4747         state->ldap2displayentry = ldapgroup2displayentry;
4748
4749         if ((state->filter == NULL) || (state->attrs == NULL)) {
4750                 DEBUG(0, ("talloc failed\n"));
4751                 return False;
4752         }
4753
4754         search->private_data = state;
4755         search->next_entry = ldapsam_search_next_entry;
4756         search->search_end = ldapsam_search_end;
4757
4758         return ldapsam_search_firstpage(search);
4759 }
4760
4761 static bool ldapsam_search_groups(struct pdb_methods *methods,
4762                                   struct pdb_search *search)
4763 {
4764         return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4765 }
4766
4767 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4768                                    struct pdb_search *search,
4769                                    const struct dom_sid *sid)
4770 {
4771         return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4772 }
4773
4774 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4775 {
4776         return PDB_CAP_STORE_RIDS;
4777 }
4778
4779 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4780                                     uint32_t *rid)
4781 {
4782         struct smbldap_state *smbldap_state = priv->smbldap_state;
4783
4784         LDAPMessage *result = NULL;
4785         LDAPMessage *entry = NULL;
4786         LDAPMod **mods = NULL;
4787         NTSTATUS status;
4788         char *value;
4789         int rc;
4790         uint32_t nextRid = 0;
4791         const char *dn;
4792
4793         TALLOC_CTX *mem_ctx;
4794
4795         mem_ctx = talloc_new(NULL);
4796         if (mem_ctx == NULL) {
4797                 DEBUG(0, ("talloc_new failed\n"));
4798                 return NT_STATUS_NO_MEMORY;
4799         }
4800
4801         status = smbldap_search_domain_info(smbldap_state, &result,
4802                                             get_global_sam_name(), False);
4803         if (!NT_STATUS_IS_OK(status)) {
4804                 DEBUG(3, ("Could not get domain info: %s\n",
4805                           nt_errstr(status)));
4806                 goto done;
4807         }
4808
4809         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4810
4811         entry = ldap_first_entry(priv2ld(priv), result);
4812         if (entry == NULL) {
4813                 DEBUG(0, ("Could not get domain info entry\n"));
4814                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4815                 goto done;
4816         }
4817
4818         /* Find the largest of the three attributes "sambaNextRid",
4819            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4820            concept of differentiating between user and group rids, and will
4821            use only "sambaNextRid" in the future. But for compatibility
4822            reasons I look if others have chosen different strategies -- VL */
4823
4824         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4825                                                 "sambaNextRid", mem_ctx);
4826         if (value != NULL) {
4827                 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4828                 nextRid = MAX(nextRid, tmp);
4829         }
4830
4831         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4832                                                 "sambaNextUserRid", mem_ctx);
4833         if (value != NULL) {
4834                 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4835                 nextRid = MAX(nextRid, tmp);
4836         }
4837
4838         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4839                                                 "sambaNextGroupRid", mem_ctx);
4840         if (value != NULL) {
4841                 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4842                 nextRid = MAX(nextRid, tmp);
4843         }
4844
4845         if (nextRid == 0) {
4846                 nextRid = BASE_RID-1;
4847         }
4848
4849         nextRid += 1;
4850
4851         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4852                          talloc_asprintf(mem_ctx, "%d", nextRid));
4853         smbldap_talloc_autofree_ldapmod(mem_ctx, mods);
4854
4855         if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4856                 status = NT_STATUS_NO_MEMORY;
4857                 goto done;
4858         }
4859
4860         rc = smbldap_modify(smbldap_state, dn, mods);
4861
4862         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4863          * please retry" */
4864
4865         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4866
4867  done:
4868         if (NT_STATUS_IS_OK(status)) {
4869                 *rid = nextRid;
4870         }
4871
4872         TALLOC_FREE(mem_ctx);
4873         return status;
4874 }
4875
4876 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4877 {
4878         int i;
4879
4880         for (i=0; i<10; i++) {
4881                 NTSTATUS result = ldapsam_get_new_rid(
4882                         (struct ldapsam_privates *)methods->private_data, rid);
4883                 if (NT_STATUS_IS_OK(result)) {
4884                         return result;
4885                 }
4886
4887                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4888                         return result;
4889                 }
4890
4891                 /* The ldap update failed (maybe a race condition), retry */
4892         }
4893
4894         /* Tried 10 times, fail. */
4895         return NT_STATUS_ACCESS_DENIED;
4896 }
4897
4898 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4899 {
4900         NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4901         return NT_STATUS_IS_OK(result) ? True : False;
4902 }
4903
4904 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4905                               const struct dom_sid *sid,
4906                               struct unixid *id)
4907 {
4908         struct ldapsam_privates *priv =
4909                 (struct ldapsam_privates *)methods->private_data;
4910         char *filter;
4911         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4912                                 NULL };
4913         LDAPMessage *result = NULL;
4914         LDAPMessage *entry = NULL;
4915         bool ret = False;
4916         char *value;
4917         int rc;
4918
4919         TALLOC_CTX *mem_ctx;
4920
4921         ret = pdb_sid_to_id_unix_users_and_groups(sid, id);
4922         if (ret == true) {
4923                 return true;
4924         }
4925
4926         mem_ctx = talloc_new(NULL);
4927         if (mem_ctx == NULL) {
4928                 DEBUG(0, ("talloc_new failed\n"));
4929                 return False;
4930         }
4931
4932         filter = talloc_asprintf(mem_ctx,
4933                                  "(&(sambaSid=%s)"
4934                                  "(|(objectClass=%s)(objectClass=%s)))",
4935                                  sid_string_talloc(mem_ctx, sid),
4936                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4937         if (filter == NULL) {
4938                 DEBUG(5, ("talloc_asprintf failed\n"));
4939                 goto done;
4940         }
4941
4942         rc = smbldap_search_suffix(priv->smbldap_state, filter,
4943                                    attrs, &result);
4944         if (rc != LDAP_SUCCESS) {
4945                 goto done;
4946         }
4947         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
4948
4949         if (ldap_count_entries(priv2ld(priv), result) != 1) {
4950                 DEBUG(10, ("Got %d entries, expected one\n",
4951                            ldap_count_entries(priv2ld(priv), result)));
4952                 goto done;
4953         }
4954
4955         entry = ldap_first_entry(priv2ld(priv), result);
4956
4957         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4958                                                 "sambaGroupType", mem_ctx);
4959
4960         if (value != NULL) {
4961                 const char *gid_str;
4962                 /* It's a group */
4963
4964                 gid_str = smbldap_talloc_single_attribute(
4965                         priv2ld(priv), entry, "gidNumber", mem_ctx);
4966                 if (gid_str == NULL) {
4967                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4968                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4969                                                     entry)));
4970                         goto done;
4971                 }
4972
4973                 id->id = strtoul(gid_str, NULL, 10);
4974                 id->type = ID_TYPE_GID;
4975                 ret = True;
4976                 goto done;
4977         }
4978
4979         /* It must be a user */
4980
4981         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4982                                                 "uidNumber", mem_ctx);
4983         if (value == NULL) {
4984                 DEBUG(1, ("Could not find uidNumber in %s\n",
4985                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4986                 goto done;
4987         }
4988
4989         id->id = strtoul(value, NULL, 10);
4990         id->type = ID_TYPE_UID;
4991
4992         ret = True;
4993  done:
4994         TALLOC_FREE(mem_ctx);
4995         return ret;
4996 }
4997
4998 /**
4999  * Find the SID for a uid.
5000  * This is shortcut is only used if ldapsam:trusted is set to true.
5001  */
5002 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5003                                struct dom_sid *sid)
5004 {
5005         struct ldapsam_privates *priv =
5006                 (struct ldapsam_privates *)methods->private_data;
5007         char *filter;
5008         const char *attrs[] = { "sambaSID", NULL };
5009         LDAPMessage *result = NULL;
5010         LDAPMessage *entry = NULL;
5011         bool ret = false;
5012         char *user_sid_string;
5013         struct dom_sid user_sid;
5014         int rc;
5015         TALLOC_CTX *tmp_ctx = talloc_stackframe();
5016
5017         filter = talloc_asprintf(tmp_ctx,
5018                                  "(&(uidNumber=%u)"
5019                                  "(objectClass=%s)"
5020                                  "(objectClass=%s))",
5021                                  (unsigned int)uid,
5022                                  LDAP_OBJ_POSIXACCOUNT,
5023                                  LDAP_OBJ_SAMBASAMACCOUNT);
5024         if (filter == NULL) {
5025                 DEBUG(3, ("talloc_asprintf failed\n"));
5026                 goto done;
5027         }
5028
5029         rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5030         if (rc != LDAP_SUCCESS) {
5031                 goto done;
5032         }
5033         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5034
5035         if (ldap_count_entries(priv2ld(priv), result) != 1) {
5036                 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5037                            ldap_count_entries(priv2ld(priv), result),
5038                            (unsigned int)uid));
5039                 goto done;
5040         }
5041
5042         entry = ldap_first_entry(priv2ld(priv), result);
5043
5044         user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5045                                                           "sambaSID", tmp_ctx);
5046         if (user_sid_string == NULL) {
5047                 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5048                           smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5049                 goto done;
5050         }
5051
5052         if (!string_to_sid(&user_sid, user_sid_string)) {
5053                 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5054                           user_sid_string));
5055                 goto done;
5056         }
5057
5058         sid_copy(sid, &user_sid);
5059
5060         ret = true;
5061
5062  done:
5063         TALLOC_FREE(tmp_ctx);
5064         return ret;
5065 }
5066
5067 /**
5068  * Find the SID for a gid.
5069  * This is shortcut is only used if ldapsam:trusted is set to true.
5070  */
5071 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5072                                struct dom_sid *sid)
5073 {
5074         struct ldapsam_privates *priv =
5075                 (struct ldapsam_privates *)methods->private_data;
5076         char *filter;
5077         const char *attrs[] = { "sambaSID", NULL };
5078         LDAPMessage *result = NULL;
5079         LDAPMessage *entry = NULL;
5080         bool ret = false;
5081         char *group_sid_string;
5082         struct dom_sid group_sid;
5083         int rc;
5084         TALLOC_CTX *tmp_ctx = talloc_stackframe();
5085
5086         filter = talloc_asprintf(tmp_ctx,
5087                                  "(&(gidNumber=%u)"
5088                                  "(objectClass=%s))",
5089                                  (unsigned int)gid,
5090                                  LDAP_OBJ_GROUPMAP);
5091         if (filter == NULL) {
5092                 DEBUG(3, ("talloc_asprintf failed\n"));
5093                 goto done;
5094         }
5095
5096         rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5097         if (rc != LDAP_SUCCESS) {
5098                 goto done;
5099         }
5100         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5101
5102         if (ldap_count_entries(priv2ld(priv), result) != 1) {
5103                 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5104                            ldap_count_entries(priv2ld(priv), result),
5105                            (unsigned int)gid));
5106                 goto done;
5107         }
5108
5109         entry = ldap_first_entry(priv2ld(priv), result);
5110
5111         group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5112                                                           "sambaSID", tmp_ctx);
5113         if (group_sid_string == NULL) {
5114                 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5115                           smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5116                 goto done;
5117         }
5118
5119         if (!string_to_sid(&group_sid, group_sid_string)) {
5120                 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5121                           group_sid_string));
5122                 goto done;
5123         }
5124
5125         sid_copy(sid, &group_sid);
5126
5127         ret = true;
5128
5129  done:
5130         TALLOC_FREE(tmp_ctx);
5131         return ret;
5132 }
5133
5134 static bool ldapsam_id_to_sid(struct pdb_methods *methods, struct unixid *id,
5135                                    struct dom_sid *sid)
5136 {
5137         switch (id->type) {
5138         case ID_TYPE_UID:
5139                 return ldapsam_uid_to_sid(methods, id->id, sid);
5140
5141         case ID_TYPE_GID:
5142                 return ldapsam_gid_to_sid(methods, id->id, sid);
5143
5144         default:
5145                 return false;
5146         }
5147 }
5148
5149
5150 /*
5151  * The following functions are called only if
5152  * ldapsam:trusted and ldapsam:editposix are
5153  * set to true
5154  */
5155
5156 /*
5157  * ldapsam_create_user creates a new
5158  * posixAccount and sambaSamAccount object
5159  * in the ldap users subtree
5160  *
5161  * The uid is allocated by winbindd.
5162  */
5163
5164 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5165                                     TALLOC_CTX *tmp_ctx, const char *name,
5166                                     uint32_t acb_info, uint32_t *rid)
5167 {
5168         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5169         LDAPMessage *entry = NULL;
5170         LDAPMessage *result = NULL;
5171         uint32_t num_result;
5172         bool is_machine = False;
5173         bool add_posix = False;
5174         bool init_okay = False;
5175         LDAPMod **mods = NULL;
5176         struct samu *user;
5177         char *filter;
5178         char *username;
5179         char *homedir;
5180         char *gidstr;
5181         char *uidstr;
5182         char *shell;
5183         const char *dn = NULL;
5184         struct dom_sid group_sid;
5185         struct dom_sid user_sid;
5186         gid_t gid = -1;
5187         uid_t uid = -1;
5188         NTSTATUS ret;
5189         int rc;
5190
5191         if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5192               acb_info & ACB_WSTRUST ||
5193               acb_info & ACB_SVRTRUST ||
5194               acb_info & ACB_DOMTRUST) {
5195                 is_machine = True;
5196         }
5197
5198         username = escape_ldap_string(talloc_tos(), name);
5199         filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5200                                  username, LDAP_OBJ_POSIXACCOUNT);
5201         TALLOC_FREE(username);
5202
5203         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5204         if (rc != LDAP_SUCCESS) {
5205                 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5206                 return NT_STATUS_ACCESS_DENIED;
5207         }
5208         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5209
5210         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5211
5212         if (num_result > 1) {
5213                 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5214                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5215         }
5216
5217         if (num_result == 1) {
5218                 char *tmp;
5219                 /* check if it is just a posix account.
5220                  * or if there is a sid attached to this entry
5221                  */
5222
5223                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5224                 if (!entry) {
5225                         return NT_STATUS_UNSUCCESSFUL;
5226                 }
5227
5228                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5229                 if (tmp) {
5230                         DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5231                         return NT_STATUS_USER_EXISTS;
5232                 }
5233
5234                 /* it is just a posix account, retrieve the dn for later use */
5235                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5236                 if (!dn) {
5237                         DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5238                         return NT_STATUS_NO_MEMORY;
5239                 }
5240         }
5241
5242         if (num_result == 0) {
5243                 add_posix = True;
5244         }
5245
5246         /* Create the basic samu structure and generate the mods for the ldap commit */
5247         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5248                 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5249                 return ret;
5250         }
5251
5252         sid_compose(&user_sid, get_global_sam_sid(), *rid);
5253
5254         user = samu_new(tmp_ctx);
5255         if (!user) {
5256                 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5257                 return NT_STATUS_NO_MEMORY;
5258         }
5259
5260         if (!pdb_set_username(user, name, PDB_SET)) {
5261                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5262                 return NT_STATUS_UNSUCCESSFUL;
5263         }
5264         if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5265                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5266                 return NT_STATUS_UNSUCCESSFUL;
5267         }
5268         if (is_machine) {
5269                 if (acb_info & ACB_NORMAL) {
5270                         if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5271                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5272                                 return NT_STATUS_UNSUCCESSFUL;
5273                         }
5274                 } else {
5275                         if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5276                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5277                                 return NT_STATUS_UNSUCCESSFUL;
5278                         }
5279                 }
5280         } else {
5281                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5282                         DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5283                         return NT_STATUS_UNSUCCESSFUL;
5284                 }
5285         }
5286
5287         if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5288                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5289                 return NT_STATUS_UNSUCCESSFUL;
5290         }
5291
5292         init_okay = init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed);
5293
5294         if (!init_okay) {
5295                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5296                 ldap_mods_free(mods, true);
5297                 return NT_STATUS_UNSUCCESSFUL;
5298         }
5299
5300         if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5301                 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5302         }
5303         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5304
5305         if (add_posix) {
5306                 char *escape_name;
5307
5308                 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5309
5310                 /* retrieve the Domain Users group gid */
5311                 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5312                     !sid_to_gid(&group_sid, &gid)) {
5313                         DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5314                         ldap_mods_free(mods, true);
5315                         return NT_STATUS_INVALID_PRIMARY_GROUP;
5316                 }
5317
5318                 /* lets allocate a new userid for this user */
5319                 if (!winbind_allocate_uid(&uid)) {
5320                         DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5321                         ldap_mods_free(mods, true);
5322                         return NT_STATUS_UNSUCCESSFUL;
5323                 }
5324
5325
5326                 if (is_machine) {
5327                         /* TODO: choose a more appropriate default for machines */
5328                         homedir = talloc_sub_specified(tmp_ctx,
5329                                                        lp_template_homedir(),
5330                                                        "SMB_workstations_home",
5331                                                        NULL,
5332                                                        ldap_state->domain_name,
5333                                                        uid,
5334                                                        gid);
5335                         shell = talloc_strdup(tmp_ctx, "/bin/false");
5336                 } else {
5337                         homedir = talloc_sub_specified(tmp_ctx,
5338                                                        lp_template_homedir(),
5339                                                        name,
5340                                                        NULL,
5341                                                        ldap_state->domain_name,
5342                                                        uid,
5343                                                        gid);
5344                         shell = talloc_sub_specified(tmp_ctx,
5345                                                      lp_template_shell(),
5346                                                      name,
5347                                                      NULL,
5348                                                      ldap_state->domain_name,
5349                                                      uid,
5350                                                      gid);
5351                 }
5352                 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5353                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5354
5355                 escape_name = escape_rdn_val_string_alloc(name);
5356                 if (!escape_name) {
5357                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5358                         ldap_mods_free(mods, true);
5359                         return NT_STATUS_NO_MEMORY;
5360                 }
5361
5362                 if (is_machine) {
5363                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix (talloc_tos()));
5364                 } else {
5365                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix (talloc_tos()));
5366                 }
5367
5368                 SAFE_FREE(escape_name);
5369
5370                 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5371                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5372                         ldap_mods_free(mods, true);
5373                         return NT_STATUS_NO_MEMORY;
5374                 }
5375
5376                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5377                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5378                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5379                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5380                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5381                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5382                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5383         }
5384
5385         if (add_posix) {
5386                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5387         } else {
5388                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5389         }       
5390
5391         ldap_mods_free(mods, true);
5392
5393         if (rc != LDAP_SUCCESS) {
5394                 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5395                 return NT_STATUS_UNSUCCESSFUL;
5396         }
5397
5398         DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5399
5400         flush_pwnam_cache();
5401
5402         return NT_STATUS_OK;
5403 }
5404
5405 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5406 {
5407         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5408         LDAPMessage *result = NULL;
5409         LDAPMessage *entry = NULL;
5410         int num_result;
5411         const char *dn;
5412         char *filter;
5413         int rc;
5414
5415         DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5416
5417         filter = talloc_asprintf(tmp_ctx,
5418                                  "(&(uid=%s)"
5419                                  "(objectClass=%s)"
5420                                  "(objectClass=%s))",
5421                                  pdb_get_username(sam_acct),
5422                                  LDAP_OBJ_POSIXACCOUNT,
5423                                  LDAP_OBJ_SAMBASAMACCOUNT);
5424         if (filter == NULL) {
5425                 return NT_STATUS_NO_MEMORY;
5426         }
5427
5428         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5429         if (rc != LDAP_SUCCESS) {
5430                 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5431                 return NT_STATUS_UNSUCCESSFUL;
5432         }
5433         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5434
5435         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5436
5437         if (num_result == 0) {
5438                 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5439                 return NT_STATUS_NO_SUCH_USER;
5440         }
5441
5442         if (num_result > 1) {
5443                 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5444                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5445         }
5446
5447         entry = ldap_first_entry(priv2ld(ldap_state), result);
5448         if (!entry) {
5449                 return NT_STATUS_UNSUCCESSFUL;
5450         }
5451
5452         /* it is just a posix account, retrieve the dn for later use */
5453         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5454         if (!dn) {
5455                 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5456                 return NT_STATUS_NO_MEMORY;
5457         }
5458
5459         /* try to remove memberships first */
5460         {
5461                 NTSTATUS status;
5462                 struct dom_sid *sids = NULL;
5463                 gid_t *gids = NULL;
5464                 uint32_t num_groups = 0;
5465                 int i;
5466                 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5467
5468                 status = ldapsam_enum_group_memberships(my_methods,
5469                                                         tmp_ctx,
5470                                                         sam_acct,
5471                                                         &sids,
5472                                                         &gids,
5473                                                         &num_groups);
5474                 if (!NT_STATUS_IS_OK(status)) {
5475                         goto delete_dn;
5476                 }
5477
5478                 for (i=0; i < num_groups; i++) {
5479
5480                         uint32_t group_rid;
5481
5482                         sid_peek_rid(&sids[i], &group_rid);
5483
5484                         ldapsam_del_groupmem(my_methods,
5485                                              tmp_ctx,
5486                                              group_rid,
5487                                              user_rid);
5488                 }
5489         }
5490
5491  delete_dn:
5492
5493         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5494         if (rc != LDAP_SUCCESS) {
5495                 return NT_STATUS_UNSUCCESSFUL;
5496         }
5497
5498         flush_pwnam_cache();
5499
5500         return NT_STATUS_OK;
5501 }
5502
5503 /*
5504  * ldapsam_create_group creates a new
5505  * posixGroup and sambaGroupMapping object
5506  * in the ldap groups subtree
5507  *
5508  * The gid is allocated by winbindd.
5509  */
5510
5511 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5512                                          TALLOC_CTX *tmp_ctx,
5513                                          const char *name,
5514                                          uint32_t *rid)
5515 {
5516         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5517         NTSTATUS ret;
5518         LDAPMessage *entry = NULL;
5519         LDAPMessage *result = NULL;
5520         uint32_t num_result;
5521         bool is_new_entry = False;
5522         LDAPMod **mods = NULL;
5523         char *filter;
5524         char *groupsidstr;
5525         char *groupname;
5526         char *grouptype;
5527         char *gidstr;
5528         const char *dn = NULL;
5529         struct dom_sid group_sid;
5530         gid_t gid = -1;
5531         int rc;
5532
5533         groupname = escape_ldap_string(talloc_tos(), name);
5534         filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5535                                  groupname, LDAP_OBJ_POSIXGROUP);
5536         TALLOC_FREE(groupname);
5537
5538         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5539         if (rc != LDAP_SUCCESS) {
5540                 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5541                 return NT_STATUS_UNSUCCESSFUL;
5542         }
5543         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5544
5545         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5546
5547         if (num_result > 1) {
5548                 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5549                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5550         }
5551
5552         if (num_result == 1) {
5553                 char *tmp;
5554                 /* check if it is just a posix group.
5555                  * or if there is a sid attached to this entry
5556                  */
5557
5558                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5559                 if (!entry) {
5560                         return NT_STATUS_UNSUCCESSFUL;
5561                 }
5562
5563                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5564                 if (tmp) {
5565                         DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5566                         return NT_STATUS_GROUP_EXISTS;
5567                 }
5568
5569                 /* it is just a posix group, retrieve the gid and the dn for later use */
5570                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5571                 if (!tmp) {
5572                         DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5573                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5574                 }
5575
5576                 gid = strtoul(tmp, NULL, 10);
5577
5578                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5579                 if (!dn) {
5580                         DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5581                         return NT_STATUS_NO_MEMORY;
5582                 }
5583         }
5584
5585         if (num_result == 0) {
5586                 is_new_entry = true;
5587         }
5588
5589         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5590                 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5591                 return ret;
5592         }
5593
5594         sid_compose(&group_sid, get_global_sam_sid(), *rid);
5595
5596         groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5597                                                                &group_sid));
5598         grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5599
5600         if (!groupsidstr || !grouptype) {
5601                 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5602                 return NT_STATUS_NO_MEMORY;
5603         }
5604
5605         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5606         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5607         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5608         smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5609
5610         if (is_new_entry) {
5611                 char *escape_name;
5612
5613                 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5614
5615                 /* lets allocate a new groupid for this group */
5616                 if (!winbind_allocate_gid(&gid)) {
5617                         DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5618                         return NT_STATUS_UNSUCCESSFUL;
5619                 }
5620
5621                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5622
5623                 escape_name = escape_rdn_val_string_alloc(name);
5624                 if (!escape_name) {
5625                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5626                         return NT_STATUS_NO_MEMORY;
5627                 }
5628
5629                 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix(talloc_tos()));
5630
5631                 SAFE_FREE(escape_name);
5632
5633                 if (!gidstr || !dn) {
5634                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5635                         return NT_STATUS_NO_MEMORY;
5636                 }
5637
5638                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5639                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5640                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5641         }
5642
5643         smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5644
5645         if (is_new_entry) {     
5646                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5647 #if 0
5648                 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5649                         /* This call may fail with rfc2307bis schema */
5650                         /* Retry adding a structural class */
5651                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5652                         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5653                 }
5654 #endif
5655         } else {
5656                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5657         }       
5658
5659         if (rc != LDAP_SUCCESS) {
5660                 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5661                 return NT_STATUS_UNSUCCESSFUL;
5662         }
5663
5664         DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5665
5666         return NT_STATUS_OK;
5667 }
5668
5669 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5670 {
5671         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5672         LDAPMessage *result = NULL;
5673         LDAPMessage *entry = NULL;
5674         int num_result;
5675         const char *dn;
5676         char *gidstr;
5677         char *filter;
5678         struct dom_sid group_sid;
5679         int rc;
5680
5681         /* get the group sid */
5682         sid_compose(&group_sid, get_global_sam_sid(), rid);
5683
5684         filter = talloc_asprintf(tmp_ctx,
5685                                  "(&(sambaSID=%s)"
5686                                  "(objectClass=%s)"
5687                                  "(objectClass=%s))",
5688                                  sid_string_talloc(tmp_ctx, &group_sid),
5689                                  LDAP_OBJ_POSIXGROUP,
5690                                  LDAP_OBJ_GROUPMAP);
5691         if (filter == NULL) {
5692                 return NT_STATUS_NO_MEMORY;
5693         }
5694
5695         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5696         if (rc != LDAP_SUCCESS) {
5697                 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5698                 return NT_STATUS_UNSUCCESSFUL;
5699         }
5700         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5701
5702         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5703
5704         if (num_result == 0) {
5705                 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5706                 return NT_STATUS_NO_SUCH_GROUP;
5707         }
5708
5709         if (num_result > 1) {
5710                 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5711                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5712         }
5713
5714         entry = ldap_first_entry(priv2ld(ldap_state), result);
5715         if (!entry) {
5716                 return NT_STATUS_UNSUCCESSFUL;
5717         }
5718
5719         /* here it is, retrieve the dn for later use */
5720         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5721         if (!dn) {
5722                 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5723                 return NT_STATUS_NO_MEMORY;
5724         }
5725
5726         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5727         if (!gidstr) {
5728                 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5729                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5730         }
5731
5732         /* check no user have this group marked as primary group */
5733         filter = talloc_asprintf(tmp_ctx,
5734                                  "(&(gidNumber=%s)"
5735                                  "(objectClass=%s)"
5736                                  "(objectClass=%s))",
5737                                  gidstr,
5738                                  LDAP_OBJ_POSIXACCOUNT,
5739                                  LDAP_OBJ_SAMBASAMACCOUNT);
5740
5741         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5742         if (rc != LDAP_SUCCESS) {
5743                 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5744                 return NT_STATUS_UNSUCCESSFUL;
5745         }
5746         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5747
5748         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5749
5750         if (num_result != 0) {
5751                 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5752                 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5753         }
5754
5755         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5756         if (rc != LDAP_SUCCESS) {
5757                 return NT_STATUS_UNSUCCESSFUL;
5758         }
5759
5760         return NT_STATUS_OK;
5761 }
5762
5763 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5764                                         TALLOC_CTX *tmp_ctx,
5765                                         uint32_t group_rid,
5766                                         uint32_t member_rid,
5767                                         int modop)
5768 {
5769         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5770         LDAPMessage *entry = NULL;
5771         LDAPMessage *result = NULL;
5772         uint32_t num_result;
5773         LDAPMod **mods = NULL;
5774         char *filter;
5775         char *uidstr;
5776         const char *dn = NULL;
5777         struct dom_sid group_sid;
5778         struct dom_sid member_sid;
5779         int rc;
5780
5781         switch (modop) {
5782         case LDAP_MOD_ADD:
5783                 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5784                 break;
5785         case LDAP_MOD_DELETE:
5786                 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5787                 break;
5788         default:
5789                 return NT_STATUS_UNSUCCESSFUL;
5790         }
5791
5792         /* get member sid  */
5793         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5794
5795         /* get the group sid */
5796         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5797
5798         filter = talloc_asprintf(tmp_ctx,
5799                                  "(&(sambaSID=%s)"
5800                                  "(objectClass=%s)"
5801                                  "(objectClass=%s))",
5802                                  sid_string_talloc(tmp_ctx, &member_sid),
5803                                  LDAP_OBJ_POSIXACCOUNT,
5804                                  LDAP_OBJ_SAMBASAMACCOUNT);
5805         if (filter == NULL) {
5806                 return NT_STATUS_NO_MEMORY;
5807         }
5808
5809         /* get the member uid */
5810         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5811         if (rc != LDAP_SUCCESS) {
5812                 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5813                 return NT_STATUS_UNSUCCESSFUL;
5814         }
5815         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5816
5817         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5818
5819         if (num_result == 0) {
5820                 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5821                 return NT_STATUS_NO_SUCH_MEMBER;
5822         }
5823
5824         if (num_result > 1) {
5825                 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5826                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5827         }
5828
5829         entry = ldap_first_entry(priv2ld(ldap_state), result);
5830         if (!entry) {
5831                 return NT_STATUS_UNSUCCESSFUL;
5832         }
5833
5834         if (modop == LDAP_MOD_DELETE) {
5835                 /* check if we are trying to remove the member from his primary group */
5836                 char *gidstr;
5837                 gid_t user_gid, group_gid;
5838
5839                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5840                 if (!gidstr) {
5841                         DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5842                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5843                 }
5844
5845                 user_gid = strtoul(gidstr, NULL, 10);
5846
5847                 if (!sid_to_gid(&group_sid, &group_gid)) {
5848                         DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5849                         return NT_STATUS_UNSUCCESSFUL;
5850                 }
5851
5852                 if (user_gid == group_gid) {
5853                         DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5854                         return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5855                 }
5856         }
5857
5858         /* here it is, retrieve the uid for later use */
5859         uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5860         if (!uidstr) {
5861                 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5862                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5863         }
5864
5865         filter = talloc_asprintf(tmp_ctx,
5866                                  "(&(sambaSID=%s)"
5867                                  "(objectClass=%s)"
5868                                  "(objectClass=%s))",
5869                                  sid_string_talloc(tmp_ctx, &group_sid),
5870                                  LDAP_OBJ_POSIXGROUP,
5871                                  LDAP_OBJ_GROUPMAP);
5872
5873         /* get the group */
5874         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5875         if (rc != LDAP_SUCCESS) {
5876                 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5877                 return NT_STATUS_UNSUCCESSFUL;
5878         }
5879         smbldap_talloc_autofree_ldapmsg(tmp_ctx, result);
5880
5881         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5882
5883         if (num_result == 0) {
5884                 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5885                 return NT_STATUS_NO_SUCH_GROUP;
5886         }
5887
5888         if (num_result > 1) {
5889                 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5890                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5891         }
5892
5893         entry = ldap_first_entry(priv2ld(ldap_state), result);
5894         if (!entry) {
5895                 return NT_STATUS_UNSUCCESSFUL;
5896         }
5897
5898         /* here it is, retrieve the dn for later use */
5899         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5900         if (!dn) {
5901                 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5902                 return NT_STATUS_NO_MEMORY;
5903         }
5904
5905         smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5906
5907         smbldap_talloc_autofree_ldapmod(tmp_ctx, mods);
5908
5909         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5910         if (rc != LDAP_SUCCESS) {
5911                 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5912                         DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5913                         return NT_STATUS_MEMBER_IN_GROUP;
5914                 }
5915                 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5916                         DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5917                         return NT_STATUS_MEMBER_NOT_IN_GROUP;
5918                 }
5919                 return NT_STATUS_UNSUCCESSFUL;
5920         }
5921
5922         return NT_STATUS_OK;
5923 }
5924
5925 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5926                                      TALLOC_CTX *tmp_ctx,
5927                                      uint32_t group_rid,
5928                                      uint32_t member_rid)
5929 {
5930         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5931 }
5932 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5933                                      TALLOC_CTX *tmp_ctx,
5934                                      uint32_t group_rid,
5935                                      uint32_t member_rid)
5936 {
5937         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5938 }
5939
5940 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5941                                           TALLOC_CTX *mem_ctx,
5942                                           struct samu *sampass)
5943 {
5944         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5945         LDAPMessage *entry = NULL;
5946         LDAPMessage *result = NULL;
5947         uint32_t num_result;
5948         LDAPMod **mods = NULL;
5949         char *filter;
5950         char *escape_username;
5951         char *gidstr;
5952         const char *dn = NULL;
5953         gid_t gid;
5954         int rc;
5955
5956         DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5957
5958         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5959                 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5960                 return NT_STATUS_UNSUCCESSFUL;
5961         }
5962         gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5963         if (!gidstr) {
5964                 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5965                 return NT_STATUS_NO_MEMORY;
5966         }
5967
5968         escape_username = escape_ldap_string(talloc_tos(),
5969                                              pdb_get_username(sampass));
5970         if (escape_username== NULL) {
5971                 return NT_STATUS_NO_MEMORY;
5972         }
5973
5974         filter = talloc_asprintf(mem_ctx,
5975                                  "(&(uid=%s)"
5976                                  "(objectClass=%s)"
5977                                  "(objectClass=%s))",
5978                                  escape_username,
5979                                  LDAP_OBJ_POSIXACCOUNT,
5980                                  LDAP_OBJ_SAMBASAMACCOUNT);
5981
5982         TALLOC_FREE(escape_username);
5983
5984         if (filter == NULL) {
5985                 return NT_STATUS_NO_MEMORY;
5986         }
5987
5988         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5989         if (rc != LDAP_SUCCESS) {
5990                 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5991                 return NT_STATUS_UNSUCCESSFUL;
5992         }
5993         smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
5994
5995         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5996
5997         if (num_result == 0) {
5998                 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5999                 return NT_STATUS_NO_SUCH_USER;
6000         }
6001
6002         if (num_result > 1) {
6003                 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
6004                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
6005         }
6006
6007         entry = ldap_first_entry(priv2ld(ldap_state), result);
6008         if (!entry) {
6009                 return NT_STATUS_UNSUCCESSFUL;
6010         }
6011
6012         /* retrieve the dn for later use */
6013         dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
6014         if (!dn) {
6015                 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
6016                 return NT_STATUS_NO_MEMORY;
6017         }
6018
6019         /* remove the old one, and add the new one, this way we do not risk races */
6020         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
6021
6022         if (mods == NULL) {
6023                 return NT_STATUS_OK;
6024         }
6025
6026         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6027
6028         if (rc != LDAP_SUCCESS) {
6029                 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6030                          pdb_get_username(sampass), gidstr));
6031                 return NT_STATUS_UNSUCCESSFUL;
6032         }
6033
6034         flush_pwnam_cache();
6035
6036         return NT_STATUS_OK;
6037 }
6038
6039
6040 /**********************************************************************
6041  trusted domains functions
6042  *********************************************************************/
6043
6044 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6045                            const char *domain)
6046 {
6047         return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6048                                ldap_state->domain_dn);
6049 }
6050
6051 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6052                                   TALLOC_CTX *mem_ctx,
6053                                   const char *domain, LDAPMessage **entry)
6054 {
6055         int rc;
6056         char *filter;
6057         int scope = LDAP_SCOPE_SUBTREE;
6058         const char **attrs = NULL; /* NULL: get all attrs */
6059         int attrsonly = 0; /* 0: return values too */
6060         LDAPMessage *result = NULL;
6061         char *trusted_dn;
6062         uint32_t num_result;
6063
6064         filter = talloc_asprintf(talloc_tos(),
6065                                  "(&(objectClass=%s)(sambaDomainName=%s))",
6066                                  LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6067
6068         trusted_dn = trusteddom_dn(ldap_state, domain);
6069         if (trusted_dn == NULL) {
6070                 return False;
6071         }
6072         rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6073                             filter, attrs, attrsonly, &result);
6074
6075         if (result != NULL) {
6076                 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6077         }
6078
6079         if (rc == LDAP_NO_SUCH_OBJECT) {
6080                 *entry = NULL;
6081                 return True;
6082         }
6083
6084         if (rc != LDAP_SUCCESS) {
6085                 return False;
6086         }
6087
6088         num_result = ldap_count_entries(priv2ld(ldap_state), result);
6089
6090         if (num_result > 1) {
6091                 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6092                           "%s object for domain '%s'?!\n",
6093                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6094                 return False;
6095         }
6096
6097         if (num_result == 0) {
6098                 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6099                           "%s object for domain %s.\n",
6100                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6101                 *entry = NULL;
6102         } else {
6103                 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6104         }
6105
6106         return True;
6107 }
6108
6109 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6110                                       const char *domain,
6111                                       char** pwd,
6112                                       struct dom_sid *sid,
6113                                       time_t *pass_last_set_time)
6114 {
6115         struct ldapsam_privates *ldap_state =
6116                 (struct ldapsam_privates *)methods->private_data;
6117         LDAPMessage *entry = NULL;
6118
6119         DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6120
6121         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6122             (entry == NULL))
6123         {
6124                 return False;
6125         }
6126
6127         /* password */
6128         if (pwd != NULL) {
6129                 char *pwd_str;
6130                 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6131                                 entry, "sambaClearTextPassword", talloc_tos());
6132                 if (pwd_str == NULL) {
6133                         return False;
6134                 }
6135                 /* trusteddom_pw routines do not use talloc yet... */
6136                 *pwd = SMB_STRDUP(pwd_str);
6137                 if (*pwd == NULL) {
6138                         return False;
6139                 }
6140         }
6141
6142         /* last change time */
6143         if (pass_last_set_time != NULL) {
6144                 char *time_str;
6145                 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6146                                 entry, "sambaPwdLastSet", talloc_tos());
6147                 if (time_str == NULL) {
6148                         return False;
6149                 }
6150                 *pass_last_set_time = (time_t)atol(time_str);
6151         }
6152
6153         /* domain sid */
6154         if (sid != NULL) {
6155                 char *sid_str;
6156                 struct dom_sid dom_sid;
6157                 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6158                                                           entry, "sambaSID",
6159                                                           talloc_tos());
6160                 if (sid_str == NULL) {
6161                         return False;
6162                 }
6163                 if (!string_to_sid(&dom_sid, sid_str)) {
6164                         return False;
6165                 }
6166                 sid_copy(sid, &dom_sid);
6167         }
6168
6169         return True;
6170 }
6171
6172 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6173                                       const char* domain,
6174                                       const char* pwd,
6175                                       const struct dom_sid *sid)
6176 {
6177         struct ldapsam_privates *ldap_state =
6178                 (struct ldapsam_privates *)methods->private_data;
6179         LDAPMessage *entry = NULL;
6180         LDAPMod **mods = NULL;
6181         char *prev_pwd = NULL;
6182         char *trusted_dn = NULL;
6183         int rc;
6184
6185         DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6186
6187         /*
6188          * get the current entry (if there is one) in order to put the
6189          * current password into the previous password attribute
6190          */
6191         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6192                 return False;
6193         }
6194
6195         mods = NULL;
6196         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6197                          LDAP_OBJ_TRUSTDOM_PASSWORD);
6198         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6199                          domain);
6200         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6201                          sid_string_tos(sid));
6202         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6203                          talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6204         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6205                          "sambaClearTextPassword", pwd);
6206
6207         if (entry != NULL) {
6208                 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6209                                 entry, "sambaClearTextPassword", talloc_tos());
6210                 if (prev_pwd != NULL) {
6211                         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6212                                          "sambaPreviousClearTextPassword",
6213                                          prev_pwd);
6214                 }
6215         }
6216
6217         smbldap_talloc_autofree_ldapmod(talloc_tos(), mods);
6218
6219         trusted_dn = trusteddom_dn(ldap_state, domain);
6220         if (trusted_dn == NULL) {
6221                 return False;
6222         }
6223         if (entry == NULL) {
6224                 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6225         } else {
6226                 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6227         }
6228
6229         if (rc != LDAP_SUCCESS) {
6230                 DEBUG(1, ("error writing trusted domain password!\n"));
6231                 return False;
6232         }
6233
6234         return True;
6235 }
6236
6237 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6238                                       const char *domain)
6239 {
6240         int rc;
6241         struct ldapsam_privates *ldap_state =
6242                 (struct ldapsam_privates *)methods->private_data;
6243         LDAPMessage *entry = NULL;
6244         const char *trusted_dn;
6245
6246         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6247                 return False;
6248         }
6249
6250         if (entry == NULL) {
6251                 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6252                           "%s\n", domain));
6253                 return True;
6254         }
6255
6256         trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6257                                        entry);
6258         if (trusted_dn == NULL) {
6259                 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6260                 return False;
6261         }
6262
6263         rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6264         if (rc != LDAP_SUCCESS) {
6265                 return False;
6266         }
6267
6268         return True;
6269 }
6270
6271 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6272                                          TALLOC_CTX *mem_ctx,
6273                                          uint32_t *num_domains,
6274                                          struct trustdom_info ***domains)
6275 {
6276         int rc;
6277         struct ldapsam_privates *ldap_state =
6278                 (struct ldapsam_privates *)methods->private_data;
6279         char *filter;
6280         int scope = LDAP_SCOPE_SUBTREE;
6281         const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6282         int attrsonly = 0; /* 0: return values too */
6283         LDAPMessage *result = NULL;
6284         LDAPMessage *entry = NULL;
6285
6286         filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6287                                  LDAP_OBJ_TRUSTDOM_PASSWORD);
6288
6289         rc = smbldap_search(ldap_state->smbldap_state,
6290                             ldap_state->domain_dn,
6291                             scope,
6292                             filter,
6293                             attrs,
6294                             attrsonly,
6295                             &result);
6296
6297         if (result != NULL) {
6298                 smbldap_talloc_autofree_ldapmsg(mem_ctx, result);
6299         }
6300
6301         if (rc != LDAP_SUCCESS) {
6302                 return NT_STATUS_UNSUCCESSFUL;
6303         }
6304
6305         *num_domains = 0;
6306         if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6307                 DEBUG(1, ("talloc failed\n"));
6308                 return NT_STATUS_NO_MEMORY;
6309         }
6310
6311         for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6312              entry != NULL;
6313              entry = ldap_next_entry(priv2ld(ldap_state), entry))
6314         {
6315                 char *dom_name, *dom_sid_str;
6316                 struct trustdom_info *dom_info;
6317
6318                 dom_info = talloc(*domains, struct trustdom_info);
6319                 if (dom_info == NULL) {
6320                         DEBUG(1, ("talloc failed\n"));
6321                         return NT_STATUS_NO_MEMORY;
6322                 }
6323
6324                 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6325                                                            entry,
6326                                                            "sambaDomainName",
6327                                                            talloc_tos());
6328                 if (dom_name == NULL) {
6329                         DEBUG(1, ("talloc failed\n"));
6330                         return NT_STATUS_NO_MEMORY;
6331                 }
6332                 dom_info->name = dom_name;
6333
6334                 dom_sid_str = smbldap_talloc_single_attribute(
6335                                         priv2ld(ldap_state), entry, "sambaSID",
6336                                         talloc_tos());
6337                 if (dom_sid_str == NULL) {
6338                         DEBUG(1, ("talloc failed\n"));
6339                         return NT_STATUS_NO_MEMORY;
6340                 }
6341                 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6342                         DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6343                                   dom_sid_str));
6344                         return NT_STATUS_UNSUCCESSFUL;
6345                 }
6346
6347                 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6348                              domains, num_domains);
6349
6350                 if (*domains == NULL) {
6351                         DEBUG(1, ("talloc failed\n"));
6352                         return NT_STATUS_NO_MEMORY;
6353                 }
6354         }
6355
6356         DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6357         return NT_STATUS_OK;
6358 }
6359
6360
6361 /**********************************************************************
6362  Housekeeping
6363  *********************************************************************/
6364
6365 static void free_private_data(void **vp) 
6366 {
6367         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6368
6369         smbldap_free_struct(&(*ldap_state)->smbldap_state);
6370
6371         if ((*ldap_state)->result != NULL) {
6372                 ldap_msgfree((*ldap_state)->result);
6373                 (*ldap_state)->result = NULL;
6374         }
6375         if ((*ldap_state)->domain_dn != NULL) {
6376                 SAFE_FREE((*ldap_state)->domain_dn);
6377         }
6378
6379         *ldap_state = NULL;
6380
6381         /* No need to free any further, as it is talloc()ed */
6382 }
6383
6384 /*********************************************************************
6385  Intitalise the parts of the pdb_methods structure that are common to 
6386  all pdb_ldap modes
6387 *********************************************************************/
6388
6389 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6390 {
6391         NTSTATUS nt_status;
6392         struct ldapsam_privates *ldap_state;
6393         char *bind_dn = NULL;
6394         char *bind_secret = NULL;
6395
6396         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6397                 return nt_status;
6398         }
6399
6400         (*pdb_method)->name = "ldapsam";
6401
6402         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6403         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6404         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6405         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6406         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6407         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6408
6409         (*pdb_method)->getgrsid = ldapsam_getgrsid;
6410         (*pdb_method)->getgrgid = ldapsam_getgrgid;
6411         (*pdb_method)->getgrnam = ldapsam_getgrnam;
6412         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6413         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6414         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6415         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6416
6417         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6418         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6419
6420         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6421
6422         (*pdb_method)->capabilities = ldapsam_capabilities;
6423         (*pdb_method)->new_rid = ldapsam_new_rid;
6424
6425         (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6426         (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6427         (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6428         (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6429
6430         /* TODO: Setup private data and free */
6431
6432         if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6433                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6434                 return NT_STATUS_NO_MEMORY;
6435         }
6436
6437         if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
6438                 DEBUG(0, ("pdb_init_ldapsam_common: Failed to retrieve LDAP password from secrets.tdb\n"));
6439                 return NT_STATUS_NO_MEMORY;
6440         }
6441
6442         nt_status = smbldap_init(*pdb_method, pdb_get_tevent_context(),
6443                                  location, false, bind_dn, bind_secret,
6444                                  &ldap_state->smbldap_state);
6445         memset(bind_secret, '\0', strlen(bind_secret));
6446         SAFE_FREE(bind_secret);
6447         SAFE_FREE(bind_dn);
6448         if ( !NT_STATUS_IS_OK(nt_status) ) {
6449                 return nt_status;
6450         }
6451
6452         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6453                 return NT_STATUS_NO_MEMORY;
6454         }
6455
6456         (*pdb_method)->private_data = ldap_state;
6457
6458         (*pdb_method)->free_private_data = free_private_data;
6459
6460         return NT_STATUS_OK;
6461 }
6462
6463 static bool ldapsam_is_responsible_for_wellknown(struct pdb_methods *m)
6464 {
6465         return true;
6466 }
6467
6468 /**********************************************************************
6469  Initialise the normal mode for pdb_ldap
6470  *********************************************************************/
6471
6472 NTSTATUS pdb_ldapsam_init_common(struct pdb_methods **pdb_method,
6473                                  const char *location)
6474 {
6475         NTSTATUS nt_status;
6476         struct ldapsam_privates *ldap_state = NULL;
6477         uint32_t alg_rid_base;
6478         char *alg_rid_base_string = NULL;
6479         LDAPMessage *result = NULL;
6480         LDAPMessage *entry = NULL;
6481         struct dom_sid ldap_domain_sid;
6482         struct dom_sid secrets_domain_sid;
6483         char *domain_sid_string = NULL;
6484         char *dn = NULL;
6485         char *uri = talloc_strdup( NULL, location );
6486
6487         trim_char( uri, '\"', '\"' );
6488         nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6489
6490         TALLOC_FREE(uri);
6491
6492         if (!NT_STATUS_IS_OK(nt_status)) {
6493                 return nt_status;
6494         }
6495
6496         (*pdb_method)->name = "ldapsam";
6497
6498         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6499         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6500         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6501         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6502         (*pdb_method)->search_users = ldapsam_search_users;
6503         (*pdb_method)->search_groups = ldapsam_search_groups;
6504         (*pdb_method)->search_aliases = ldapsam_search_aliases;
6505         (*pdb_method)->is_responsible_for_wellknown =
6506                                         ldapsam_is_responsible_for_wellknown;
6507
6508         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6509                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6510                 (*pdb_method)->enum_group_memberships =
6511                         ldapsam_enum_group_memberships;
6512                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6513                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6514                 (*pdb_method)->id_to_sid = ldapsam_id_to_sid;
6515
6516                 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6517                         (*pdb_method)->create_user = ldapsam_create_user;
6518                         (*pdb_method)->delete_user = ldapsam_delete_user;
6519                         (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6520                         (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6521                         (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6522                         (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6523                         (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6524                 }
6525         }
6526
6527         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6528         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6529
6530         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6531
6532         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6533                                                &result,
6534                                                ldap_state->domain_name, True);
6535
6536         if ( !NT_STATUS_IS_OK(nt_status) ) {
6537                 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6538                           "info, nor add one to the domain. "
6539                           "We cannot work reliably without it.\n"));
6540                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6541         }
6542
6543         /* Given that the above might fail, everything below this must be
6544          * optional */
6545
6546         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6547                                  result);
6548         if (!entry) {
6549                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6550                           "entry\n"));
6551                 ldap_msgfree(result);
6552                 return NT_STATUS_UNSUCCESSFUL;
6553         }
6554
6555         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6556         if (!dn) {
6557                 ldap_msgfree(result);
6558                 return NT_STATUS_UNSUCCESSFUL;
6559         }
6560
6561         ldap_state->domain_dn = smb_xstrdup(dn);
6562         TALLOC_FREE(dn);
6563
6564         domain_sid_string = smbldap_talloc_single_attribute(
6565                     ldap_state->smbldap_state->ldap_struct,
6566                     entry,
6567                     get_userattr_key2string(ldap_state->schema_ver,
6568                                             LDAP_ATTR_USER_SID),
6569                     talloc_tos());
6570
6571         if (domain_sid_string) {
6572                 bool found_sid;
6573                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6574                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6575                                   "read as a valid SID\n", domain_sid_string));
6576                         ldap_msgfree(result);
6577                         TALLOC_FREE(domain_sid_string);
6578                         return NT_STATUS_INVALID_PARAMETER;
6579                 }
6580                 found_sid = PDB_secrets_fetch_domain_sid(ldap_state->domain_name,
6581                                                      &secrets_domain_sid);
6582                 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6583                                              &ldap_domain_sid)) {
6584                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6585                                   "%s based on pdb_ldap results %s -> %s\n",
6586                                   ldap_state->domain_name,
6587                                   sid_string_dbg(&secrets_domain_sid),
6588                                   sid_string_dbg(&ldap_domain_sid)));
6589
6590                         /* reset secrets.tdb sid */
6591                         PDB_secrets_store_domain_sid(ldap_state->domain_name,
6592                                                  &ldap_domain_sid);
6593                         DEBUG(1, ("New global sam SID: %s\n",
6594                                   sid_string_dbg(get_global_sam_sid())));
6595                 }
6596                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6597                 TALLOC_FREE(domain_sid_string);
6598         }
6599
6600         alg_rid_base_string = smbldap_talloc_single_attribute(
6601                     ldap_state->smbldap_state->ldap_struct,
6602                     entry,
6603                     get_attr_key2string( dominfo_attr_list,
6604                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6605                     talloc_tos());
6606         if (alg_rid_base_string) {
6607                 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6608                 if (alg_rid_base != algorithmic_rid_base()) {
6609                         DEBUG(0, ("The value of 'algorithmic RID base' has "
6610                                   "changed since the LDAP\n"
6611                                   "database was initialised.  Aborting. \n"));
6612                         ldap_msgfree(result);
6613                         TALLOC_FREE(alg_rid_base_string);
6614                         return NT_STATUS_UNSUCCESSFUL;
6615                 }
6616                 TALLOC_FREE(alg_rid_base_string);
6617         }
6618         ldap_msgfree(result);
6619
6620         return NT_STATUS_OK;
6621 }
6622
6623 NTSTATUS pdb_ldapsam_init(void)
6624 {
6625         NTSTATUS nt_status;
6626
6627         nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION,
6628                                         "ldapsam",
6629                                         pdb_ldapsam_init_common);
6630         if (!NT_STATUS_IS_OK(nt_status)) {
6631                 return nt_status;
6632         }
6633
6634         /* Let pdb_nds register backends */
6635         pdb_nds_init();
6636
6637         return NT_STATUS_OK;
6638 }