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