638a4a290f1d06e2d4b2e5af4fc7f57bb9617d52
[obnox/samba/samba-obnox.git] / source3 / passdb / pdb_samba_dsdb.c
1 /*
2    Unix SMB/CIFS implementation.
3    pdb glue module for direct access to the dsdb via LDB APIs
4    Copyright (C) Volker Lendecke 2009-2011
5    Copyright (C) Andrew Bartlett 2010-2012
6    Copyright (C) Matthias Dieter Wallnöfer                 2009
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /* This module, is a port of Volker's pdb_ads to ldb and DSDB APIs */
23
24 #include "includes.h"
25 #include "source3/include/passdb.h"
26 #include "source4/dsdb/samdb/samdb.h"
27 #include "ldb_errors.h"
28 #include "libcli/security/dom_sid.h"
29 #include "source4/winbind/idmap.h"
30 #include "librpc/gen_ndr/ndr_security.h"
31 #include "librpc/gen_ndr/ndr_drsblobs.h"
32 #include "librpc/gen_ndr/ndr_lsa.h"
33 #include "libds/common/flag_mapping.h"
34 #include "source4/lib/events/events.h"
35 #include "source4/auth/session.h"
36 #include "source4/auth/system_session_proto.h"
37 #include "lib/param/param.h"
38 #include "source4/dsdb/common/util.h"
39 #include "source3/include/secrets.h"
40 #include "source4/auth/auth_sam.h"
41 #include "auth/credentials/credentials.h"
42
43 struct pdb_samba_dsdb_state {
44         struct tevent_context *ev;
45         struct ldb_context *ldb;
46         struct idmap_context *idmap_ctx;
47         struct loadparm_context *lp_ctx;
48 };
49
50 static NTSTATUS pdb_samba_dsdb_getsampwsid(struct pdb_methods *m,
51                                     struct samu *sam_acct,
52                                     const struct dom_sid *sid);
53 static NTSTATUS pdb_samba_dsdb_getsamupriv(struct pdb_samba_dsdb_state *state,
54                                     const char *filter,
55                                     TALLOC_CTX *mem_ctx,
56                                     struct ldb_message **pmsg);
57 static bool pdb_samba_dsdb_sid_to_id(struct pdb_methods *m, const struct dom_sid *sid,
58                                  struct unixid *id);
59
60 static bool pdb_samba_dsdb_pull_time(struct ldb_message *msg, const char *attr,
61                               time_t *ptime)
62 {
63         uint64_t tmp;
64         if (! ldb_msg_find_element(msg, attr)) {
65                 return false;
66         }
67         tmp = ldb_msg_find_attr_as_uint64(msg, attr, 0);
68         *ptime = nt_time_to_unix(tmp);
69         return true;
70 }
71
72 static struct pdb_domain_info *pdb_samba_dsdb_get_domain_info(
73         struct pdb_methods *m, TALLOC_CTX *mem_ctx)
74 {
75         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
76                 m->private_data, struct pdb_samba_dsdb_state);
77         struct pdb_domain_info *info;
78         struct dom_sid *domain_sid;
79         struct ldb_dn *forest_dn, *domain_dn;
80         struct ldb_result *dom_res = NULL;
81         const char *dom_attrs[] = {
82                 "objectSid",
83                 "objectGUID",
84                 "fSMORoleOwner",
85                 NULL
86         };
87         char *p;
88         int ret;
89
90         info = talloc(mem_ctx, struct pdb_domain_info);
91         if (info == NULL) {
92                 return NULL;
93         }
94
95         domain_dn = ldb_get_default_basedn(state->ldb);
96
97         ret = ldb_search(state->ldb, info, &dom_res,
98                          domain_dn, LDB_SCOPE_BASE, dom_attrs, NULL);
99         if (ret != LDB_SUCCESS) {
100                 goto fail;
101         }
102         if (dom_res->count != 1) {
103                 goto fail;
104         }
105
106         info->guid = samdb_result_guid(dom_res->msgs[0], "objectGUID");
107
108         domain_sid = samdb_result_dom_sid(state, dom_res->msgs[0], "objectSid");
109         if (!domain_sid) {
110                 goto fail;
111         }
112         info->sid = *domain_sid;
113
114         TALLOC_FREE(dom_res);
115
116         info->name = talloc_strdup(info, lpcfg_sam_name(state->lp_ctx));
117         info->dns_domain = ldb_dn_canonical_string(info, domain_dn);
118
119         if (!info->dns_domain) {
120                 goto fail;
121         }
122         p = strchr(info->dns_domain, '/');
123         if (p) {
124                 *p = '\0';
125         }
126
127         forest_dn = ldb_get_root_basedn(state->ldb);
128         if (!forest_dn) {
129                 goto fail;
130         }
131
132         info->dns_forest = ldb_dn_canonical_string(info, forest_dn);
133         if (!info->dns_forest) {
134                 goto fail;
135         }
136         p = strchr(info->dns_forest, '/');
137         if (p) {
138                 *p = '\0';
139         }
140
141         return info;
142
143 fail:
144         TALLOC_FREE(dom_res);
145         TALLOC_FREE(info);
146         return NULL;
147 }
148
149 static struct ldb_message *pdb_samba_dsdb_get_samu_private(
150         struct pdb_methods *m, struct samu *sam)
151 {
152         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
153                 m->private_data, struct pdb_samba_dsdb_state);
154         struct ldb_message *msg;
155         char *sidstr, *filter;
156         NTSTATUS status;
157
158         msg = (struct ldb_message *)
159                 pdb_get_backend_private_data(sam, m);
160
161         if (msg != NULL) {
162                 return talloc_get_type_abort(msg, struct ldb_message);
163         }
164
165         sidstr = dom_sid_string(talloc_tos(), pdb_get_user_sid(sam));
166         if (sidstr == NULL) {
167                 return NULL;
168         }
169
170         filter = talloc_asprintf(
171                 talloc_tos(), "(&(objectsid=%s)(objectclass=user))", sidstr);
172         TALLOC_FREE(sidstr);
173         if (filter == NULL) {
174                 return NULL;
175         }
176
177         status = pdb_samba_dsdb_getsamupriv(state, filter, sam, &msg);
178         TALLOC_FREE(filter);
179         if (!NT_STATUS_IS_OK(status)) {
180                 return NULL;
181         }
182
183         return msg;
184 }
185
186 static NTSTATUS pdb_samba_dsdb_init_sam_from_priv(struct pdb_methods *m,
187                                            struct samu *sam,
188                                            struct ldb_message *msg)
189 {
190         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
191                 m->private_data, struct pdb_samba_dsdb_state);
192         TALLOC_CTX *frame = talloc_stackframe();
193         NTSTATUS status = NT_STATUS_INTERNAL_DB_CORRUPTION;
194         const char *str;
195         time_t tmp_time;
196         struct dom_sid *sid, group_sid;
197         uint64_t n;
198         const DATA_BLOB *blob;
199
200         str = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
201         if (str == NULL) {
202                 DEBUG(10, ("no samAccountName\n"));
203                 goto fail;
204         }
205         pdb_set_username(sam, str, PDB_SET);
206
207         if (pdb_samba_dsdb_pull_time(msg, "lastLogon", &tmp_time)) {
208                 pdb_set_logon_time(sam, tmp_time, PDB_SET);
209         }
210         if (pdb_samba_dsdb_pull_time(msg, "lastLogoff", &tmp_time)) {
211                 pdb_set_logoff_time(sam, tmp_time, PDB_SET);
212         }
213         if (pdb_samba_dsdb_pull_time(msg, "pwdLastSet", &tmp_time)) {
214                 pdb_set_pass_last_set_time(sam, tmp_time, PDB_SET);
215         }
216         if (pdb_samba_dsdb_pull_time(msg, "accountExpires", &tmp_time)) {
217                 pdb_set_kickoff_time(sam, tmp_time, PDB_SET);
218         }
219
220         str = ldb_msg_find_attr_as_string(msg, "displayName",
221                                             NULL);
222         if (str != NULL) {
223                 pdb_set_fullname(sam, str, PDB_SET);
224         }
225
226         str = ldb_msg_find_attr_as_string(msg, "homeDirectory",
227                                             NULL);
228         if (str != NULL) {
229                 pdb_set_homedir(sam, str, PDB_SET);
230         }
231
232         str = ldb_msg_find_attr_as_string(msg, "homeDrive", NULL);
233         if (str != NULL) {
234                 pdb_set_dir_drive(sam, str, PDB_SET);
235         }
236
237         str = ldb_msg_find_attr_as_string(msg, "scriptPath", NULL);
238         if (str != NULL) {
239                 pdb_set_logon_script(sam, str, PDB_SET);
240         }
241
242         str = ldb_msg_find_attr_as_string(msg, "profilePath",
243                                             NULL);
244         if (str != NULL) {
245                 pdb_set_profile_path(sam, str, PDB_SET);
246         }
247
248         str = ldb_msg_find_attr_as_string(msg, "comment",
249                                             NULL);
250         if (str != NULL) {
251                 pdb_set_comment(sam, str, PDB_SET);
252         }
253
254         str = ldb_msg_find_attr_as_string(msg, "description",
255                                             NULL);
256         if (str != NULL) {
257                 pdb_set_acct_desc(sam, str, PDB_SET);
258         }
259
260         str = ldb_msg_find_attr_as_string(msg, "userWorkstations",
261                                             NULL);
262         if (str != NULL) {
263                 pdb_set_workstations(sam, str, PDB_SET);
264         }
265
266         blob = ldb_msg_find_ldb_val(msg, "userParameters");
267         if (blob != NULL) {
268                 str = base64_encode_data_blob(frame, *blob);
269                 if (str == NULL) {
270                         DEBUG(0, ("base64_encode_data_blob() failed\n"));
271                         goto fail;
272                 }
273                 pdb_set_munged_dial(sam, str, PDB_SET);
274         }
275
276         sid = samdb_result_dom_sid(talloc_tos(), msg, "objectSid");
277         if (!sid) {
278                 DEBUG(10, ("Could not pull SID\n"));
279                 goto fail;
280         }
281         pdb_set_user_sid(sam, sid, PDB_SET);
282
283         n = samdb_result_acct_flags(msg, "msDS-User-Account-Control-Computed");
284         if (n == 0) {
285                 DEBUG(10, ("Could not pull userAccountControl\n"));
286                 goto fail;
287         }
288         pdb_set_acct_ctrl(sam, n, PDB_SET);
289
290         blob = ldb_msg_find_ldb_val(msg, "unicodePwd");
291         if (blob) {
292                 if (blob->length != NT_HASH_LEN) {
293                         DEBUG(0, ("Got NT hash of length %d, expected %d\n",
294                                   (int)blob->length, NT_HASH_LEN));
295                         goto fail;
296                 }
297                 pdb_set_nt_passwd(sam, blob->data, PDB_SET);
298         }
299
300         blob = ldb_msg_find_ldb_val(msg, "dBCSPwd");
301         if (blob) {
302                 if (blob->length != LM_HASH_LEN) {
303                         DEBUG(0, ("Got LM hash of length %d, expected %d\n",
304                                   (int)blob->length, LM_HASH_LEN));
305                         goto fail;
306                 }
307                 pdb_set_lanman_passwd(sam, blob->data, PDB_SET);
308         }
309
310         n = ldb_msg_find_attr_as_uint(msg, "primaryGroupID", 0);
311         if (n == 0) {
312                 DEBUG(10, ("Could not pull primaryGroupID\n"));
313                 goto fail;
314         }
315         sid_compose(&group_sid, samdb_domain_sid(state->ldb), n);
316         pdb_set_group_sid(sam, &group_sid, PDB_SET);
317
318         status = NT_STATUS_OK;
319 fail:
320         TALLOC_FREE(frame);
321         return status;
322 }
323
324 static bool pdb_samba_dsdb_add_time(struct ldb_message *msg,
325                                 const char *attrib, time_t t)
326 {
327         uint64_t nt_time;
328
329         unix_to_nt_time(&nt_time, t);
330
331         return ldb_msg_add_fmt(msg, attrib, "%llu", (unsigned long long) nt_time);
332 }
333
334 static int pdb_samba_dsdb_replace_by_sam(struct pdb_samba_dsdb_state *state,
335                                      bool (*need_update)(const struct samu *,
336                                                          enum pdb_elements),
337                                      struct ldb_dn *dn,
338                                      struct samu *sam)
339 {
340         TALLOC_CTX *frame = talloc_stackframe();
341         int ret = LDB_SUCCESS;
342         const char *pw;
343         struct ldb_message *msg;
344         struct ldb_request *req;
345         uint32_t dsdb_flags = 0;
346         /* TODO: All fields :-) */
347
348         msg = ldb_msg_new(frame);
349         if (!msg) {
350                 talloc_free(frame);
351                 return false;
352         }
353
354         msg->dn = dn;
355
356         /* build modify request */
357         ret = ldb_build_mod_req(&req, state->ldb, frame, msg, NULL, NULL,
358                                 ldb_op_default_callback,
359                                 NULL);
360         if (ret != LDB_SUCCESS) {
361                 talloc_free(frame);
362                 return ret;
363         }
364
365         /* If we set a plaintext password, the system will
366          * force the pwdLastSet to now() */
367         if (need_update(sam, PDB_PASSLASTSET)) {
368                 dsdb_flags = DSDB_PASSWORD_BYPASS_LAST_SET;
369
370                 ret |= pdb_samba_dsdb_add_time(msg, "pwdLastSet",
371                                            pdb_get_pass_last_set_time(sam));
372         }
373
374         pw = pdb_get_plaintext_passwd(sam);
375         if (need_update(sam, PDB_PLAINTEXT_PW)) {
376                 struct ldb_val pw_utf16;
377                 if (pw == NULL) {
378                         talloc_free(frame);
379                         return LDB_ERR_OPERATIONS_ERROR;
380                 }
381
382                 if (!convert_string_talloc(msg,
383                                            CH_UNIX, CH_UTF16,
384                                            pw, strlen(pw),
385                                            (void *)&pw_utf16.data,
386                                            &pw_utf16.length)) {
387                         talloc_free(frame);
388                         return LDB_ERR_OPERATIONS_ERROR;
389                 }
390                 ret |= ldb_msg_add_value(msg, "clearTextPassword", &pw_utf16, NULL);
391         } else {
392                 bool changed_lm_pw = false;
393                 bool changed_nt_pw = false;
394                 bool changed_history = false;
395                 if (need_update(sam, PDB_LMPASSWD)) {
396                         struct ldb_val val;
397                         val.data = discard_const_p(uint8_t, pdb_get_lanman_passwd(sam));
398                         if (!val.data) {
399                                 samdb_msg_add_delete(state->ldb, msg, msg,
400                                                      "dBCSPwd");
401                         } else {
402                                 val.length = LM_HASH_LEN;
403                                 ret |= ldb_msg_add_value(msg, "dBCSPwd", &val, NULL);
404                         }
405                         changed_lm_pw = true;
406                 }
407                 if (need_update(sam, PDB_NTPASSWD)) {
408                         struct ldb_val val;
409                         val.data = discard_const_p(uint8_t, pdb_get_nt_passwd(sam));
410                         if (!val.data) {
411                                 samdb_msg_add_delete(state->ldb, msg, msg,
412                                                      "unicodePwd");
413                         } else {
414                                 val.length = NT_HASH_LEN;
415                                 ret |= ldb_msg_add_value(msg, "unicodePwd", &val, NULL);
416                         }
417                         changed_nt_pw = true;
418                 }
419
420                 /* Try to ensure we don't get out of sync */
421                 if (changed_lm_pw && !changed_nt_pw) {
422                         samdb_msg_add_delete(state->ldb, msg, msg,
423                                              "unicodePwd");
424                 } else if (changed_nt_pw && !changed_lm_pw) {
425                         samdb_msg_add_delete(state->ldb, msg, msg,
426                                              "dBCSPwd");
427                 }
428                 if (changed_lm_pw || changed_nt_pw) {
429                         samdb_msg_add_delete(state->ldb, msg, msg,
430                                              "supplementalCredentials");
431
432                 }
433
434                 if (need_update(sam, PDB_PWHISTORY)) {
435                         uint32_t current_hist_len;
436                         const uint8_t *history = pdb_get_pw_history(sam, &current_hist_len);
437
438                         bool invalid_history = false;
439                         struct samr_Password *history_hashes = talloc_array(talloc_tos(), struct samr_Password,
440                                                                             current_hist_len);
441                         if (!history) {
442                                 invalid_history = true;
443                         } else {
444                                 unsigned int i;
445                                 static const uint8_t zeros[16];
446                                 /* Parse the history into the correct format */
447                                 for (i = 0; i < current_hist_len; i++) {
448                                         if (memcmp(&history[i*PW_HISTORY_ENTRY_LEN], zeros, 16) != 0) {
449                                                 /* If the history is in the old format, with a salted hash, then we can't migrate it to AD format */
450                                                 invalid_history = true;
451                                                 break;
452                                         }
453                                         /* Copy out the 2nd 16 bytes of the 32 byte password history, containing the NT hash */
454                                         memcpy(history_hashes[i].hash,
455                                                &history[(i*PW_HISTORY_ENTRY_LEN) + PW_HISTORY_SALT_LEN],
456                                                sizeof(history_hashes[i].hash));
457                                 }
458                         }
459                         if (invalid_history) {
460                                 ret |= samdb_msg_add_delete(state->ldb, msg, msg,
461                                                      "ntPwdHistory");
462
463                                 ret |= samdb_msg_add_delete(state->ldb, msg, msg,
464                                                      "lmPwdHistory");
465                         } else {
466                                 ret |= samdb_msg_add_hashes(state->ldb, msg, msg,
467                                                             "ntPwdHistory",
468                                                             history_hashes,
469                                                             current_hist_len);
470                         }
471                         changed_history = true;
472                 }
473                 if (changed_lm_pw || changed_nt_pw || changed_history) {
474                         /* These attributes can only be modified directly by using a special control */
475                         dsdb_flags = DSDB_BYPASS_PASSWORD_HASH;
476                 }
477         }
478
479         /* PDB_USERSID is only allowed on ADD, handled in caller */
480         if (need_update(sam, PDB_GROUPSID)) {
481                 const struct dom_sid *sid = pdb_get_group_sid(sam);
482                 uint32_t rid;
483                 NTSTATUS status = dom_sid_split_rid(NULL, sid, NULL, &rid);
484                 if (!NT_STATUS_IS_OK(status)) {
485                         talloc_free(frame);
486                         return LDB_ERR_OPERATIONS_ERROR;
487                 }
488                 if (!dom_sid_in_domain(samdb_domain_sid(state->ldb), sid)) {
489                         talloc_free(frame);
490                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
491                 }
492                 ret |= samdb_msg_add_uint(state->ldb, msg, msg, "primaryGroupID", rid);
493         }
494         if (need_update(sam, PDB_FULLNAME)) {
495                 ret |= ldb_msg_add_string(msg, "displayName", pdb_get_fullname(sam));
496         }
497
498         if (need_update(sam, PDB_SMBHOME)) {
499                 ret |= ldb_msg_add_string(msg, "homeDirectory",
500                                           pdb_get_homedir(sam));
501         }
502
503         if (need_update(sam, PDB_PROFILE)) {
504                 ret |= ldb_msg_add_string(msg, "profilePath",
505                                           pdb_get_profile_path(sam));
506         }
507
508         if (need_update(sam, PDB_DRIVE)) {
509                 ret |= ldb_msg_add_string(msg, "homeDrive",
510                                           pdb_get_dir_drive(sam));
511         }
512
513         if (need_update(sam, PDB_LOGONSCRIPT)) {
514                 ret |= ldb_msg_add_string(msg, "scriptPath",
515                                           pdb_get_logon_script(sam));
516         }
517
518         if (need_update(sam, PDB_KICKOFFTIME)) {
519                 ret |= pdb_samba_dsdb_add_time(msg, "accountExpires",
520                                         pdb_get_kickoff_time(sam));
521         }
522
523         if (need_update(sam, PDB_LOGONTIME)) {
524                 ret |= pdb_samba_dsdb_add_time(msg, "lastLogon",
525                                         pdb_get_logon_time(sam));
526         }
527
528         if (need_update(sam, PDB_LOGOFFTIME)) {
529                 ret |= pdb_samba_dsdb_add_time(msg, "lastLogoff",
530                                         pdb_get_logoff_time(sam));
531         }
532
533         if (need_update(sam, PDB_USERNAME)) {
534                 ret |= ldb_msg_add_string(msg, "samAccountName",
535                                           pdb_get_username(sam));
536         }
537
538         if (need_update(sam, PDB_HOURSLEN) || need_update(sam, PDB_HOURS)) {
539                 struct ldb_val hours = data_blob_const(pdb_get_hours(sam), pdb_get_hours_len(sam));
540                 ret |= ldb_msg_add_value(msg, "logonHours",
541                                          &hours, NULL);
542         }
543
544         if (need_update(sam, PDB_ACCTCTRL)) {
545                 ret |= samdb_msg_add_acct_flags(state->ldb, msg, msg,
546                                                 "userAccountControl", pdb_get_acct_ctrl(sam));
547         }
548
549         if (need_update(sam, PDB_COMMENT)) {
550                 ret |= ldb_msg_add_string(msg, "comment",
551                                           pdb_get_comment(sam));
552         }
553
554         if (need_update(sam, PDB_ACCTDESC)) {
555                 ret |= ldb_msg_add_string(msg, "description",
556                                           pdb_get_acct_desc(sam));
557         }
558
559         if (need_update(sam, PDB_WORKSTATIONS)) {
560                 ret |= ldb_msg_add_string(msg, "userWorkstations",
561                                           pdb_get_workstations(sam));
562         }
563
564         /* This will need work, it is actually a UTF8 'string' with internal NULLs, to handle TS parameters */
565         if (need_update(sam, PDB_MUNGEDDIAL)) {
566                 const char *base64_munged_dial = NULL;
567
568                 base64_munged_dial = pdb_get_munged_dial(sam);
569                 if (base64_munged_dial != NULL && strlen(base64_munged_dial) > 0) {
570                         struct ldb_val blob;
571
572                         blob = base64_decode_data_blob_talloc(msg,
573                                                         base64_munged_dial);
574                         if (blob.data == NULL) {
575                                 DEBUG(0, ("Failed to decode userParameters from "
576                                           "munged dialback string[%s] for %s\n",
577                                           base64_munged_dial,
578                                           ldb_dn_get_linearized(msg->dn)));
579                                 talloc_free(frame);
580                                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
581                         }
582                         ret |= ldb_msg_add_steal_value(msg, "userParameters",
583                                                        &blob);
584                 }
585         }
586
587         if (need_update(sam, PDB_COUNTRY_CODE)) {
588                 ret |= ldb_msg_add_fmt(msg, "countryCode",
589                                        "%i", (int)pdb_get_country_code(sam));
590         }
591
592         if (need_update(sam, PDB_CODE_PAGE)) {
593                 ret |= ldb_msg_add_fmt(msg, "codePage",
594                                        "%i", (int)pdb_get_code_page(sam));
595         }
596
597         /* Not yet handled here or not meaningful for modifies on a Samba_Dsdb backend:
598         PDB_BAD_PASSWORD_TIME,
599         PDB_CANCHANGETIME, - these are calculated per policy, not stored
600         PDB_DOMAIN,
601         PDB_NTUSERNAME, - this makes no sense, and never really did
602         PDB_LOGONDIVS,
603         PDB_USERSID, - Handled in pdb_samba_dsdb_add_sam_account()
604         PDB_FIELDS_PRESENT,
605         PDB_BAD_PASSWORD_COUNT,
606         PDB_LOGON_COUNT,
607         PDB_UNKNOWN6,
608         PDB_BACKEND_PRIVATE_DATA,
609
610  */
611         if (ret != LDB_SUCCESS) {
612                 talloc_free(frame);
613                 return LDB_ERR_OPERATIONS_ERROR;
614         }
615
616         if (msg->num_elements == 0) {
617                 talloc_free(frame);
618                 /* Nothing to do, just return success */
619                 return LDB_SUCCESS;
620         }
621
622         ret = dsdb_replace(state->ldb, msg, dsdb_flags);
623
624         if (ret != LDB_SUCCESS) {
625                 DEBUG(0,("Failed to modify account record %s to set user attributes: %s\n",
626                          ldb_dn_get_linearized(msg->dn),
627                          ldb_errstring(state->ldb)));
628         }
629
630         talloc_free(frame);
631         return ret;
632 }
633
634 static NTSTATUS pdb_samba_dsdb_getsamupriv(struct pdb_samba_dsdb_state *state,
635                                     const char *filter,
636                                     TALLOC_CTX *mem_ctx,
637                                     struct ldb_message **msg)
638 {
639         const char * attrs[] = {
640                 "lastLogon", "lastLogoff", "pwdLastSet", "accountExpires",
641                 "sAMAccountName", "displayName", "homeDirectory",
642                 "homeDrive", "scriptPath", "profilePath", "description",
643                 "userWorkstations", "comment", "userParameters", "objectSid",
644                 "primaryGroupID", "userAccountControl",
645                 "msDS-User-Account-Control-Computed", "logonHours",
646                 "badPwdCount", "logonCount", "countryCode", "codePage",
647                 "unicodePwd", "dBCSPwd", NULL };
648
649         int rc = dsdb_search_one(state->ldb, mem_ctx, msg, ldb_get_default_basedn(state->ldb), LDB_SCOPE_SUBTREE, attrs, 0, "%s", filter);
650         if (rc != LDB_SUCCESS) {
651                 DEBUG(10, ("ldap_search failed %s\n",
652                            ldb_errstring(state->ldb)));
653                 return NT_STATUS_LDAP(rc);
654         }
655
656         return NT_STATUS_OK;
657 }
658
659 static NTSTATUS pdb_samba_dsdb_getsampwfilter(struct pdb_methods *m,
660                                           struct pdb_samba_dsdb_state *state,
661                                           struct samu *sam_acct,
662                                           const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(4, 5)
663 {
664         struct ldb_message *priv;
665         NTSTATUS status;
666         va_list ap;
667         char *expression = NULL;
668         TALLOC_CTX *tmp_ctx = talloc_new(state);
669         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
670
671         va_start(ap, exp_fmt);
672         expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
673         va_end(ap);
674
675         if (!expression) {
676                 talloc_free(tmp_ctx);
677                 return NT_STATUS_NO_MEMORY;
678         }
679
680         status = pdb_samba_dsdb_getsamupriv(state, expression, sam_acct, &priv);
681         talloc_free(tmp_ctx);
682         if (!NT_STATUS_IS_OK(status)) {
683                 DEBUG(10, ("pdb_samba_dsdb_getsamupriv failed: %s\n",
684                            nt_errstr(status)));
685                 return status;
686         }
687
688         status = pdb_samba_dsdb_init_sam_from_priv(m, sam_acct, priv);
689         if (!NT_STATUS_IS_OK(status)) {
690                 DEBUG(10, ("pdb_samba_dsdb_init_sam_from_priv failed: %s\n",
691                            nt_errstr(status)));
692                 TALLOC_FREE(priv);
693                 return status;
694         }
695
696         pdb_set_backend_private_data(sam_acct, priv, NULL, m, PDB_SET);
697         return NT_STATUS_OK;
698 }
699
700 static NTSTATUS pdb_samba_dsdb_getsampwnam(struct pdb_methods *m,
701                                     struct samu *sam_acct,
702                                     const char *username)
703 {
704         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
705                 m->private_data, struct pdb_samba_dsdb_state);
706
707         return pdb_samba_dsdb_getsampwfilter(m, state, sam_acct,
708                                          "(&(samaccountname=%s)(objectclass=user))",
709                                          username);
710 }
711
712 static NTSTATUS pdb_samba_dsdb_getsampwsid(struct pdb_methods *m,
713                                     struct samu *sam_acct,
714                                     const struct dom_sid *sid)
715 {
716         NTSTATUS status;
717         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
718                 m->private_data, struct pdb_samba_dsdb_state);
719         char *sidstr;
720
721         sidstr = dom_sid_string(talloc_tos(), sid);
722         NT_STATUS_HAVE_NO_MEMORY(sidstr);
723
724         status = pdb_samba_dsdb_getsampwfilter(m, state, sam_acct,
725                                            "(&(objectsid=%s)(objectclass=user))",
726                                            sidstr);
727         talloc_free(sidstr);
728         return status;
729 }
730
731 static NTSTATUS pdb_samba_dsdb_create_user(struct pdb_methods *m,
732                                     TALLOC_CTX *mem_ctx,
733                                     const char *name, uint32 acct_flags,
734                                     uint32 *rid)
735 {
736         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
737                 m->private_data, struct pdb_samba_dsdb_state);
738         struct dom_sid *sid;
739         struct ldb_dn *dn;
740         NTSTATUS status;
741         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
742         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
743
744         /* Internally this uses transactions to ensure all the steps
745          * happen or fail as one */
746         status = dsdb_add_user(state->ldb, tmp_ctx, name, acct_flags, NULL,
747                                &sid, &dn);
748         if (!NT_STATUS_IS_OK(status)) {
749                 talloc_free(tmp_ctx);
750                 return status;
751         }
752         sid_peek_rid(sid, rid);
753         talloc_free(tmp_ctx);
754         return NT_STATUS_OK;
755 }
756
757 static NTSTATUS pdb_samba_dsdb_delete_user(struct pdb_methods *m,
758                                        TALLOC_CTX *mem_ctx,
759                                        struct samu *sam)
760 {
761         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
762                 m->private_data, struct pdb_samba_dsdb_state);
763         struct ldb_dn *dn;
764         int rc;
765         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
766         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
767
768         dn = ldb_dn_new_fmt(tmp_ctx, state->ldb, "<SID=%s>", dom_sid_string(tmp_ctx, pdb_get_user_sid(sam)));
769         if (!dn || !ldb_dn_validate(dn)) {
770                 talloc_free(tmp_ctx);
771                 return NT_STATUS_NO_MEMORY;
772         }
773         rc = ldb_delete(state->ldb, dn);
774
775         if (rc != LDB_SUCCESS) {
776                 DEBUG(10, ("ldb_delete for %s failed: %s\n", ldb_dn_get_linearized(dn),
777                            ldb_errstring(state->ldb)));
778                 talloc_free(tmp_ctx);
779                 return NT_STATUS_LDAP(rc);
780         }
781         talloc_free(tmp_ctx);
782         return NT_STATUS_OK;
783 }
784
785 /* This interface takes a fully populated struct samu and places it in
786  * the database.  This is not implemented at this time as we need to
787  * be careful around the creation of arbitary SIDs (ie, we must ensrue
788  * they are not left in a RID pool */
789 static NTSTATUS pdb_samba_dsdb_add_sam_account(struct pdb_methods *m,
790                                         struct samu *sampass)
791 {
792         int ret;
793         NTSTATUS status;
794         struct ldb_dn *dn;
795         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
796                 m->private_data, struct pdb_samba_dsdb_state);
797         uint32_t acb_flags = pdb_get_acct_ctrl(sampass);
798         const char *username = pdb_get_username(sampass);
799         const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
800         TALLOC_CTX *tframe = talloc_stackframe();
801
802         acb_flags &= (ACB_NORMAL|ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST);
803
804         ret = ldb_transaction_start(state->ldb);
805         if (ret != LDB_SUCCESS) {
806                 talloc_free(tframe);
807                 return NT_STATUS_LOCK_NOT_GRANTED;
808         }
809
810         status = dsdb_add_user(state->ldb, talloc_tos(), username,
811                                acb_flags, user_sid, NULL, &dn);
812         if (!NT_STATUS_IS_OK(status)) {
813                 ldb_transaction_cancel(state->ldb);
814                 talloc_free(tframe);
815                 return status;
816         }
817
818         ret = pdb_samba_dsdb_replace_by_sam(state, pdb_element_is_set_or_changed,
819                                         dn, sampass);
820         if (ret != LDB_SUCCESS) {
821                 ldb_transaction_cancel(state->ldb);
822                 talloc_free(tframe);
823                 return dsdb_ldb_err_to_ntstatus(ret);
824         }
825
826         ret = ldb_transaction_commit(state->ldb);
827         if (ret != LDB_SUCCESS) {
828                 DEBUG(0,("Failed to commit transaction to add and modify account record %s: %s\n",
829                          ldb_dn_get_linearized(dn),
830                          ldb_errstring(state->ldb)));
831                 talloc_free(tframe);
832                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
833         }
834         talloc_free(tframe);
835         return NT_STATUS_OK;
836 }
837
838 /*
839  * Update the Samba_Dsdb LDB with the changes from a struct samu.
840  *
841  * This takes care not to update elements that have not been changed
842  * by the caller
843  */
844 static NTSTATUS pdb_samba_dsdb_update_sam_account(struct pdb_methods *m,
845                                            struct samu *sam)
846 {
847         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
848                 m->private_data, struct pdb_samba_dsdb_state);
849         struct ldb_message *msg = pdb_samba_dsdb_get_samu_private(
850                 m, sam);
851         int ret;
852
853         ret = pdb_samba_dsdb_replace_by_sam(state, pdb_element_is_changed, msg->dn,
854                                         sam);
855         return dsdb_ldb_err_to_ntstatus(ret);
856 }
857
858 static NTSTATUS pdb_samba_dsdb_delete_sam_account(struct pdb_methods *m,
859                                            struct samu *username)
860 {
861         NTSTATUS status;
862         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
863         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
864         status = pdb_samba_dsdb_delete_user(m, tmp_ctx, username);
865         talloc_free(tmp_ctx);
866         return status;
867 }
868
869 static NTSTATUS pdb_samba_dsdb_rename_sam_account(struct pdb_methods *m,
870                                            struct samu *oldname,
871                                            const char *newname)
872 {
873         return NT_STATUS_NOT_IMPLEMENTED;
874 }
875
876 /* This is not implemented, as this module is exptected to be used
877  * with auth_samba_dsdb, and this is responible for login counters etc
878  *
879  */
880 static NTSTATUS pdb_samba_dsdb_update_login_attempts(struct pdb_methods *m,
881                                               struct samu *sam_acct,
882                                               bool success)
883 {
884         return NT_STATUS_NOT_IMPLEMENTED;
885 }
886
887 static NTSTATUS pdb_samba_dsdb_getgrfilter(struct pdb_methods *m, GROUP_MAP *map,
888                                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(4, 5)
889 {
890         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
891                 m->private_data, struct pdb_samba_dsdb_state);
892         const char *attrs[] = { "objectClass", "objectSid", "description", "samAccountName", "groupType",
893                                 NULL };
894         struct ldb_message *msg;
895         va_list ap;
896         char *expression = NULL;
897         struct dom_sid *sid;
898         const char *str;
899         int rc;
900         struct id_map id_map;
901         struct id_map *id_maps[2];
902         TALLOC_CTX *tmp_ctx = talloc_stackframe();
903         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
904
905         va_start(ap, exp_fmt);
906         expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
907         va_end(ap);
908
909         if (!expression) {
910                 talloc_free(tmp_ctx);
911                 return NT_STATUS_NO_MEMORY;
912         }
913
914         rc = dsdb_search_one(state->ldb, tmp_ctx, &msg, ldb_get_default_basedn(state->ldb), LDB_SCOPE_SUBTREE, attrs, 0, "%s", expression);
915         if (rc == LDB_ERR_NO_SUCH_OBJECT) {
916                 talloc_free(tmp_ctx);
917                 return NT_STATUS_NO_SUCH_GROUP;
918         } else if (rc != LDB_SUCCESS) {
919                 talloc_free(tmp_ctx);
920                 DEBUG(10, ("dsdb_search_one failed %s\n",
921                            ldb_errstring(state->ldb)));
922                 return NT_STATUS_LDAP(rc);
923         }
924
925         sid = samdb_result_dom_sid(tmp_ctx, msg, "objectSid");
926         if (!sid) {
927                 talloc_free(tmp_ctx);
928                 DEBUG(10, ("Could not pull SID\n"));
929                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
930         }
931
932         map->sid = *sid;
933
934         if (samdb_find_attribute(state->ldb, msg, "objectClass", "group")) {
935                 NTSTATUS status;
936                 uint32_t grouptype = ldb_msg_find_attr_as_uint(msg, "groupType", 0);
937                 switch (grouptype) {
938                 case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
939                 case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
940                         map->sid_name_use = SID_NAME_ALIAS;
941                         break;
942                 case GTYPE_SECURITY_GLOBAL_GROUP:
943                         map->sid_name_use = SID_NAME_DOM_GRP;
944                         break;
945                 default:
946                         talloc_free(tmp_ctx);
947                         DEBUG(10, ("Could not pull groupType\n"));
948                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
949                 }
950
951                 ZERO_STRUCT(id_map);
952                 id_map.sid = sid;
953                 id_maps[0] = &id_map;
954                 id_maps[1] = NULL;
955
956                 status = idmap_sids_to_xids(state->idmap_ctx, tmp_ctx, id_maps);
957
958                 if (!NT_STATUS_IS_OK(status)) {
959                         talloc_free(tmp_ctx);
960                         return status;
961                 }
962                 if (id_map.xid.type == ID_TYPE_GID || id_map.xid.type == ID_TYPE_BOTH) {
963                         map->gid = id_map.xid.id;
964                 } else {
965                         DEBUG(1, (__location__ "Did not get GUID when mapping SID for %s", expression));
966                         talloc_free(tmp_ctx);
967                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
968                 }
969         } else if (samdb_find_attribute(state->ldb, msg, "objectClass", "user")) {
970                 DEBUG(1, (__location__ "Got SID_NAME_USER when searching for a group with %s", expression));
971                 talloc_free(tmp_ctx);
972                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
973         }
974
975         str = ldb_msg_find_attr_as_string(msg, "samAccountName",
976                                           NULL);
977         if (str == NULL) {
978                 talloc_free(tmp_ctx);
979                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
980         }
981         map->nt_name = talloc_strdup(map, str);
982         if (!map->nt_name) {
983                 talloc_free(tmp_ctx);
984                 return NT_STATUS_NO_MEMORY;
985         }
986
987         str = ldb_msg_find_attr_as_string(msg, "description",
988                                             NULL);
989         if (str != NULL) {
990                 map->comment = talloc_strdup(map, str);
991         } else {
992                 map->comment = talloc_strdup(map, "");
993         }
994         if (!map->comment) {
995                 talloc_free(tmp_ctx);
996                 return NT_STATUS_NO_MEMORY;
997         }
998
999         talloc_free(tmp_ctx);
1000         return NT_STATUS_OK;
1001 }
1002
1003 static NTSTATUS pdb_samba_dsdb_getgrsid(struct pdb_methods *m, GROUP_MAP *map,
1004                                  struct dom_sid sid)
1005 {
1006         char *filter;
1007         NTSTATUS status;
1008
1009         filter = talloc_asprintf(talloc_tos(),
1010                                  "(&(objectsid=%s)(objectclass=group))",
1011                                  sid_string_talloc(talloc_tos(), &sid));
1012         if (filter == NULL) {
1013                 return NT_STATUS_NO_MEMORY;
1014         }
1015
1016         status = pdb_samba_dsdb_getgrfilter(m, map, filter);
1017         TALLOC_FREE(filter);
1018         return status;
1019 }
1020
1021 static NTSTATUS pdb_samba_dsdb_getgrgid(struct pdb_methods *m, GROUP_MAP *map,
1022                                  gid_t gid)
1023 {
1024         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1025                 m->private_data, struct pdb_samba_dsdb_state);
1026         NTSTATUS status;
1027         struct id_map id_map;
1028         struct id_map *id_maps[2];
1029         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1030         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1031
1032         id_map.xid.id = gid;
1033         id_map.xid.type = ID_TYPE_GID;
1034         id_maps[0] = &id_map;
1035         id_maps[1] = NULL;
1036
1037         status = idmap_xids_to_sids(state->idmap_ctx, tmp_ctx, id_maps);
1038         if (!NT_STATUS_IS_OK(status)) {
1039                 talloc_free(tmp_ctx);
1040                 return status;
1041         }
1042         status = pdb_samba_dsdb_getgrsid(m, map, *id_map.sid);
1043         talloc_free(tmp_ctx);
1044         return status;
1045 }
1046
1047 static NTSTATUS pdb_samba_dsdb_getgrnam(struct pdb_methods *m, GROUP_MAP *map,
1048                                  const char *name)
1049 {
1050         char *filter;
1051         NTSTATUS status;
1052
1053         filter = talloc_asprintf(talloc_tos(),
1054                                  "(&(samaccountname=%s)(objectclass=group))",
1055                                  name);
1056         if (filter == NULL) {
1057                 return NT_STATUS_NO_MEMORY;
1058         }
1059
1060         status = pdb_samba_dsdb_getgrfilter(m, map, filter);
1061         TALLOC_FREE(filter);
1062         return status;
1063 }
1064
1065 static NTSTATUS pdb_samba_dsdb_create_dom_group(struct pdb_methods *m,
1066                                          TALLOC_CTX *mem_ctx, const char *name,
1067                                          uint32 *rid)
1068 {
1069         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1070                 m->private_data, struct pdb_samba_dsdb_state);
1071         NTSTATUS status;
1072         struct dom_sid *sid;
1073         struct ldb_dn *dn;
1074         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1075         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1076
1077         status = dsdb_add_domain_group(state->ldb, tmp_ctx, name, &sid, &dn);
1078         if (!NT_STATUS_IS_OK(status)) {
1079                 talloc_free(tmp_ctx);
1080                 return status;
1081         }
1082
1083         sid_peek_rid(sid, rid);
1084         talloc_free(tmp_ctx);
1085         return NT_STATUS_OK;
1086 }
1087
1088 static NTSTATUS pdb_samba_dsdb_delete_dom_group(struct pdb_methods *m,
1089                                          TALLOC_CTX *mem_ctx, uint32 rid)
1090 {
1091         const char *attrs[] = { NULL };
1092         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1093                 m->private_data, struct pdb_samba_dsdb_state);
1094         struct dom_sid sid;
1095         struct ldb_message *msg;
1096         struct ldb_dn *dn;
1097         int rc;
1098         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1099         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1100
1101         sid_compose(&sid, samdb_domain_sid(state->ldb), rid);
1102
1103         if (ldb_transaction_start(state->ldb) != LDB_SUCCESS) {
1104                 DEBUG(0, ("Unable to start transaction in pdb_samba_dsdb_delete_dom_group()\n"));
1105                 return NT_STATUS_INTERNAL_ERROR;
1106         }
1107
1108         dn = ldb_dn_new_fmt(tmp_ctx, state->ldb, "<SID=%s>", dom_sid_string(tmp_ctx, &sid));
1109         if (!dn || !ldb_dn_validate(dn)) {
1110                 talloc_free(tmp_ctx);
1111                 ldb_transaction_cancel(state->ldb);
1112                 return NT_STATUS_NO_MEMORY;
1113         }
1114         rc = dsdb_search_one(state->ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE, attrs, 0, "objectclass=group");
1115         if (rc == LDB_ERR_NO_SUCH_OBJECT) {
1116                 talloc_free(tmp_ctx);
1117                 ldb_transaction_cancel(state->ldb);
1118                 return NT_STATUS_NO_SUCH_GROUP;
1119         }
1120         rc = ldb_delete(state->ldb, dn);
1121         if (rc == LDB_ERR_NO_SUCH_OBJECT) {
1122                 talloc_free(tmp_ctx);
1123                 ldb_transaction_cancel(state->ldb);
1124                 return NT_STATUS_NO_SUCH_GROUP;
1125         } else if (rc != LDB_SUCCESS) {
1126                 DEBUG(10, ("ldb_delete failed %s\n",
1127                            ldb_errstring(state->ldb)));
1128                 ldb_transaction_cancel(state->ldb);
1129                 return NT_STATUS_LDAP(rc);
1130         }
1131
1132         if (ldb_transaction_commit(state->ldb) != LDB_SUCCESS) {
1133                 DEBUG(0, ("Unable to commit transaction in pdb_samba_dsdb_delete_dom_group()\n"));
1134                 return NT_STATUS_INTERNAL_ERROR;
1135         }
1136         return NT_STATUS_OK;
1137 }
1138
1139 static NTSTATUS pdb_samba_dsdb_add_group_mapping_entry(struct pdb_methods *m,
1140                                                 GROUP_MAP *map)
1141 {
1142         return NT_STATUS_NOT_IMPLEMENTED;
1143 }
1144
1145 static NTSTATUS pdb_samba_dsdb_update_group_mapping_entry(struct pdb_methods *m,
1146                                                    GROUP_MAP *map)
1147 {
1148         return NT_STATUS_NOT_IMPLEMENTED;
1149 }
1150
1151 static NTSTATUS pdb_samba_dsdb_delete_group_mapping_entry(struct pdb_methods *m,
1152                                                    struct dom_sid sid)
1153 {
1154         return NT_STATUS_NOT_IMPLEMENTED;
1155 }
1156
1157 static NTSTATUS pdb_samba_dsdb_enum_group_mapping(struct pdb_methods *m,
1158                                            const struct dom_sid *sid,
1159                                            enum lsa_SidType sid_name_use,
1160                                            GROUP_MAP ***pp_rmap,
1161                                            size_t *p_num_entries,
1162                                            bool unix_only)
1163 {
1164         return NT_STATUS_NOT_IMPLEMENTED;
1165 }
1166
1167 static NTSTATUS pdb_samba_dsdb_enum_group_members(struct pdb_methods *m,
1168                                            TALLOC_CTX *mem_ctx,
1169                                            const struct dom_sid *group,
1170                                            uint32_t **pmembers,
1171                                            size_t *pnum_members)
1172 {
1173         unsigned int i, num_sids, num_members;
1174         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1175                 m->private_data, struct pdb_samba_dsdb_state);
1176         struct dom_sid *members_as_sids;
1177         struct dom_sid *dom_sid;
1178         uint32_t *members;
1179         struct ldb_dn *dn;
1180         NTSTATUS status;
1181
1182         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1183         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1184
1185         dn = ldb_dn_new_fmt(tmp_ctx, state->ldb, "<SID=%s>", dom_sid_string(tmp_ctx, group));
1186         if (!dn || !ldb_dn_validate(dn)) {
1187                 return NT_STATUS_NO_MEMORY;
1188         }
1189
1190         status = dsdb_enum_group_mem(state->ldb, tmp_ctx, dn, &members_as_sids, &num_sids);
1191         if (!NT_STATUS_IS_OK(status)) {
1192                 talloc_free(tmp_ctx);
1193                 return status;
1194         }
1195         status = dom_sid_split_rid(tmp_ctx, group, &dom_sid, NULL);
1196         if (!NT_STATUS_IS_OK(status)) {
1197                 talloc_free(tmp_ctx);
1198                 return status;
1199         }
1200
1201         *pmembers = members = talloc_array(mem_ctx, uint32_t, num_sids);
1202         if (*pmembers == NULL) {
1203                 TALLOC_FREE(tmp_ctx);
1204                 return NT_STATUS_NO_MEMORY;
1205         }
1206         num_members = 0;
1207
1208         for (i = 0; i < num_sids; i++) {
1209                 if (!dom_sid_in_domain(dom_sid, &members_as_sids[i])) {
1210                         continue;
1211                 }
1212                 status = dom_sid_split_rid(NULL, &members_as_sids[i],
1213                                            NULL, &members[num_members]);
1214                 if (!NT_STATUS_IS_OK(status)) {
1215                         talloc_free(tmp_ctx);
1216                         return status;
1217                 }
1218                 num_members++;
1219         }
1220         *pnum_members = num_members;
1221         return NT_STATUS_OK;
1222 }
1223
1224 /* Just convert the primary group SID into a group */
1225 static NTSTATUS fake_enum_group_memberships(struct pdb_samba_dsdb_state *state,
1226                                             TALLOC_CTX *mem_ctx,
1227                                             struct samu *user,
1228                                             struct dom_sid **pp_sids,
1229                                             gid_t **pp_gids,
1230                                             uint32_t *p_num_groups)
1231 {
1232         NTSTATUS status;
1233         size_t num_groups = 0;
1234         struct dom_sid *group_sids = NULL;
1235         gid_t *gids = NULL;
1236         TALLOC_CTX *tmp_ctx;
1237
1238         tmp_ctx = talloc_new(mem_ctx);
1239         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1240
1241         if (user->group_sid) {
1242                 struct id_map *id_maps[2];
1243                 struct id_map id_map;
1244
1245                 num_groups = 1;
1246
1247                 group_sids = talloc_array(tmp_ctx, struct dom_sid, num_groups);
1248                 if (group_sids == NULL) {
1249                         talloc_free(tmp_ctx);
1250                         return NT_STATUS_NO_MEMORY;
1251                 }
1252                 gids = talloc_array(tmp_ctx, gid_t, num_groups);
1253                 if (gids == NULL) {
1254                         talloc_free(tmp_ctx);
1255                         return NT_STATUS_NO_MEMORY;
1256                 }
1257
1258                 group_sids[0] = *user->group_sid;
1259
1260                 ZERO_STRUCT(id_map);
1261                 id_map.sid = &group_sids[0];
1262                 id_maps[0] = &id_map;
1263                 id_maps[1] = NULL;
1264
1265                 status = idmap_sids_to_xids(state->idmap_ctx, tmp_ctx, id_maps);
1266                 if (!NT_STATUS_IS_OK(status)) {
1267                         talloc_free(tmp_ctx);
1268                         return status;
1269                 }
1270                 if (id_map.xid.type == ID_TYPE_GID || id_map.xid.type == ID_TYPE_BOTH) {
1271                         gids[0] = id_map.xid.id;
1272                 } else {
1273                         DEBUG(1, (__location__
1274                                   "Group %s, of which %s is a member, could not be converted to a GID\n",
1275                                   dom_sid_string(tmp_ctx, &group_sids[0]),
1276                                   dom_sid_string(tmp_ctx, &user->user_sid)));
1277                         talloc_free(tmp_ctx);
1278                         /* We must error out, otherwise a user might
1279                          * avoid a DENY acl based on a group they
1280                          * missed out on */
1281                         return NT_STATUS_NO_SUCH_GROUP;
1282                 }
1283         }
1284
1285         *pp_sids = talloc_steal(mem_ctx, group_sids);
1286         *pp_gids = talloc_steal(mem_ctx, gids);
1287         *p_num_groups = num_groups;
1288         talloc_free(tmp_ctx);
1289         return NT_STATUS_OK;
1290 }
1291
1292 static NTSTATUS pdb_samba_dsdb_enum_group_memberships(struct pdb_methods *m,
1293                                                TALLOC_CTX *mem_ctx,
1294                                                struct samu *user,
1295                                                struct dom_sid **pp_sids,
1296                                                gid_t **pp_gids,
1297                                                uint32_t *p_num_groups)
1298 {
1299         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1300                 m->private_data, struct pdb_samba_dsdb_state);
1301         struct ldb_message *msg = pdb_samba_dsdb_get_samu_private(
1302                 m, user);
1303         const char *attrs[] = { "tokenGroups", NULL};
1304         struct ldb_message *tokengroups_msg;
1305         struct ldb_message_element *tokengroups;
1306         int i, rc;
1307         NTSTATUS status;
1308         unsigned int count = 0;
1309         size_t num_groups;
1310         struct dom_sid *group_sids;
1311         gid_t *gids;
1312         TALLOC_CTX *tmp_ctx;
1313
1314         if (msg == NULL) {
1315                 /* Fake up some things here */
1316                 return fake_enum_group_memberships(state,
1317                                                    mem_ctx,
1318                                                    user, pp_sids,
1319                                                    pp_gids, p_num_groups);
1320         }
1321
1322         tmp_ctx = talloc_new(mem_ctx);
1323         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1324
1325         rc = dsdb_search_one(state->ldb, tmp_ctx, &tokengroups_msg, msg->dn, LDB_SCOPE_BASE, attrs, 0, NULL);
1326
1327         if (rc == LDB_ERR_NO_SUCH_OBJECT) {
1328                 talloc_free(tmp_ctx);
1329                 return NT_STATUS_NO_SUCH_USER;
1330         } else if (rc != LDB_SUCCESS) {
1331                 DEBUG(10, ("dsdb_search_one failed %s\n",
1332                            ldb_errstring(state->ldb)));
1333                 talloc_free(tmp_ctx);
1334                 return NT_STATUS_LDAP(rc);
1335         }
1336
1337         tokengroups = ldb_msg_find_element(tokengroups_msg, "tokenGroups");
1338
1339         if (tokengroups) {
1340                 count = tokengroups->num_values;
1341         }
1342
1343         group_sids = talloc_array(tmp_ctx, struct dom_sid, count);
1344         if (group_sids == NULL) {
1345                 talloc_free(tmp_ctx);
1346                 return NT_STATUS_NO_MEMORY;
1347         }
1348         gids = talloc_array(tmp_ctx, gid_t, count);
1349         if (gids == NULL) {
1350                 talloc_free(tmp_ctx);
1351                 return NT_STATUS_NO_MEMORY;
1352         }
1353         num_groups = 0;
1354
1355         for (i=0; i<count; i++) {
1356                 struct id_map *id_maps[2];
1357                 struct id_map id_map;
1358                 struct ldb_val *v = &tokengroups->values[i];
1359                 enum ndr_err_code ndr_err
1360                         = ndr_pull_struct_blob(v, group_sids, &group_sids[num_groups],
1361                                                (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
1362                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1363                         talloc_free(tmp_ctx);
1364                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1365                 }
1366
1367                 ZERO_STRUCT(id_map);
1368                 id_map.sid = &group_sids[num_groups];
1369                 id_maps[0] = &id_map;
1370                 id_maps[1] = NULL;
1371
1372                 status = idmap_sids_to_xids(state->idmap_ctx, tmp_ctx, id_maps);
1373                 if (!NT_STATUS_IS_OK(status)) {
1374                         talloc_free(tmp_ctx);
1375                         return status;
1376                 }
1377                 if (id_map.xid.type == ID_TYPE_GID || id_map.xid.type == ID_TYPE_BOTH) {
1378                         gids[num_groups] = id_map.xid.id;
1379                 } else {
1380                         DEBUG(1, (__location__
1381                                   "Group %s, of which %s is a member, could not be converted to a GID\n",
1382                                   dom_sid_string(tmp_ctx, &group_sids[num_groups]),
1383                                   ldb_dn_get_linearized(msg->dn)));
1384                         talloc_free(tmp_ctx);
1385                         /* We must error out, otherwise a user might
1386                          * avoid a DENY acl based on a group they
1387                          * missed out on */
1388                         return NT_STATUS_NO_SUCH_GROUP;
1389                 }
1390
1391                 num_groups += 1;
1392                 if (num_groups == count) {
1393                         break;
1394                 }
1395         }
1396
1397         *pp_sids = talloc_steal(mem_ctx, group_sids);
1398         *pp_gids = talloc_steal(mem_ctx, gids);
1399         *p_num_groups = num_groups;
1400         talloc_free(tmp_ctx);
1401         return NT_STATUS_OK;
1402 }
1403
1404 static NTSTATUS pdb_samba_dsdb_set_unix_primary_group(struct pdb_methods *m,
1405                                                TALLOC_CTX *mem_ctx,
1406                                                struct samu *user)
1407 {
1408         return NT_STATUS_NOT_IMPLEMENTED;
1409 }
1410
1411 static NTSTATUS pdb_samba_dsdb_mod_groupmem_by_sid(struct pdb_methods *m,
1412                                                TALLOC_CTX *mem_ctx,
1413                                                const struct dom_sid *groupsid,
1414                                                const struct dom_sid *membersid,
1415                                                int mod_op)
1416 {
1417         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1418                 m->private_data, struct pdb_samba_dsdb_state);
1419         struct ldb_message *msg;
1420         int ret;
1421         struct ldb_message_element *el;
1422         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1423         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1424         msg = ldb_msg_new(tmp_ctx);
1425         if (msg == NULL) {
1426                 TALLOC_FREE(tmp_ctx);
1427                 return NT_STATUS_NO_MEMORY;
1428         }
1429
1430         msg->dn = ldb_dn_new_fmt(msg, state->ldb, "<SID=%s>", dom_sid_string(tmp_ctx, groupsid));
1431         if (!msg->dn || !ldb_dn_validate(msg->dn)) {
1432                 talloc_free(tmp_ctx);
1433                 return NT_STATUS_NO_MEMORY;
1434         }
1435         ret = ldb_msg_add_fmt(msg, "member", "<SID=%s>", dom_sid_string(tmp_ctx, membersid));
1436         if (ret != LDB_SUCCESS) {
1437                 talloc_free(tmp_ctx);
1438                 return NT_STATUS_NO_MEMORY;
1439         }
1440         el = ldb_msg_find_element(msg, "member");
1441         el->flags = mod_op;
1442
1443         /* No need for transactions here, the ldb auto-transaction
1444          * code will handle things for the single operation */
1445         ret = ldb_modify(state->ldb, msg);
1446         talloc_free(tmp_ctx);
1447         if (ret != LDB_SUCCESS) {
1448                 DEBUG(10, ("ldb_modify failed: %s\n",
1449                            ldb_errstring(state->ldb)));
1450                 if (ret == LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
1451                         return NT_STATUS_MEMBER_IN_GROUP;
1452                 }
1453                 if (ret == LDB_ERR_NO_SUCH_ATTRIBUTE) {
1454                         return NT_STATUS_MEMBER_NOT_IN_GROUP;
1455                 }
1456                 return NT_STATUS_LDAP(ret);
1457         }
1458
1459         return NT_STATUS_OK;
1460 }
1461
1462 static NTSTATUS pdb_samba_dsdb_mod_groupmem(struct pdb_methods *m,
1463                                      TALLOC_CTX *mem_ctx,
1464                                      uint32 grouprid, uint32 memberrid,
1465                                      int mod_op)
1466 {
1467         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1468                 m->private_data, struct pdb_samba_dsdb_state);
1469         const struct dom_sid *dom_sid, *groupsid, *membersid;
1470         NTSTATUS status;
1471         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1472         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1473
1474         dom_sid = samdb_domain_sid(state->ldb);
1475
1476         groupsid = dom_sid_add_rid(tmp_ctx, dom_sid, grouprid);
1477         if (groupsid == NULL) {
1478                 TALLOC_FREE(tmp_ctx);
1479                 return NT_STATUS_NO_MEMORY;
1480         }
1481         membersid = dom_sid_add_rid(tmp_ctx, dom_sid, memberrid);
1482         if (membersid == NULL) {
1483                 TALLOC_FREE(tmp_ctx);
1484                 return NT_STATUS_NO_MEMORY;
1485         }
1486         status = pdb_samba_dsdb_mod_groupmem_by_sid(m, tmp_ctx, groupsid, membersid, mod_op);
1487         talloc_free(tmp_ctx);
1488         return status;
1489 }
1490
1491 static NTSTATUS pdb_samba_dsdb_add_groupmem(struct pdb_methods *m,
1492                                      TALLOC_CTX *mem_ctx,
1493                                      uint32 group_rid, uint32 member_rid)
1494 {
1495         return pdb_samba_dsdb_mod_groupmem(m, mem_ctx, group_rid, member_rid,
1496                                     LDB_FLAG_MOD_ADD);
1497 }
1498
1499 static NTSTATUS pdb_samba_dsdb_del_groupmem(struct pdb_methods *m,
1500                                      TALLOC_CTX *mem_ctx,
1501                                      uint32 group_rid, uint32 member_rid)
1502 {
1503         return pdb_samba_dsdb_mod_groupmem(m, mem_ctx, group_rid, member_rid,
1504                                        LDB_FLAG_MOD_DELETE);
1505 }
1506
1507 static NTSTATUS pdb_samba_dsdb_create_alias(struct pdb_methods *m,
1508                                      const char *name, uint32 *rid)
1509 {
1510         TALLOC_CTX *frame = talloc_stackframe();
1511         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1512                 m->private_data, struct pdb_samba_dsdb_state);
1513         struct dom_sid *sid;
1514
1515         struct ldb_dn *dn;
1516         NTSTATUS status;
1517
1518         /* Internally this uses transactions to ensure all the steps
1519          * happen or fail as one */
1520         status = dsdb_add_domain_alias(state->ldb, frame, name, &sid, &dn);
1521         if (!NT_STATUS_IS_OK(status)) {
1522                 TALLOC_FREE(frame);
1523         }
1524
1525         sid_peek_rid(sid, rid);
1526         TALLOC_FREE(frame);
1527         return NT_STATUS_OK;
1528 }
1529
1530 static NTSTATUS pdb_samba_dsdb_delete_alias(struct pdb_methods *m,
1531                                      const struct dom_sid *sid)
1532 {
1533         const char *attrs[] = { NULL };
1534         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1535                 m->private_data, struct pdb_samba_dsdb_state);
1536         struct ldb_message *msg;
1537         struct ldb_dn *dn;
1538         int rc;
1539         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1540         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1541
1542         dn = ldb_dn_new_fmt(tmp_ctx, state->ldb, "<SID=%s>", dom_sid_string(tmp_ctx, sid));
1543         if (!dn || !ldb_dn_validate(dn)) {
1544                 talloc_free(tmp_ctx);
1545                 return NT_STATUS_NO_MEMORY;
1546         }
1547
1548         if (ldb_transaction_start(state->ldb) != LDB_SUCCESS) {
1549                 DEBUG(0, ("Failed to start transaction in dsdb_add_domain_alias(): %s\n", ldb_errstring(state->ldb)));
1550                 talloc_free(tmp_ctx);
1551                 return NT_STATUS_INTERNAL_ERROR;
1552         }
1553
1554         rc = dsdb_search_one(state->ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE, attrs, 0, "(objectclass=group)"
1555                              "(|(grouptype=%d)(grouptype=%d)))",
1556                              GTYPE_SECURITY_BUILTIN_LOCAL_GROUP,
1557                              GTYPE_SECURITY_DOMAIN_LOCAL_GROUP);
1558         if (rc == LDB_ERR_NO_SUCH_OBJECT) {
1559                 talloc_free(tmp_ctx);
1560                 ldb_transaction_cancel(state->ldb);
1561                 return NT_STATUS_NO_SUCH_ALIAS;
1562         }
1563         rc = ldb_delete(state->ldb, dn);
1564         if (rc == LDB_ERR_NO_SUCH_OBJECT) {
1565                 talloc_free(tmp_ctx);
1566                 ldb_transaction_cancel(state->ldb);
1567                 return NT_STATUS_NO_SUCH_ALIAS;
1568         } else if (rc != LDB_SUCCESS) {
1569                 DEBUG(10, ("ldb_delete failed %s\n",
1570                            ldb_errstring(state->ldb)));
1571                 ldb_transaction_cancel(state->ldb);
1572                 talloc_free(tmp_ctx);
1573                 return NT_STATUS_LDAP(rc);
1574         }
1575
1576         if (ldb_transaction_commit(state->ldb) != LDB_SUCCESS) {
1577                 DEBUG(0, ("Failed to commit transaction in pdb_samba_dsdb_delete_alias(): %s\n",
1578                           ldb_errstring(state->ldb)));
1579                 talloc_free(tmp_ctx);
1580                 return NT_STATUS_INTERNAL_ERROR;
1581         }
1582
1583         talloc_free(tmp_ctx);
1584         return NT_STATUS_OK;
1585 }
1586
1587 #if 0
1588 static NTSTATUS pdb_samba_dsdb_set_aliasinfo(struct pdb_methods *m,
1589                                       const struct dom_sid *sid,
1590                                       struct acct_info *info)
1591 {
1592         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1593                 m->private_data, struct pdb_samba_dsdb_state);
1594         struct tldap_context *ld;
1595         const char *attrs[3] = { "objectSid", "description",
1596                                  "samAccountName" };
1597         struct ldb_message **msg;
1598         char *sidstr, *dn;
1599         int rc;
1600         struct tldap_mod *mods;
1601         int num_mods;
1602         bool ok;
1603
1604         ld = pdb_samba_dsdb_ld(state);
1605         if (ld == NULL) {
1606                 return NT_STATUS_LDAP(TLDAP_SERVER_DOWN);
1607         }
1608
1609         sidstr = sid_binstring(talloc_tos(), sid);
1610         NT_STATUS_HAVE_NO_MEMORY(sidstr);
1611
1612         rc = pdb_samba_dsdb_search_fmt(state, state->domaindn, TLDAP_SCOPE_SUB,
1613                                 attrs, ARRAY_SIZE(attrs), 0, talloc_tos(),
1614                                 &msg, "(&(objectSid=%s)(objectclass=group)"
1615                                 "(|(grouptype=%d)(grouptype=%d)))",
1616                                 sidstr, GTYPE_SECURITY_BUILTIN_LOCAL_GROUP,
1617                                 GTYPE_SECURITY_DOMAIN_LOCAL_GROUP);
1618         TALLOC_FREE(sidstr)
1619         if (rc != LDB_SUCCESS) {
1620                 DEBUG(10, ("ldap_search failed %s\n",
1621                            ldb_errstring(state->ldb)));
1622                 return NT_STATUS_LDAP(rc);
1623         }
1624         switch talloc_array_length(msg) {
1625         case 0:
1626                 return NT_STATUS_NO_SUCH_ALIAS;
1627         case 1:
1628                 break;
1629         default:
1630                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1631         }
1632
1633         if (!tldap_entry_dn(msg[0], &dn)) {
1634                 TALLOC_FREE(msg);
1635                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1636         }
1637
1638         mods = NULL;
1639         num_mods = 0;
1640         ok = true;
1641
1642         ok &= tldap_make_mod_fmt(
1643                 msg[0], msg, &num_mods, &mods, "description",
1644                 "%s", info->acct_desc);
1645         ok &= tldap_make_mod_fmt(
1646                 msg[0], msg, &num_mods, &mods, "samAccountName",
1647                 "%s", info->acct_name);
1648         if (!ok) {
1649                 TALLOC_FREE(msg);
1650                 return NT_STATUS_NO_MEMORY;
1651         }
1652         if (num_mods == 0) {
1653                 /* no change */
1654                 TALLOC_FREE(msg);
1655                 return NT_STATUS_OK;
1656         }
1657
1658         rc = tldap_modify(ld, dn, num_mods, mods, NULL, 0, NULL, 0);
1659         TALLOC_FREE(msg);
1660         if (rc != LDB_SUCCESS) {
1661                 DEBUG(10, ("ldap_modify failed: %s\n",
1662                            ldb_errstring(state->ldb)));
1663                 return NT_STATUS_LDAP(rc);
1664         }
1665         return NT_STATUS_OK;
1666 }
1667 #endif
1668 static NTSTATUS pdb_samba_dsdb_add_aliasmem(struct pdb_methods *m,
1669                                      const struct dom_sid *alias,
1670                                      const struct dom_sid *member)
1671 {
1672         NTSTATUS status;
1673         TALLOC_CTX *frame = talloc_stackframe();
1674         status = pdb_samba_dsdb_mod_groupmem_by_sid(m, frame, alias, member, LDB_FLAG_MOD_ADD);
1675         talloc_free(frame);
1676         return status;
1677 }
1678
1679 static NTSTATUS pdb_samba_dsdb_del_aliasmem(struct pdb_methods *m,
1680                                      const struct dom_sid *alias,
1681                                      const struct dom_sid *member)
1682 {
1683         NTSTATUS status;
1684         TALLOC_CTX *frame = talloc_stackframe();
1685         status = pdb_samba_dsdb_mod_groupmem_by_sid(m, frame, alias, member, LDB_FLAG_MOD_DELETE);
1686         talloc_free(frame);
1687         return status;
1688 }
1689
1690 static NTSTATUS pdb_samba_dsdb_enum_aliasmem(struct pdb_methods *m,
1691                                       const struct dom_sid *alias,
1692                                       TALLOC_CTX *mem_ctx,
1693                                       struct dom_sid **pmembers,
1694                                       size_t *pnum_members)
1695 {
1696         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1697                 m->private_data, struct pdb_samba_dsdb_state);
1698         struct ldb_dn *dn;
1699         unsigned int num_members;
1700         NTSTATUS status;
1701         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1702         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1703
1704         dn = ldb_dn_new_fmt(tmp_ctx, state->ldb, "<SID=%s>", dom_sid_string(tmp_ctx, alias));
1705         if (!dn || !ldb_dn_validate(dn)) {
1706                 return NT_STATUS_NO_MEMORY;
1707         }
1708
1709         status = dsdb_enum_group_mem(state->ldb, mem_ctx, dn, pmembers, &num_members);
1710         *pnum_members = num_members;
1711         if (NT_STATUS_IS_OK(status)) {
1712                 talloc_steal(mem_ctx, pmembers);
1713         }
1714         talloc_free(tmp_ctx);
1715         return status;
1716 }
1717
1718 static NTSTATUS pdb_samba_dsdb_enum_alias_memberships(struct pdb_methods *m,
1719                                                TALLOC_CTX *mem_ctx,
1720                                                const struct dom_sid *domain_sid,
1721                                                const struct dom_sid *members,
1722                                                size_t num_members,
1723                                                uint32_t **palias_rids,
1724                                                size_t *pnum_alias_rids)
1725 {
1726         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1727                 m->private_data, struct pdb_samba_dsdb_state);
1728         uint32_t *alias_rids = NULL;
1729         size_t num_alias_rids = 0;
1730         int i;
1731         struct dom_sid *groupSIDs = NULL;
1732         unsigned int num_groupSIDs = 0;
1733         char *filter;
1734         NTSTATUS status;
1735         const char *sid_string;
1736         const char *sid_dn;
1737         DATA_BLOB sid_blob;
1738
1739         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1740         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1741         /*
1742          * TODO: Get the filter right so that we only get the aliases from
1743          * either the SAM or BUILTIN
1744          */
1745
1746         filter = talloc_asprintf(tmp_ctx, "(&(objectClass=group)(groupType:1.2.840.113556.1.4.803:=%u))",
1747                                  GROUP_TYPE_BUILTIN_LOCAL_GROUP);
1748         if (filter == NULL) {
1749                 return NT_STATUS_NO_MEMORY;
1750         }
1751
1752         for (i = 0; i < num_members; i++) {
1753                 sid_string = dom_sid_string(tmp_ctx, &members[i]);
1754                 if (sid_string == NULL) {
1755                         TALLOC_FREE(tmp_ctx);
1756                         return NT_STATUS_NO_MEMORY;
1757                 }
1758
1759                 sid_dn = talloc_asprintf(tmp_ctx, "<SID=%s>", sid_string);
1760                 if (sid_dn == NULL) {
1761                         TALLOC_FREE(tmp_ctx);
1762                         return NT_STATUS_NO_MEMORY;
1763                 }
1764
1765                 sid_blob = data_blob_string_const(sid_dn);
1766
1767                 status = dsdb_expand_nested_groups(state->ldb, &sid_blob, true, filter,
1768                                                    tmp_ctx, &groupSIDs, &num_groupSIDs);
1769                 if (!NT_STATUS_IS_OK(status)) {
1770                         talloc_free(tmp_ctx);
1771                         return status;
1772                 }
1773         }
1774
1775         alias_rids = talloc_array(mem_ctx, uint32_t, num_groupSIDs);
1776         if (alias_rids == NULL) {
1777                 talloc_free(tmp_ctx);
1778                 return NT_STATUS_NO_MEMORY;
1779         }
1780
1781         for (i=0; i<num_groupSIDs; i++) {
1782                 if (sid_peek_check_rid(domain_sid, &groupSIDs[i],
1783                                        &alias_rids[num_alias_rids])) {
1784                         num_alias_rids++;;
1785                 }
1786         }
1787
1788         *palias_rids = alias_rids;
1789         *pnum_alias_rids = num_alias_rids;
1790         return NT_STATUS_OK;
1791 }
1792
1793 static NTSTATUS pdb_samba_dsdb_lookup_rids(struct pdb_methods *m,
1794                                     const struct dom_sid *domain_sid,
1795                                     int num_rids,
1796                                     uint32 *rids,
1797                                     const char **names,
1798                                     enum lsa_SidType *lsa_attrs)
1799 {
1800         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1801                 m->private_data, struct pdb_samba_dsdb_state);
1802         NTSTATUS status;
1803
1804         TALLOC_CTX *tmp_ctx;
1805
1806         if (num_rids == 0) {
1807                 return NT_STATUS_NONE_MAPPED;
1808         }
1809
1810         tmp_ctx = talloc_stackframe();
1811         NT_STATUS_HAVE_NO_MEMORY(tmp_ctx);
1812
1813         status = dsdb_lookup_rids(state->ldb, tmp_ctx, domain_sid, num_rids, rids, names, lsa_attrs);
1814         talloc_free(tmp_ctx);
1815         return status;
1816 }
1817
1818 static NTSTATUS pdb_samba_dsdb_lookup_names(struct pdb_methods *m,
1819                                      const struct dom_sid *domain_sid,
1820                                      int num_names,
1821                                      const char **pp_names,
1822                                      uint32 *rids,
1823                                      enum lsa_SidType *attrs)
1824 {
1825         return NT_STATUS_NOT_IMPLEMENTED;
1826 }
1827
1828 static NTSTATUS pdb_samba_dsdb_get_account_policy(struct pdb_methods *m,
1829                                            enum pdb_policy_type type,
1830                                            uint32_t *value)
1831 {
1832         return account_policy_get(type, value)
1833                 ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1834 }
1835
1836 static NTSTATUS pdb_samba_dsdb_set_account_policy(struct pdb_methods *m,
1837                                            enum pdb_policy_type type,
1838                                            uint32_t value)
1839 {
1840         return account_policy_set(type, value)
1841                 ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1842 }
1843
1844 static NTSTATUS pdb_samba_dsdb_get_seq_num(struct pdb_methods *m,
1845                                     time_t *seq_num_out)
1846 {
1847         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1848                 m->private_data, struct pdb_samba_dsdb_state);
1849         uint64_t seq_num;
1850         int ret = ldb_sequence_number(state->ldb, LDB_SEQ_HIGHEST_SEQ, &seq_num);
1851         if (ret == LDB_SUCCESS) {
1852                 *seq_num_out = seq_num;
1853                 return NT_STATUS_OK;
1854         } else {
1855                 return NT_STATUS_UNSUCCESSFUL;
1856         }
1857 }
1858
1859 struct pdb_samba_dsdb_search_state {
1860         uint32_t acct_flags;
1861         struct samr_displayentry *entries;
1862         uint32_t num_entries;
1863         ssize_t array_size;
1864         uint32_t current;
1865 };
1866
1867 static bool pdb_samba_dsdb_next_entry(struct pdb_search *search,
1868                                struct samr_displayentry *entry)
1869 {
1870         struct pdb_samba_dsdb_search_state *state = talloc_get_type_abort(
1871                 search->private_data, struct pdb_samba_dsdb_search_state);
1872
1873         if (state->current == state->num_entries) {
1874                 return false;
1875         }
1876
1877         entry->idx = state->entries[state->current].idx;
1878         entry->rid = state->entries[state->current].rid;
1879         entry->acct_flags = state->entries[state->current].acct_flags;
1880
1881         entry->account_name = talloc_strdup(
1882                 search, state->entries[state->current].account_name);
1883         entry->fullname = talloc_strdup(
1884                 search, state->entries[state->current].fullname);
1885         entry->description = talloc_strdup(
1886                 search, state->entries[state->current].description);
1887
1888         state->current += 1;
1889         return true;
1890 }
1891
1892 static void pdb_samba_dsdb_search_end(struct pdb_search *search)
1893 {
1894         struct pdb_samba_dsdb_search_state *state = talloc_get_type_abort(
1895                 search->private_data, struct pdb_samba_dsdb_search_state);
1896         talloc_free(state);
1897 }
1898
1899 static bool pdb_samba_dsdb_search_filter(struct pdb_methods *m,
1900                                      struct pdb_search *search,
1901                                      struct pdb_samba_dsdb_search_state **pstate,
1902                                      const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(4, 5)
1903 {
1904         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
1905                 m->private_data, struct pdb_samba_dsdb_state);
1906         struct pdb_samba_dsdb_search_state *sstate;
1907         const char * attrs[] = { "objectSid", "sAMAccountName", "displayName",
1908                                  "userAccountControl", "description", NULL };
1909         struct ldb_result *res;
1910         int i, rc, num_users;
1911
1912         va_list ap;
1913         char *expression = NULL;
1914
1915         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1916         if (!tmp_ctx) {
1917                 return false;
1918         }
1919
1920         va_start(ap, exp_fmt);
1921         expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
1922         va_end(ap);
1923
1924         if (!expression) {
1925                 talloc_free(tmp_ctx);
1926                 return LDB_ERR_OPERATIONS_ERROR;
1927         }
1928
1929         sstate = talloc_zero(tmp_ctx, struct pdb_samba_dsdb_search_state);
1930         if (sstate == NULL) {
1931                 talloc_free(tmp_ctx);
1932                 return false;
1933         }
1934
1935         rc = dsdb_search(state->ldb, tmp_ctx, &res, ldb_get_default_basedn(state->ldb), LDB_SCOPE_SUBTREE, attrs, 0, "%s", expression);
1936         if (rc != LDB_SUCCESS) {
1937                 talloc_free(tmp_ctx);
1938                 DEBUG(10, ("dsdb_search failed: %s\n",
1939                            ldb_errstring(state->ldb)));
1940                 return false;
1941         }
1942
1943         num_users = res->count;
1944
1945         sstate->entries = talloc_array(sstate, struct samr_displayentry,
1946                                        num_users);
1947         if (sstate->entries == NULL) {
1948                 talloc_free(tmp_ctx);
1949                 DEBUG(10, ("talloc failed\n"));
1950                 return false;
1951         }
1952
1953         sstate->num_entries = 0;
1954
1955         for (i=0; i<num_users; i++) {
1956                 struct samr_displayentry *e;
1957                 struct dom_sid *sid;
1958
1959                 e = &sstate->entries[sstate->num_entries];
1960
1961                 e->idx = sstate->num_entries;
1962                 sid = samdb_result_dom_sid(tmp_ctx, res->msgs[i], "objectSid");
1963                 if (!sid) {
1964                         talloc_free(tmp_ctx);
1965                         DEBUG(10, ("Could not pull SID\n"));
1966                         return false;
1967                 }
1968                 sid_peek_rid(sid, &e->rid);
1969
1970                 e->acct_flags = samdb_result_acct_flags(res->msgs[i], "userAccountControl");
1971                 e->account_name = ldb_msg_find_attr_as_string(
1972                         res->msgs[i], "samAccountName", NULL);
1973                 if (e->account_name == NULL) {
1974                         talloc_free(tmp_ctx);
1975                         return false;
1976                 }
1977                 e->fullname = ldb_msg_find_attr_as_string(
1978                         res->msgs[i], "displayName", "");
1979                 e->description = ldb_msg_find_attr_as_string(
1980                         res->msgs[i], "description", "");
1981
1982                 sstate->num_entries += 1;
1983                 if (sstate->num_entries >= num_users) {
1984                         break;
1985                 }
1986         }
1987         talloc_steal(sstate->entries, res->msgs);
1988         search->private_data = talloc_steal(search, sstate);
1989         search->next_entry = pdb_samba_dsdb_next_entry;
1990         search->search_end = pdb_samba_dsdb_search_end;
1991         *pstate = sstate;
1992         talloc_free(tmp_ctx);
1993         return true;
1994 }
1995
1996 static bool pdb_samba_dsdb_search_users(struct pdb_methods *m,
1997                                  struct pdb_search *search,
1998                                  uint32 acct_flags)
1999 {
2000         struct pdb_samba_dsdb_search_state *sstate;
2001         bool ret;
2002
2003         ret = pdb_samba_dsdb_search_filter(m, search, &sstate, "(objectclass=user)");
2004         if (!ret) {
2005                 return false;
2006         }
2007         sstate->acct_flags = acct_flags;
2008         return true;
2009 }
2010
2011 static bool pdb_samba_dsdb_search_groups(struct pdb_methods *m,
2012                                   struct pdb_search *search)
2013 {
2014         struct pdb_samba_dsdb_search_state *sstate;
2015         bool ret;
2016
2017         ret = pdb_samba_dsdb_search_filter(m, search, &sstate,
2018                                        "(&(grouptype=%d)(objectclass=group))",
2019                                        GTYPE_SECURITY_GLOBAL_GROUP);
2020         if (!ret) {
2021                 return false;
2022         }
2023         sstate->acct_flags = 0;
2024         return true;
2025 }
2026
2027 static bool pdb_samba_dsdb_search_aliases(struct pdb_methods *m,
2028                                    struct pdb_search *search,
2029                                    const struct dom_sid *sid)
2030 {
2031         struct pdb_samba_dsdb_search_state *sstate;
2032         bool ret;
2033
2034         ret = pdb_samba_dsdb_search_filter(m, search, &sstate,
2035                                        "(&(grouptype=%d)(objectclass=group))",
2036                                        sid_check_is_builtin(sid)
2037                                        ? GTYPE_SECURITY_BUILTIN_LOCAL_GROUP
2038                                        : GTYPE_SECURITY_DOMAIN_LOCAL_GROUP);
2039         if (!ret) {
2040                 return false;
2041         }
2042         sstate->acct_flags = 0;
2043         return true;
2044 }
2045
2046 /* 
2047  * Instead of taking a gid or uid, this function takes a pointer to a 
2048  * unixid. 
2049  *
2050  * This acts as an in-out variable so that the idmap functions can correctly
2051  * receive ID_TYPE_BOTH, and this function ensures cache details are filled
2052  * correctly rather than forcing the cache to store ID_TYPE_UID or ID_TYPE_GID. 
2053  */
2054 static bool pdb_samba_dsdb_id_to_sid(struct pdb_methods *m, struct unixid *id,
2055                                      struct dom_sid *sid)
2056 {
2057         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
2058                 m->private_data, struct pdb_samba_dsdb_state);
2059         NTSTATUS status;
2060         struct id_map id_map;
2061         struct id_map *id_maps[2];
2062         TALLOC_CTX *tmp_ctx = talloc_stackframe();
2063         if (!tmp_ctx) {
2064                 return false;
2065         }
2066
2067         id_map.xid = *id;
2068         id_maps[0] = &id_map;
2069         id_maps[1] = NULL;
2070
2071         status = idmap_xids_to_sids(state->idmap_ctx, tmp_ctx, id_maps);
2072         if (!NT_STATUS_IS_OK(status)) {
2073                 talloc_free(tmp_ctx);
2074                 return false;
2075         }
2076
2077         if (id_map.xid.type != ID_TYPE_NOT_SPECIFIED) {
2078                 id->type = id_map.xid.type;
2079         }
2080         *sid = *id_map.sid;
2081         talloc_free(tmp_ctx);
2082         return true;
2083 }
2084
2085 static bool pdb_samba_dsdb_sid_to_id(struct pdb_methods *m, const struct dom_sid *sid,
2086                                  struct unixid *id)
2087 {
2088         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
2089                 m->private_data, struct pdb_samba_dsdb_state);
2090         struct id_map id_map;
2091         struct id_map *id_maps[2];
2092         NTSTATUS status;
2093         TALLOC_CTX *tmp_ctx = talloc_stackframe();
2094         if (!tmp_ctx) {
2095                 return false;
2096         }
2097
2098         ZERO_STRUCT(id_map);
2099         id_map.sid = discard_const_p(struct dom_sid, sid);
2100         id_maps[0] = &id_map;
2101         id_maps[1] = NULL;
2102
2103         status = idmap_sids_to_xids(state->idmap_ctx, tmp_ctx, id_maps);
2104         talloc_free(tmp_ctx);
2105         if (!NT_STATUS_IS_OK(status)) {
2106                 return false;
2107         }
2108         if (id_map.xid.type != ID_TYPE_NOT_SPECIFIED) {
2109                 *id = id_map.xid;
2110                 return true;
2111         }
2112         return false;
2113 }
2114
2115 static uint32_t pdb_samba_dsdb_capabilities(struct pdb_methods *m)
2116 {
2117         return PDB_CAP_STORE_RIDS | PDB_CAP_ADS;
2118 }
2119
2120 static bool pdb_samba_dsdb_new_rid(struct pdb_methods *m, uint32 *rid)
2121 {
2122         return false;
2123 }
2124
2125 static bool pdb_samba_dsdb_get_trusteddom_pw(struct pdb_methods *m,
2126                                       const char *domain, char** pwd,
2127                                       struct dom_sid *sid,
2128                                       time_t *pass_last_set_time)
2129 {
2130         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
2131                 m->private_data, struct pdb_samba_dsdb_state);
2132         TALLOC_CTX *tmp_ctx = talloc_stackframe();
2133         const char * const attrs[] = {
2134                 "securityIdentifier",
2135                 "flatName",
2136                 "trustPartner",
2137                 "trustAuthOutgoing",
2138                 "whenCreated",
2139                 "msDS-SupportedEncryptionTypes",
2140                 "trustAttributes",
2141                 "trustDirection",
2142                 "trustType",
2143                 NULL
2144         };
2145         struct ldb_message *msg;
2146         const struct ldb_val *password_val;
2147         int trust_direction_flags;
2148         int trust_type;
2149         int i;
2150         DATA_BLOB password_utf16;
2151         struct trustAuthInOutBlob password_blob;
2152         struct AuthenticationInformationArray *auth_array;
2153         char *password_talloc;
2154         size_t password_len;
2155         enum ndr_err_code ndr_err;
2156         NTSTATUS status;
2157         const char *netbios_domain = NULL;
2158
2159         status = sam_get_results_trust(state->ldb, tmp_ctx, domain,
2160                                        NULL, attrs, &msg);
2161         if (!NT_STATUS_IS_OK(status)) {
2162                 /*
2163                  * This can be called to work out of a domain is
2164                  * trusted, rather than just to get the password
2165                  */
2166                 DEBUG(2, ("Failed to get trusted domain password for %s.  "
2167                           "It may not be a trusted domain.\n", domain));
2168                 TALLOC_FREE(tmp_ctx);
2169                 return false;
2170         }
2171
2172         netbios_domain = ldb_msg_find_attr_as_string(msg, "flatName", NULL);
2173         if (netbios_domain == NULL) {
2174                 DEBUG(2, ("Trusted domain %s has to flatName defined.\n",
2175                           domain));
2176                 TALLOC_FREE(tmp_ctx);
2177                 return false;
2178         }
2179
2180         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
2181         if (!(trust_direction_flags & LSA_TRUST_DIRECTION_OUTBOUND)) {
2182                 DEBUG(2, ("Trusted domain %s is is not an outbound trust.\n",
2183                           domain));
2184                 TALLOC_FREE(tmp_ctx);
2185                 return false;
2186         }
2187
2188         trust_type = ldb_msg_find_attr_as_int(msg, "trustType", 0);
2189         if (trust_type == LSA_TRUST_TYPE_MIT) {
2190                 DEBUG(1, ("Trusted domain %s is is not an AD trust "
2191                           "(trustType == LSA_TRUST_TYPE_MIT).\n",
2192                           domain));
2193                 TALLOC_FREE(tmp_ctx);
2194                 return false;
2195         }
2196
2197         password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
2198         if (password_val == NULL) {
2199                 DEBUG(2, ("Failed to get trusted domain password for %s, "
2200                           "attribute trustAuthOutgoing not returned.\n", domain));
2201                 TALLOC_FREE(tmp_ctx);
2202                 return false;
2203         }
2204
2205         ndr_err = ndr_pull_struct_blob(password_val, tmp_ctx, &password_blob,
2206                                 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2207         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2208                 DEBUG(0, ("Failed to get trusted domain password for %s, "
2209                           "attribute trustAuthOutgoing coult not be parsed %s.\n",
2210                           domain,
2211                           ndr_map_error2string(ndr_err)));
2212                 TALLOC_FREE(tmp_ctx);
2213                 return false;
2214         }
2215
2216         auth_array = &password_blob.current;
2217
2218         for (i=0; i < auth_array->count; i++) {
2219                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2220                         break;
2221                 }
2222         }
2223
2224         if (i == auth_array->count) {
2225                 DEBUG(0, ("Trusted domain %s does not have a "
2226                           "clear-text password stored\n",
2227                           domain));
2228                 TALLOC_FREE(tmp_ctx);
2229                 return false;
2230         }
2231
2232         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
2233                                          auth_array->array[i].AuthInfo.clear.size);
2234
2235         /*
2236          * In the future, make this function return a
2237          * cli_credentials that can store a MD4 hash with cli_credential_set_nt_hash()
2238          * but for now convert to UTF8 and fail if the string can not be converted.
2239          *
2240          * We can't safely convert the random strings windows uses into
2241          * utf8.
2242          */
2243         if (!convert_string_talloc(tmp_ctx,
2244                                    CH_UTF16MUNGED, CH_UTF8,
2245                                    password_utf16.data, password_utf16.length,
2246                                    (void *)&password_talloc,
2247                                    &password_len)) {
2248                 DEBUG(0, ("FIXME: Could not convert password for trusted domain %s"
2249                           " to UTF8. This may be a password set from Windows.\n",
2250                           domain));
2251                 TALLOC_FREE(tmp_ctx);
2252                 return false;
2253         }
2254         *pwd = SMB_STRNDUP(password_talloc, password_len);
2255         if (pass_last_set_time) {
2256                 *pass_last_set_time = nt_time_to_unix(auth_array->array[i].LastUpdateTime);
2257         }
2258
2259         TALLOC_FREE(tmp_ctx);
2260         return true;
2261 }
2262
2263 static NTSTATUS pdb_samba_dsdb_get_trusteddom_creds(struct pdb_methods *m,
2264                                                     const char *domain,
2265                                                     TALLOC_CTX *mem_ctx,
2266                                                     struct cli_credentials **_creds)
2267 {
2268         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
2269                 m->private_data, struct pdb_samba_dsdb_state);
2270         TALLOC_CTX *tmp_ctx = talloc_stackframe();
2271         const char * const attrs[] = {
2272                 "securityIdentifier",
2273                 "flatName",
2274                 "trustPartner",
2275                 "trustAuthOutgoing",
2276                 "whenCreated",
2277                 "msDS-SupportedEncryptionTypes",
2278                 "trustAttributes",
2279                 "trustDirection",
2280                 "trustType",
2281                 NULL
2282         };
2283         struct ldb_message *msg;
2284         const struct ldb_val *password_val;
2285         int trust_direction_flags;
2286         int trust_type;
2287         int i;
2288         DATA_BLOB password_utf16 = {};
2289         DATA_BLOB password_nt = {};
2290         struct trustAuthInOutBlob password_blob;
2291         struct AuthenticationInformationArray *auth_array = NULL;
2292         enum ndr_err_code ndr_err;
2293         NTSTATUS status;
2294         time_t last_set_time = 0;
2295         struct cli_credentials *creds = NULL;
2296         bool ok;
2297         const char *my_netbios_name = NULL;
2298         const char *my_netbios_domain = NULL;
2299         const char *netbios_domain = NULL;
2300         char *account_name = NULL;
2301         const char *dns_domain = NULL;
2302
2303         status = sam_get_results_trust(state->ldb, tmp_ctx, domain,
2304                                        NULL, attrs, &msg);
2305         if (!NT_STATUS_IS_OK(status)) {
2306                 /*
2307                  * This can be called to work out of a domain is
2308                  * trusted, rather than just to get the password
2309                  */
2310                 DEBUG(2, ("Failed to get trusted domain password for %s.  "
2311                           "It may not be a trusted domain.\n", domain));
2312                 TALLOC_FREE(tmp_ctx);
2313                 return status;
2314         }
2315
2316         netbios_domain = ldb_msg_find_attr_as_string(msg, "flatName", NULL);
2317         if (netbios_domain == NULL) {
2318                 DEBUG(2, ("Trusted domain %s has to flatName defined.\n",
2319                           domain));
2320                 TALLOC_FREE(tmp_ctx);
2321                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2322         }
2323
2324         dns_domain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
2325
2326         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
2327         if (!(trust_direction_flags & LSA_TRUST_DIRECTION_OUTBOUND)) {
2328                 DEBUG(2, ("Trusted domain %s is is not an outbound trust.\n",
2329                           domain));
2330                 TALLOC_FREE(tmp_ctx);
2331                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2332         }
2333
2334         trust_type = ldb_msg_find_attr_as_int(msg, "trustType", 0);
2335         if (trust_type == LSA_TRUST_TYPE_MIT) {
2336                 DEBUG(1, ("Trusted domain %s is is not an AD trust "
2337                           "(trustType == LSA_TRUST_TYPE_MIT).\n",
2338                           domain));
2339                 TALLOC_FREE(tmp_ctx);
2340                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2341         }
2342
2343         password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
2344         if (password_val == NULL) {
2345                 DEBUG(2, ("Failed to get trusted domain password for %s, "
2346                           "attribute trustAuthOutgoing not returned.\n", domain));
2347                 TALLOC_FREE(tmp_ctx);
2348                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2349         }
2350
2351         ndr_err = ndr_pull_struct_blob(password_val, tmp_ctx, &password_blob,
2352                                 (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
2353         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2354                 DEBUG(0, ("Failed to get trusted domain password for %s, "
2355                           "attribute trustAuthOutgoing coult not be parsed %s.\n",
2356                           domain,
2357                           ndr_map_error2string(ndr_err)));
2358                 TALLOC_FREE(tmp_ctx);
2359                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2360         }
2361
2362         auth_array = &password_blob.current;
2363
2364         for (i=0; i < auth_array->count; i++) {
2365                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
2366                         last_set_time = nt_time_to_unix(auth_array->array[i].LastUpdateTime);
2367
2368                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
2369                                                          auth_array->array[i].AuthInfo.clear.size);
2370                         password_nt = data_blob_null;
2371                         break;
2372                 }
2373
2374                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
2375                         last_set_time = nt_time_to_unix(auth_array->array[i].LastUpdateTime);
2376
2377                         password_nt = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
2378                                                       auth_array->array[i].AuthInfo.clear.size);
2379                 }
2380         }
2381
2382         if (password_utf16.length == 0 && password_nt.length == 0) {
2383                 DEBUG(0, ("Trusted domain %s does not have a "
2384                           "clear-text nor nt password stored\n",
2385                           domain));
2386                 TALLOC_FREE(tmp_ctx);
2387                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2388         }
2389
2390         my_netbios_name = lpcfg_netbios_name(state->lp_ctx);
2391         my_netbios_domain = lpcfg_workgroup(state->lp_ctx);
2392
2393         creds = cli_credentials_init(tmp_ctx);
2394         if (creds == NULL) {
2395                 TALLOC_FREE(tmp_ctx);
2396                 return NT_STATUS_NO_MEMORY;
2397         }
2398
2399         ok = cli_credentials_set_workstation(creds, my_netbios_name, CRED_SPECIFIED);
2400         if (!ok) {
2401                 TALLOC_FREE(tmp_ctx);
2402                 return NT_STATUS_NO_MEMORY;
2403         }
2404
2405         ok = cli_credentials_set_domain(creds, netbios_domain, CRED_SPECIFIED);
2406         if (!ok) {
2407                 TALLOC_FREE(tmp_ctx);
2408                 return NT_STATUS_NO_MEMORY;
2409         }
2410         ok = cli_credentials_set_realm(creds, dns_domain, CRED_SPECIFIED);
2411         if (!ok) {
2412                 TALLOC_FREE(tmp_ctx);
2413                 return NT_STATUS_NO_MEMORY;
2414         }
2415
2416         cli_credentials_set_secure_channel_type(creds, SEC_CHAN_DOMAIN);
2417
2418         account_name = talloc_asprintf(tmp_ctx, "%s$", my_netbios_domain);
2419         if (account_name == NULL) {
2420                 TALLOC_FREE(tmp_ctx);
2421                 return NT_STATUS_NO_MEMORY;
2422         }
2423
2424         ok = cli_credentials_set_username(creds, account_name, CRED_SPECIFIED);
2425         if (!ok) {
2426                 TALLOC_FREE(tmp_ctx);
2427                 return NT_STATUS_NO_MEMORY;
2428         }
2429
2430         if (password_nt.length == 16) {
2431                 struct samr_Password nt_hash;
2432
2433                 memcpy(nt_hash.hash, password_nt.data, 16);
2434
2435                 ok = cli_credentials_set_nt_hash(creds, &nt_hash,
2436                                                  CRED_SPECIFIED);
2437                 ZERO_STRUCT(nt_hash);
2438                 if (!ok) {
2439                         TALLOC_FREE(tmp_ctx);
2440                         return NT_STATUS_NO_MEMORY;
2441                 }
2442         }
2443
2444         if (password_utf16.length > 0) {
2445                 ok = cli_credentials_set_utf16_password(creds,
2446                                                         &password_utf16,
2447                                                         CRED_SPECIFIED);
2448                 if (!ok) {
2449                         TALLOC_FREE(tmp_ctx);
2450                         return NT_STATUS_NO_MEMORY;
2451                 }
2452         }
2453
2454         cli_credentials_set_password_last_changed_time(creds, last_set_time);
2455
2456         if (password_utf16.length > 0 && dns_domain != NULL) {
2457                 /*
2458                  * Force kerberos if this is an active directory domain
2459                  */
2460                 cli_credentials_set_kerberos_state(creds,
2461                                                    CRED_MUST_USE_KERBEROS);
2462         } else  {
2463                 /*
2464                  * TODO: we should allow krb5 with the raw nt hash.
2465                  */
2466                 cli_credentials_set_kerberos_state(creds,
2467                                                    CRED_DONT_USE_KERBEROS);
2468         }
2469
2470         *_creds = talloc_move(mem_ctx, &creds);
2471         TALLOC_FREE(tmp_ctx);
2472         return NT_STATUS_OK;
2473 }
2474
2475 static bool pdb_samba_dsdb_set_trusteddom_pw(struct pdb_methods *m,
2476                                       const char* domain, const char* pwd,
2477                                       const struct dom_sid *sid)
2478 {
2479         return false;
2480 }
2481
2482 static bool pdb_samba_dsdb_del_trusteddom_pw(struct pdb_methods *m,
2483                                       const char *domain)
2484 {
2485         return false;
2486 }
2487
2488 static NTSTATUS pdb_samba_dsdb_enum_trusteddoms(struct pdb_methods *m,
2489                                          TALLOC_CTX *mem_ctx,
2490                                          uint32 *num_domains,
2491                                          struct trustdom_info ***domains)
2492 {
2493         *num_domains = 0;
2494         *domains = NULL;
2495         return NT_STATUS_OK;
2496 }
2497
2498 static bool pdb_samba_dsdb_is_responsible_for_wellknown(struct pdb_methods *m)
2499 {
2500         return true;
2501 }
2502
2503 static bool pdb_samba_dsdb_is_responsible_for_everything_else(struct pdb_methods *m)
2504 {
2505         return true;
2506 }
2507
2508 static void pdb_samba_dsdb_init_methods(struct pdb_methods *m)
2509 {
2510         m->name = "samba_dsdb";
2511         m->get_domain_info = pdb_samba_dsdb_get_domain_info;
2512         m->getsampwnam = pdb_samba_dsdb_getsampwnam;
2513         m->getsampwsid = pdb_samba_dsdb_getsampwsid;
2514         m->create_user = pdb_samba_dsdb_create_user;
2515         m->delete_user = pdb_samba_dsdb_delete_user;
2516         m->add_sam_account = pdb_samba_dsdb_add_sam_account;
2517         m->update_sam_account = pdb_samba_dsdb_update_sam_account;
2518         m->delete_sam_account = pdb_samba_dsdb_delete_sam_account;
2519         m->rename_sam_account = pdb_samba_dsdb_rename_sam_account;
2520         m->update_login_attempts = pdb_samba_dsdb_update_login_attempts;
2521         m->getgrsid = pdb_samba_dsdb_getgrsid;
2522         m->getgrgid = pdb_samba_dsdb_getgrgid;
2523         m->getgrnam = pdb_samba_dsdb_getgrnam;
2524         m->create_dom_group = pdb_samba_dsdb_create_dom_group;
2525         m->delete_dom_group = pdb_samba_dsdb_delete_dom_group;
2526         m->add_group_mapping_entry = pdb_samba_dsdb_add_group_mapping_entry;
2527         m->update_group_mapping_entry = pdb_samba_dsdb_update_group_mapping_entry;
2528         m->delete_group_mapping_entry = pdb_samba_dsdb_delete_group_mapping_entry;
2529         m->enum_group_mapping = pdb_samba_dsdb_enum_group_mapping;
2530         m->enum_group_members = pdb_samba_dsdb_enum_group_members;
2531         m->enum_group_memberships = pdb_samba_dsdb_enum_group_memberships;
2532         m->set_unix_primary_group = pdb_samba_dsdb_set_unix_primary_group;
2533         m->add_groupmem = pdb_samba_dsdb_add_groupmem;
2534         m->del_groupmem = pdb_samba_dsdb_del_groupmem;
2535         m->create_alias = pdb_samba_dsdb_create_alias;
2536         m->delete_alias = pdb_samba_dsdb_delete_alias;
2537         m->get_aliasinfo = pdb_default_get_aliasinfo;
2538         m->add_aliasmem = pdb_samba_dsdb_add_aliasmem;
2539         m->del_aliasmem = pdb_samba_dsdb_del_aliasmem;
2540         m->enum_aliasmem = pdb_samba_dsdb_enum_aliasmem;
2541         m->enum_alias_memberships = pdb_samba_dsdb_enum_alias_memberships;
2542         m->lookup_rids = pdb_samba_dsdb_lookup_rids;
2543         m->lookup_names = pdb_samba_dsdb_lookup_names;
2544         m->get_account_policy = pdb_samba_dsdb_get_account_policy;
2545         m->set_account_policy = pdb_samba_dsdb_set_account_policy;
2546         m->get_seq_num = pdb_samba_dsdb_get_seq_num;
2547         m->search_users = pdb_samba_dsdb_search_users;
2548         m->search_groups = pdb_samba_dsdb_search_groups;
2549         m->search_aliases = pdb_samba_dsdb_search_aliases;
2550         m->id_to_sid = pdb_samba_dsdb_id_to_sid;
2551         m->sid_to_id = pdb_samba_dsdb_sid_to_id;
2552         m->capabilities = pdb_samba_dsdb_capabilities;
2553         m->new_rid = pdb_samba_dsdb_new_rid;
2554         m->get_trusteddom_pw = pdb_samba_dsdb_get_trusteddom_pw;
2555         m->get_trusteddom_creds = pdb_samba_dsdb_get_trusteddom_creds;
2556         m->set_trusteddom_pw = pdb_samba_dsdb_set_trusteddom_pw;
2557         m->del_trusteddom_pw = pdb_samba_dsdb_del_trusteddom_pw;
2558         m->enum_trusteddoms = pdb_samba_dsdb_enum_trusteddoms;
2559         m->is_responsible_for_wellknown =
2560                                 pdb_samba_dsdb_is_responsible_for_wellknown;
2561         m->is_responsible_for_everything_else =
2562                                 pdb_samba_dsdb_is_responsible_for_everything_else;
2563 }
2564
2565 static void free_private_data(void **vp)
2566 {
2567         struct pdb_samba_dsdb_state *state = talloc_get_type_abort(
2568                 *vp, struct pdb_samba_dsdb_state);
2569         talloc_unlink(state, state->ldb);
2570         return;
2571 }
2572
2573 static NTSTATUS pdb_samba_dsdb_init_secrets(struct pdb_methods *m)
2574 {
2575         struct pdb_domain_info *dom_info;
2576         struct dom_sid stored_sid;
2577         struct GUID stored_guid;
2578         bool sid_exists_and_matches = false;
2579         bool guid_exists_and_matches = false;
2580         bool ret;
2581
2582         dom_info = pdb_samba_dsdb_get_domain_info(m, m);
2583         if (!dom_info) {
2584                 return NT_STATUS_UNSUCCESSFUL;
2585         }
2586
2587         ret = secrets_fetch_domain_sid(dom_info->name, &stored_sid);
2588         if (ret) {
2589                 if (dom_sid_equal(&stored_sid, &dom_info->sid)) {
2590                         sid_exists_and_matches = true;
2591                 }
2592         }
2593
2594         if (sid_exists_and_matches == false) {
2595                 secrets_clear_domain_protection(dom_info->name);
2596                 ret = secrets_store_domain_sid(dom_info->name,
2597                                                &dom_info->sid);
2598                 ret &= secrets_mark_domain_protected(dom_info->name);
2599                 if (!ret) {
2600                         goto done;
2601                 }
2602         }
2603
2604         ret = secrets_fetch_domain_guid(dom_info->name, &stored_guid);
2605         if (ret) {
2606                 if (GUID_equal(&stored_guid, &dom_info->guid)) {
2607                         guid_exists_and_matches = true;
2608                 }
2609         }
2610
2611         if (guid_exists_and_matches == false) {
2612                 secrets_clear_domain_protection(dom_info->name);
2613                 ret = secrets_store_domain_guid(dom_info->name,
2614                                                &dom_info->guid);
2615                 ret &= secrets_mark_domain_protected(dom_info->name);
2616                 if (!ret) {
2617                         goto done;
2618                 }
2619         }
2620
2621 done:
2622         TALLOC_FREE(dom_info);
2623         if (!ret) {
2624                 return NT_STATUS_UNSUCCESSFUL;
2625         }
2626         return NT_STATUS_OK;
2627 }
2628
2629 static NTSTATUS pdb_init_samba_dsdb(struct pdb_methods **pdb_method,
2630                              const char *location)
2631 {
2632         struct pdb_methods *m;
2633         struct pdb_samba_dsdb_state *state;
2634         NTSTATUS status;
2635
2636         if ( !NT_STATUS_IS_OK(status = make_pdb_method( &m )) ) {
2637                 return status;
2638         }
2639
2640         state = talloc_zero(m, struct pdb_samba_dsdb_state);
2641         if (state == NULL) {
2642                 goto nomem;
2643         }
2644         m->private_data = state;
2645         m->free_private_data = free_private_data;
2646         pdb_samba_dsdb_init_methods(m);
2647
2648         state->ev = s4_event_context_init(state);
2649         if (!state->ev) {
2650                 DEBUG(0, ("s4_event_context_init failed\n"));
2651                 goto nomem;
2652         }
2653
2654         state->lp_ctx = loadparm_init_s3(state, loadparm_s3_helpers());
2655         if (state->lp_ctx == NULL) {
2656                 DEBUG(0, ("loadparm_init_s3 failed\n"));
2657                 goto nomem;
2658         }
2659
2660         if (location) {
2661                 state->ldb = samdb_connect_url(state,
2662                                    state->ev,
2663                                    state->lp_ctx,
2664                                    system_session(state->lp_ctx),
2665                                    0, location);
2666         } else {
2667                 state->ldb = samdb_connect(state,
2668                                    state->ev,
2669                                    state->lp_ctx,
2670                                    system_session(state->lp_ctx), 0);
2671         }
2672
2673         if (!state->ldb) {
2674                 DEBUG(0, ("samdb_connect failed\n"));
2675                 status = NT_STATUS_INTERNAL_ERROR;
2676                 goto fail;
2677         }
2678
2679         state->idmap_ctx = idmap_init(state, state->ev,
2680                                       state->lp_ctx);
2681         if (!state->idmap_ctx) {
2682                 DEBUG(0, ("idmap failed\n"));
2683                 status = NT_STATUS_INTERNAL_ERROR;
2684                 goto fail;
2685         }
2686
2687         status = pdb_samba_dsdb_init_secrets(m);
2688         if (!NT_STATUS_IS_OK(status)) {
2689                 DEBUG(10, ("pdb_samba_dsdb_init_secrets failed!\n"));
2690                 goto fail;
2691         }
2692
2693         *pdb_method = m;
2694         return NT_STATUS_OK;
2695 nomem:
2696         status = NT_STATUS_NO_MEMORY;
2697 fail:
2698         TALLOC_FREE(m);
2699         return status;
2700 }
2701
2702 NTSTATUS pdb_samba_dsdb_init(void);
2703 NTSTATUS pdb_samba_dsdb_init(void)
2704 {
2705         NTSTATUS status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "samba_dsdb",
2706                                               pdb_init_samba_dsdb);
2707         if (!NT_STATUS_IS_OK(status)) {
2708                 return status;
2709         }
2710         return smb_register_passdb(PASSDB_INTERFACE_VERSION, "samba4",
2711                                    pdb_init_samba_dsdb);
2712 }