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