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