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