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