s4-dsdb: added dsdb_find_guid_attr_by_dn()
[metze/samba/wip.git] / source4 / dsdb / common / util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
5    Copyright (C) Andrew Tridgell 2004
6    Copyright (C) Volker Lendecke 2004
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006
8    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "events/events.h"
26 #include "ldb.h"
27 #include "ldb_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "../lib/crypto/crypto.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "libcli/security/security.h"
32 #include "librpc/gen_ndr/ndr_security.h"
33 #include "librpc/gen_ndr/ndr_misc.h"
34 #include "../libds/common/flags.h"
35 #include "dsdb/common/proto.h"
36 #include "libcli/ldap/ldap_ndr.h"
37 #include "param/param.h"
38 #include "libcli/auth/libcli_auth.h"
39 #include "librpc/gen_ndr/ndr_drsblobs.h"
40 #include "system/locale.h"
41
42 /*
43   search the sam for the specified attributes in a specific domain, filter on
44   objectSid being in domain_sid.
45 */
46 int samdb_search_domain(struct ldb_context *sam_ldb,
47                         TALLOC_CTX *mem_ctx, 
48                         struct ldb_dn *basedn,
49                         struct ldb_message ***res,
50                         const char * const *attrs,
51                         const struct dom_sid *domain_sid,
52                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
53 {
54         va_list ap;
55         int i, count;
56
57         va_start(ap, format);
58         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
59                                res, attrs, format, ap);
60         va_end(ap);
61
62         i=0;
63
64         while (i<count) {
65                 struct dom_sid *entry_sid;
66
67                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
68
69                 if ((entry_sid == NULL) ||
70                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
71                         /* Delete that entry from the result set */
72                         (*res)[i] = (*res)[count-1];
73                         count -= 1;
74                         talloc_free(entry_sid);
75                         continue;
76                 }
77                 talloc_free(entry_sid);
78                 i += 1;
79         }
80
81         return count;
82 }
83
84 /*
85   search the sam for a single string attribute in exactly 1 record
86 */
87 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
88                                   TALLOC_CTX *mem_ctx,
89                                   struct ldb_dn *basedn,
90                                   const char *attr_name,
91                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
92 {
93         int count;
94         const char *attrs[2] = { NULL, NULL };
95         struct ldb_message **res = NULL;
96
97         attrs[0] = attr_name;
98
99         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
100         if (count > 1) {                
101                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
102                          attr_name, format, count));
103         }
104         if (count != 1) {
105                 talloc_free(res);
106                 return NULL;
107         }
108
109         return samdb_result_string(res[0], attr_name, NULL);
110 }
111
112 /*
113   search the sam for a single string attribute in exactly 1 record
114 */
115 const char *samdb_search_string(struct ldb_context *sam_ldb,
116                                 TALLOC_CTX *mem_ctx,
117                                 struct ldb_dn *basedn,
118                                 const char *attr_name,
119                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
120 {
121         va_list ap;
122         const char *str;
123
124         va_start(ap, format);
125         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
126         va_end(ap);
127
128         return str;
129 }
130
131 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
132                                TALLOC_CTX *mem_ctx,
133                                struct ldb_dn *basedn,
134                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
135 {
136         va_list ap;
137         struct ldb_dn *ret;
138         struct ldb_message **res = NULL;
139         int count;
140
141         va_start(ap, format);
142         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
143         va_end(ap);
144
145         if (count != 1) return NULL;
146
147         ret = talloc_steal(mem_ctx, res[0]->dn);
148         talloc_free(res);
149
150         return ret;
151 }
152
153 /*
154   search the sam for a dom_sid attribute in exactly 1 record
155 */
156 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
157                                      TALLOC_CTX *mem_ctx,
158                                      struct ldb_dn *basedn,
159                                      const char *attr_name,
160                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
161 {
162         va_list ap;
163         int count;
164         struct ldb_message **res;
165         const char *attrs[2] = { NULL, NULL };
166         struct dom_sid *sid;
167
168         attrs[0] = attr_name;
169
170         va_start(ap, format);
171         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
172         va_end(ap);
173         if (count > 1) {                
174                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
175                          attr_name, format, count));
176         }
177         if (count != 1) {
178                 talloc_free(res);
179                 return NULL;
180         }
181         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
182         talloc_free(res);
183         return sid;     
184 }
185
186 /*
187   return the count of the number of records in the sam matching the query
188 */
189 int samdb_search_count(struct ldb_context *sam_ldb,
190                        struct ldb_dn *basedn,
191                        const char *format, ...) _PRINTF_ATTRIBUTE(3,4)
192 {
193         va_list ap;
194         struct ldb_message **res;
195         const char *attrs[] = { NULL };
196         int ret;
197         TALLOC_CTX *tmp_ctx = talloc_new(sam_ldb);
198
199         va_start(ap, format);
200         ret = gendb_search_v(sam_ldb, tmp_ctx, basedn, &res, attrs, format, ap);
201         va_end(ap);
202         talloc_free(tmp_ctx);
203
204         return ret;
205 }
206
207
208 /*
209   search the sam for a single integer attribute in exactly 1 record
210 */
211 uint_t samdb_search_uint(struct ldb_context *sam_ldb,
212                          TALLOC_CTX *mem_ctx,
213                          uint_t default_value,
214                          struct ldb_dn *basedn,
215                          const char *attr_name,
216                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
217 {
218         va_list ap;
219         int count;
220         struct ldb_message **res;
221         const char *attrs[2] = { NULL, NULL };
222
223         attrs[0] = attr_name;
224
225         va_start(ap, format);
226         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
227         va_end(ap);
228
229         if (count != 1) {
230                 return default_value;
231         }
232
233         return samdb_result_uint(res[0], attr_name, default_value);
234 }
235
236 /*
237   search the sam for a single signed 64 bit integer attribute in exactly 1 record
238 */
239 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
240                            TALLOC_CTX *mem_ctx,
241                            int64_t default_value,
242                            struct ldb_dn *basedn,
243                            const char *attr_name,
244                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
245 {
246         va_list ap;
247         int count;
248         struct ldb_message **res;
249         const char *attrs[2] = { NULL, NULL };
250
251         attrs[0] = attr_name;
252
253         va_start(ap, format);
254         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
255         va_end(ap);
256
257         if (count != 1) {
258                 return default_value;
259         }
260
261         return samdb_result_int64(res[0], attr_name, default_value);
262 }
263
264 /*
265   search the sam for multipe records each giving a single string attribute
266   return the number of matches, or -1 on error
267 */
268 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
269                                  TALLOC_CTX *mem_ctx,
270                                  struct ldb_dn *basedn,
271                                  const char ***strs,
272                                  const char *attr_name,
273                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
274 {
275         va_list ap;
276         int count, i;
277         const char *attrs[2] = { NULL, NULL };
278         struct ldb_message **res = NULL;
279
280         attrs[0] = attr_name;
281
282         va_start(ap, format);
283         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
284         va_end(ap);
285
286         if (count <= 0) {
287                 return count;
288         }
289
290         /* make sure its single valued */
291         for (i=0;i<count;i++) {
292                 if (res[i]->num_elements != 1) {
293                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
294                                  attr_name, format));
295                         talloc_free(res);
296                         return -1;
297                 }
298         }
299
300         *strs = talloc_array(mem_ctx, const char *, count+1);
301         if (! *strs) {
302                 talloc_free(res);
303                 return -1;
304         }
305
306         for (i=0;i<count;i++) {
307                 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
308         }
309         (*strs)[count] = NULL;
310
311         return count;
312 }
313
314 /*
315   pull a uint from a result set. 
316 */
317 uint_t samdb_result_uint(const struct ldb_message *msg, const char *attr, uint_t default_value)
318 {
319         return ldb_msg_find_attr_as_uint(msg, attr, default_value);
320 }
321
322 /*
323   pull a (signed) int64 from a result set. 
324 */
325 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
326 {
327         return ldb_msg_find_attr_as_int64(msg, attr, default_value);
328 }
329
330 /*
331   pull a string from a result set. 
332 */
333 const char *samdb_result_string(const struct ldb_message *msg, const char *attr, 
334                                 const char *default_value)
335 {
336         return ldb_msg_find_attr_as_string(msg, attr, default_value);
337 }
338
339 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
340                                const char *attr, struct ldb_dn *default_value)
341 {
342         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
343         if (!ret_dn) {
344                 return default_value;
345         }
346         return ret_dn;
347 }
348
349 /*
350   pull a rid from a objectSid in a result set. 
351 */
352 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
353                                    const char *attr, uint32_t default_value)
354 {
355         struct dom_sid *sid;
356         uint32_t rid;
357
358         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
359         if (sid == NULL) {
360                 return default_value;
361         }
362         rid = sid->sub_auths[sid->num_auths-1];
363         talloc_free(sid);
364         return rid;
365 }
366
367 /*
368   pull a dom_sid structure from a objectSid in a result set. 
369 */
370 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
371                                      const char *attr)
372 {
373         const struct ldb_val *v;
374         struct dom_sid *sid;
375         enum ndr_err_code ndr_err;
376         v = ldb_msg_find_ldb_val(msg, attr);
377         if (v == NULL) {
378                 return NULL;
379         }
380         sid = talloc(mem_ctx, struct dom_sid);
381         if (sid == NULL) {
382                 return NULL;
383         }
384         ndr_err = ndr_pull_struct_blob(v, sid, NULL, sid,
385                                        (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
386         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
387                 talloc_free(sid);
388                 return NULL;
389         }
390         return sid;
391 }
392
393 /*
394   pull a guid structure from a objectGUID in a result set. 
395 */
396 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
397 {
398         const struct ldb_val *v;
399         struct GUID guid;
400         NTSTATUS status;
401
402         v = ldb_msg_find_ldb_val(msg, attr);
403         if (!v) return GUID_zero();
404
405         status = GUID_from_ndr_blob(v, &guid);
406         if (!NT_STATUS_IS_OK(status)) {
407                 return GUID_zero();
408         }
409
410         return guid;
411 }
412
413 /*
414   pull a sid prefix from a objectSid in a result set. 
415   this is used to find the domain sid for a user
416 */
417 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
418                                         const char *attr)
419 {
420         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
421         if (!sid || sid->num_auths < 1) return NULL;
422         sid->num_auths--;
423         return sid;
424 }
425
426 /*
427   pull a NTTIME in a result set. 
428 */
429 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
430                            NTTIME default_value)
431 {
432         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
433 }
434
435 /*
436  * Windows stores 0 for lastLogoff.
437  * But when a MS DC return the lastLogoff (as Logoff Time)
438  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
439  * cause windows 2008 and newer version to fail for SMB requests
440  */
441 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
442 {
443         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
444
445         if (ret == 0)
446                 ret = 0x7FFFFFFFFFFFFFFFULL;
447
448         return ret;
449 }
450
451 /*
452  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
453  * indicate an account doesn't expire.
454  *
455  * When Windows initially creates an account, it sets
456  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
457  * when changing from an account having a specific expiration date to
458  * that account never expiring, it sets accountExpires = 0.
459  *
460  * Consolidate that logic here to allow clearer logic for account expiry in
461  * the rest of the code.
462  */
463 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
464 {
465         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
466                                                  0);
467
468         if (ret == 0)
469                 ret = 0x7FFFFFFFFFFFFFFFULL;
470
471         return ret;
472 }
473
474 /*
475   pull a uint64_t from a result set. 
476 */
477 uint64_t samdb_result_uint64(const struct ldb_message *msg, const char *attr,
478                              uint64_t default_value)
479 {
480         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
481 }
482
483
484 /*
485   construct the allow_password_change field from the PwdLastSet attribute and the 
486   domain password settings
487 */
488 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
489                                           TALLOC_CTX *mem_ctx, 
490                                           struct ldb_dn *domain_dn, 
491                                           struct ldb_message *msg, 
492                                           const char *attr)
493 {
494         uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
495         int64_t minPwdAge;
496
497         if (attr_time == 0) {
498                 return 0;
499         }
500
501         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
502
503         /* yes, this is a -= not a += as minPwdAge is stored as the negative
504            of the number of 100-nano-seconds */
505         attr_time -= minPwdAge;
506
507         return attr_time;
508 }
509
510 /*
511   construct the force_password_change field from the PwdLastSet
512   attribute, the userAccountControl and the domain password settings
513 */
514 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb, 
515                                           TALLOC_CTX *mem_ctx, 
516                                           struct ldb_dn *domain_dn, 
517                                           struct ldb_message *msg)
518 {
519         uint64_t attr_time = samdb_result_uint64(msg, "pwdLastSet", 0);
520         uint32_t userAccountControl = samdb_result_uint64(msg, "userAccountControl", 0);
521         int64_t maxPwdAge;
522
523         /* Machine accounts don't expire, and there is a flag for 'no expiry' */
524         if (!(userAccountControl & UF_NORMAL_ACCOUNT)
525             || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
526                 return 0x7FFFFFFFFFFFFFFFULL;
527         }
528
529         if (attr_time == 0) {
530                 return 0;
531         }
532
533         maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "maxPwdAge", NULL);
534         if (maxPwdAge == 0) {
535                 return 0x7FFFFFFFFFFFFFFFULL;
536         } else {
537                 attr_time -= maxPwdAge;
538         }
539
540         return attr_time;
541 }
542
543 /*
544   pull a samr_Password structutre from a result set. 
545 */
546 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
547 {
548         struct samr_Password *hash = NULL;
549         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
550         if (val && (val->length >= sizeof(hash->hash))) {
551                 hash = talloc(mem_ctx, struct samr_Password);
552                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
553         }
554         return hash;
555 }
556
557 /*
558   pull an array of samr_Password structutres from a result set. 
559 */
560 uint_t samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
561                            const char *attr, struct samr_Password **hashes)
562 {
563         uint_t count, i;
564         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
565
566         *hashes = NULL;
567         if (!val) {
568                 return 0;
569         }
570         count = val->length / 16;
571         if (count == 0) {
572                 return 0;
573         }
574
575         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
576         if (! *hashes) {
577                 return 0;
578         }
579
580         for (i=0;i<count;i++) {
581                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
582         }
583
584         return count;
585 }
586
587 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg, 
588                                 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd) 
589 {
590         struct samr_Password *lmPwdHash, *ntPwdHash;
591         if (nt_pwd) {
592                 int num_nt;
593                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
594                 if (num_nt == 0) {
595                         *nt_pwd = NULL;
596                 } else if (num_nt > 1) {
597                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
598                 } else {
599                         *nt_pwd = &ntPwdHash[0];
600                 }
601         }
602         if (lm_pwd) {
603                 /* Ensure that if we have turned off LM
604                  * authentication, that we never use the LM hash, even
605                  * if we store it */
606                 if (lp_lanman_auth(lp_ctx)) {
607                         int num_lm;
608                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
609                         if (num_lm == 0) {
610                                 *lm_pwd = NULL;
611                         } else if (num_lm > 1) {
612                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
613                         } else {
614                                 *lm_pwd = &lmPwdHash[0];
615                         }
616                 } else {
617                         *lm_pwd = NULL;
618                 }
619         }
620         return NT_STATUS_OK;
621 }
622
623 /*
624   pull a samr_LogonHours structutre from a result set. 
625 */
626 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
627 {
628         struct samr_LogonHours hours;
629         const int units_per_week = 168;
630         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
631         ZERO_STRUCT(hours);
632         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week);
633         if (!hours.bits) {
634                 return hours;
635         }
636         hours.units_per_week = units_per_week;
637         memset(hours.bits, 0xFF, units_per_week);
638         if (val) {
639                 memcpy(hours.bits, val->data, MIN(val->length, units_per_week));
640         }
641         return hours;
642 }
643
644 /*
645   pull a set of account_flags from a result set. 
646
647   This requires that the attributes: 
648    pwdLastSet
649    userAccountControl
650   be included in 'msg'
651 */
652 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
653                                  struct ldb_message *msg, struct ldb_dn *domain_dn)
654 {
655         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
656         uint32_t acct_flags = ds_uf2acb(userAccountControl);
657         NTTIME must_change_time;
658         NTTIME now;
659
660         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
661                                                               domain_dn, msg);
662
663         /* Test account expire time */
664         unix_to_nt_time(&now, time(NULL));
665         /* check for expired password */
666         if (must_change_time < now) {
667                 acct_flags |= ACB_PW_EXPIRED;
668         }
669         return acct_flags;
670 }
671
672 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
673                                                 struct ldb_message *msg,
674                                                 const char *attr)
675 {
676         struct lsa_BinaryString s;
677         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
678
679         ZERO_STRUCT(s);
680
681         if (!val) {
682                 return s;
683         }
684
685         s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
686         if (!s.array) {
687                 return s;
688         }
689         s.length = s.size = val->length/2;
690         memcpy(s.array, val->data, val->length);
691
692         return s;
693 }
694
695 /* Find an attribute, with a particular value */
696
697 /* The current callers of this function expect a very specific
698  * behaviour: In particular, objectClass subclass equivilance is not
699  * wanted.  This means that we should not lookup the schema for the
700  * comparison function */
701 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb, 
702                                                  const struct ldb_message *msg, 
703                                                  const char *name, const char *value)
704 {
705         int i;
706         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
707
708         if (!el) {
709                 return NULL;
710         }
711
712         for (i=0;i<el->num_values;i++) {
713                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
714                         return el;
715                 }
716         }
717
718         return NULL;
719 }
720
721 int samdb_find_or_add_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
722 {
723         if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
724                 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
725         }
726         return LDB_SUCCESS;
727 }
728
729 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
730 {
731         struct ldb_message_element *el;
732
733         el = ldb_msg_find_element(msg, name);
734         if (el) {
735                 return LDB_SUCCESS;
736         }
737
738         return samdb_msg_add_string(ldb, msg, msg, name, set_value);
739 }
740
741
742
743 /*
744   add a string element to a message
745 */
746 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
747                          const char *attr_name, const char *str)
748 {
749         char *s = talloc_strdup(mem_ctx, str);
750         char *a = talloc_strdup(mem_ctx, attr_name);
751         if (s == NULL || a == NULL) {
752                 return LDB_ERR_OPERATIONS_ERROR;
753         }
754         return ldb_msg_add_string(msg, a, s);
755 }
756
757 /*
758   add a dom_sid element to a message
759 */
760 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
761                          const char *attr_name, struct dom_sid *sid)
762 {
763         struct ldb_val v;
764         enum ndr_err_code ndr_err;
765
766         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
767                                        lp_iconv_convenience(ldb_get_opaque(sam_ldb, "loadparm")),
768                                        sid,
769                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
770         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
771                 return -1;
772         }
773         return ldb_msg_add_value(msg, attr_name, &v, NULL);
774 }
775
776
777 /*
778   add a delete element operation to a message
779 */
780 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
781                          const char *attr_name)
782 {
783         /* we use an empty replace rather than a delete, as it allows for 
784            samdb_replace() to be used everywhere */
785         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
786 }
787
788 /*
789   add a add attribute value to a message
790 */
791 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
792                          const char *attr_name, const char *value)
793 {
794         struct ldb_message_element *el;
795         char *a, *v;
796         int ret;
797         a = talloc_strdup(mem_ctx, attr_name);
798         if (a == NULL)
799                 return -1;
800         v = talloc_strdup(mem_ctx, value);
801         if (v == NULL)
802                 return -1;
803         ret = ldb_msg_add_string(msg, a, v);
804         if (ret != 0)
805                 return ret;
806         el = ldb_msg_find_element(msg, a);
807         if (el == NULL)
808                 return -1;
809         el->flags = LDB_FLAG_MOD_ADD;
810         return 0;
811 }
812
813 /*
814   add a delete attribute value to a message
815 */
816 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
817                          const char *attr_name, const char *value)
818 {
819         struct ldb_message_element *el;
820         char *a, *v;
821         int ret;
822         a = talloc_strdup(mem_ctx, attr_name);
823         if (a == NULL)
824                 return -1;
825         v = talloc_strdup(mem_ctx, value);
826         if (v == NULL)
827                 return -1;
828         ret = ldb_msg_add_string(msg, a, v);
829         if (ret != 0)
830                 return ret;
831         el = ldb_msg_find_element(msg, a);
832         if (el == NULL)
833                 return -1;
834         el->flags = LDB_FLAG_MOD_DELETE;
835         return 0;
836 }
837
838 /*
839   add a int element to a message
840 */
841 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
842                        const char *attr_name, int v)
843 {
844         const char *s = talloc_asprintf(mem_ctx, "%d", v);
845         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
846 }
847
848 /*
849   add a uint_t element to a message
850 */
851 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
852                        const char *attr_name, uint_t v)
853 {
854         const char *s = talloc_asprintf(mem_ctx, "%u", v);
855         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
856 }
857
858 /*
859   add a (signed) int64_t element to a message
860 */
861 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
862                         const char *attr_name, int64_t v)
863 {
864         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
865         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
866 }
867
868 /*
869   add a uint64_t element to a message
870 */
871 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
872                         const char *attr_name, uint64_t v)
873 {
874         const char *s = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)v);
875         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
876 }
877
878 /*
879   add a samr_Password element to a message
880 */
881 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
882                        const char *attr_name, struct samr_Password *hash)
883 {
884         struct ldb_val val;
885         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
886         if (!val.data) {
887                 return -1;
888         }
889         val.length = 16;
890         return ldb_msg_add_value(msg, attr_name, &val, NULL);
891 }
892
893 /*
894   add a samr_Password array to a message
895 */
896 int samdb_msg_add_hashes(TALLOC_CTX *mem_ctx, struct ldb_message *msg,
897                          const char *attr_name, struct samr_Password *hashes, uint_t count)
898 {
899         struct ldb_val val;
900         int i;
901         val.data = talloc_array_size(mem_ctx, 16, count);
902         val.length = count*16;
903         if (!val.data) {
904                 return -1;
905         }
906         for (i=0;i<count;i++) {
907                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
908         }
909         return ldb_msg_add_value(msg, attr_name, &val, NULL);
910 }
911
912 /*
913   add a acct_flags element to a message
914 */
915 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
916                              const char *attr_name, uint32_t v)
917 {
918         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
919 }
920
921 /*
922   add a logon_hours element to a message
923 */
924 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
925                               const char *attr_name, struct samr_LogonHours *hours)
926 {
927         struct ldb_val val;
928         val.length = hours->units_per_week / 8;
929         val.data = hours->bits;
930         return ldb_msg_add_value(msg, attr_name, &val, NULL);
931 }
932
933 /*
934   add a parameters element to a message
935 */
936 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
937                              const char *attr_name, struct lsa_BinaryString *parameters)
938 {
939         struct ldb_val val;
940         val.length = parameters->length * 2;
941         val.data = (uint8_t *)parameters->array;
942         return ldb_msg_add_value(msg, attr_name, &val, NULL);
943 }
944 /*
945   add a general value element to a message
946 */
947 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
948                               const char *attr_name, const struct ldb_val *val)
949 {
950         return ldb_msg_add_value(msg, attr_name, val, NULL);
951 }
952
953 /*
954   sets a general value element to a message
955 */
956 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
957                         const char *attr_name, const struct ldb_val *val)
958 {
959         struct ldb_message_element *el;
960
961         el = ldb_msg_find_element(msg, attr_name);
962         if (el) {
963                 el->num_values = 0;
964         }
965         return ldb_msg_add_value(msg, attr_name, val, NULL);
966 }
967
968 /*
969   set a string element in a message
970 */
971 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
972                          const char *attr_name, const char *str)
973 {
974         struct ldb_message_element *el;
975
976         el = ldb_msg_find_element(msg, attr_name);
977         if (el) {
978                 el->num_values = 0;
979         }
980         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
981 }
982
983 /*
984   replace elements in a record
985 */
986 int samdb_replace(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg)
987 {
988         int i;
989
990         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
991         for (i=0;i<msg->num_elements;i++) {
992                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
993         }
994
995         /* modify the samdb record */
996         return ldb_modify(sam_ldb, msg);
997 }
998
999 /*
1000  * Handle ldb_request in transaction
1001  */
1002 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1003                                  struct ldb_request *req)
1004 {
1005         int ret;
1006
1007         ret = ldb_transaction_start(sam_ldb);
1008         if (ret != LDB_SUCCESS) {
1009                 return ret;
1010         }
1011
1012         ret = ldb_request(sam_ldb, req);
1013         if (ret == LDB_SUCCESS) {
1014                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1015         }
1016
1017         if (ret == LDB_SUCCESS) {
1018                 return ldb_transaction_commit(sam_ldb);
1019         }
1020         ldb_transaction_cancel(sam_ldb);
1021
1022         return ret;
1023 }
1024
1025 /*
1026  * replace elements in a record using LDB_CONTROL_AS_SYSTEM
1027  * used to skip access checks on operations
1028  * that are performed by the system
1029  */
1030 int samdb_replace_as_system(struct ldb_context *sam_ldb,
1031                             TALLOC_CTX *mem_ctx,
1032                             struct ldb_message *msg)
1033 {
1034         int i;
1035         int ldb_ret;
1036         struct ldb_request *req = NULL;
1037
1038         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
1039         for (i=0;i<msg->num_elements;i++) {
1040                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
1041         }
1042
1043
1044         ldb_ret = ldb_msg_sanity_check(sam_ldb, msg);
1045         if (ldb_ret != LDB_SUCCESS) {
1046                 return ldb_ret;
1047         }
1048
1049         ldb_ret = ldb_build_mod_req(&req, sam_ldb, mem_ctx,
1050                                     msg,
1051                                     NULL,
1052                                     NULL,
1053                                     ldb_op_default_callback,
1054                                     NULL);
1055
1056         if (ldb_ret != LDB_SUCCESS) {
1057                 talloc_free(req);
1058                 return ldb_ret;
1059         }
1060
1061         ldb_ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
1062         if (ldb_ret != LDB_SUCCESS) {
1063                 talloc_free(req);
1064                 return ldb_ret;
1065         }
1066
1067         /* do request and auto start a transaction */
1068         ldb_ret = dsdb_autotransaction_request(sam_ldb, req);
1069
1070         talloc_free(req);
1071         return ldb_ret;
1072 }
1073
1074 /*
1075   return a default security descriptor
1076 */
1077 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1078 {
1079         struct security_descriptor *sd;
1080
1081         sd = security_descriptor_initialise(mem_ctx);
1082
1083         return sd;
1084 }
1085
1086 struct ldb_dn *samdb_base_dn(struct ldb_context *sam_ctx) 
1087 {
1088         return ldb_get_default_basedn(sam_ctx);
1089 }
1090
1091 struct ldb_dn *samdb_config_dn(struct ldb_context *sam_ctx) 
1092 {
1093         return ldb_get_config_basedn(sam_ctx);
1094 }
1095
1096 struct ldb_dn *samdb_schema_dn(struct ldb_context *sam_ctx) 
1097 {
1098         return ldb_get_schema_basedn(sam_ctx);
1099 }
1100
1101 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1102 {
1103         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1104         struct ldb_dn *aggregate_dn;
1105         if (!schema_dn) {
1106                 return NULL;
1107         }
1108
1109         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1110         if (!aggregate_dn) {
1111                 return NULL;
1112         }
1113         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1114                 return NULL;
1115         }
1116         return aggregate_dn;
1117 }
1118
1119 struct ldb_dn *samdb_root_dn(struct ldb_context *sam_ctx) 
1120 {
1121         return ldb_get_root_basedn(sam_ctx);
1122 }
1123
1124 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1125 {
1126         struct ldb_dn *new_dn;
1127
1128         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1129         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1130                 talloc_free(new_dn);
1131                 return NULL;
1132         }
1133         return new_dn;
1134 }
1135
1136 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1137 {
1138         struct ldb_dn *new_dn;
1139
1140         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1141         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1142                 talloc_free(new_dn);
1143                 return NULL;
1144         }
1145         return new_dn;
1146 }
1147
1148 /*
1149   work out the domain sid for the current open ldb
1150 */
1151 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1152 {
1153         TALLOC_CTX *tmp_ctx;
1154         const struct dom_sid *domain_sid;
1155         const char *attrs[] = {
1156                 "objectSid",
1157                 NULL
1158         };
1159         struct ldb_result *res;
1160         int ret;
1161
1162         /* see if we have a cached copy */
1163         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1164         if (domain_sid) {
1165                 return domain_sid;
1166         }
1167
1168         tmp_ctx = talloc_new(ldb);
1169         if (tmp_ctx == NULL) {
1170                 goto failed;
1171         }
1172
1173         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1174
1175         if (ret != LDB_SUCCESS) {
1176                 goto failed;
1177         }
1178
1179         if (res->count != 1) {
1180                 goto failed;
1181         }
1182
1183         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1184         if (domain_sid == NULL) {
1185                 goto failed;
1186         }
1187
1188         /* cache the domain_sid in the ldb */
1189         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1190                 goto failed;
1191         }
1192
1193         talloc_steal(ldb, domain_sid);
1194         talloc_free(tmp_ctx);
1195
1196         return domain_sid;
1197
1198 failed:
1199         DEBUG(1,("Failed to find domain_sid for open ldb\n"));
1200         talloc_free(tmp_ctx);
1201         return NULL;
1202 }
1203
1204 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1205 {
1206         TALLOC_CTX *tmp_ctx;
1207         struct dom_sid *dom_sid_new;
1208         struct dom_sid *dom_sid_old;
1209
1210         /* see if we have a cached copy */
1211         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1212                                                      "cache.domain_sid"), struct dom_sid);
1213
1214         tmp_ctx = talloc_new(ldb);
1215         if (tmp_ctx == NULL) {
1216                 goto failed;
1217         }
1218
1219         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1220         if (!dom_sid_new) {
1221                 goto failed;
1222         }
1223
1224         /* cache the domain_sid in the ldb */
1225         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1226                 goto failed;
1227         }
1228
1229         talloc_steal(ldb, dom_sid_new);
1230         talloc_free(tmp_ctx);
1231         talloc_free(dom_sid_old);
1232
1233         return true;
1234
1235 failed:
1236         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1237         talloc_free(tmp_ctx);
1238         return false;
1239 }
1240
1241 /* Obtain the short name of the flexible single master operator
1242  * (FSMO), such as the PDC Emulator */
1243 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
1244                              const char *attr)
1245 {
1246         /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1247         struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1248         const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1249         const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1250
1251         if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1252                 /* Ensure this matches the format.  This gives us a
1253                  * bit more confidence that a 'cn' value will be a
1254                  * ascii string */
1255                 return NULL;
1256         }
1257         if (val) {
1258                 return (char *)val->data;
1259         }
1260         return NULL;
1261 }
1262
1263 /*
1264   work out the ntds settings dn for the current open ldb
1265 */
1266 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1267 {
1268         TALLOC_CTX *tmp_ctx;
1269         const char *root_attrs[] = { "dsServiceName", NULL };
1270         int ret;
1271         struct ldb_result *root_res;
1272         struct ldb_dn *settings_dn;
1273
1274         /* see if we have a cached copy */
1275         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.settings_dn");
1276         if (settings_dn) {
1277                 return settings_dn;
1278         }
1279
1280         tmp_ctx = talloc_new(ldb);
1281         if (tmp_ctx == NULL) {
1282                 goto failed;
1283         }
1284
1285         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1286         if (ret) {
1287                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1288                          ldb_errstring(ldb)));
1289                 goto failed;
1290         }
1291
1292         if (root_res->count != 1) {
1293                 goto failed;
1294         }
1295
1296         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1297
1298         /* cache the domain_sid in the ldb */
1299         if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1300                 goto failed;
1301         }
1302
1303         talloc_steal(ldb, settings_dn);
1304         talloc_free(tmp_ctx);
1305
1306         return settings_dn;
1307
1308 failed:
1309         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1310         talloc_free(tmp_ctx);
1311         return NULL;
1312 }
1313
1314 /*
1315   work out the ntds settings invocationId for the current open ldb
1316 */
1317 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1318 {
1319         TALLOC_CTX *tmp_ctx;
1320         const char *attrs[] = { "invocationId", NULL };
1321         int ret;
1322         struct ldb_result *res;
1323         struct GUID *invocation_id;
1324
1325         /* see if we have a cached copy */
1326         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1327         if (invocation_id) {
1328                 return invocation_id;
1329         }
1330
1331         tmp_ctx = talloc_new(ldb);
1332         if (tmp_ctx == NULL) {
1333                 goto failed;
1334         }
1335
1336         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1337         if (ret) {
1338                 goto failed;
1339         }
1340
1341         if (res->count != 1) {
1342                 goto failed;
1343         }
1344
1345         invocation_id = talloc(tmp_ctx, struct GUID);
1346         if (!invocation_id) {
1347                 goto failed;
1348         }
1349
1350         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1351
1352         /* cache the domain_sid in the ldb */
1353         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1354                 goto failed;
1355         }
1356
1357         talloc_steal(ldb, invocation_id);
1358         talloc_free(tmp_ctx);
1359
1360         return invocation_id;
1361
1362 failed:
1363         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1364         talloc_free(tmp_ctx);
1365         return NULL;
1366 }
1367
1368 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1369 {
1370         TALLOC_CTX *tmp_ctx;
1371         struct GUID *invocation_id_new;
1372         struct GUID *invocation_id_old;
1373
1374         /* see if we have a cached copy */
1375         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1376                                                          "cache.invocation_id");
1377
1378         tmp_ctx = talloc_new(ldb);
1379         if (tmp_ctx == NULL) {
1380                 goto failed;
1381         }
1382
1383         invocation_id_new = talloc(tmp_ctx, struct GUID);
1384         if (!invocation_id_new) {
1385                 goto failed;
1386         }
1387
1388         *invocation_id_new = *invocation_id_in;
1389
1390         /* cache the domain_sid in the ldb */
1391         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1392                 goto failed;
1393         }
1394
1395         talloc_steal(ldb, invocation_id_new);
1396         talloc_free(tmp_ctx);
1397         talloc_free(invocation_id_old);
1398
1399         return true;
1400
1401 failed:
1402         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1403         talloc_free(tmp_ctx);
1404         return false;
1405 }
1406
1407 /*
1408   work out the ntds settings objectGUID for the current open ldb
1409 */
1410 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1411 {
1412         TALLOC_CTX *tmp_ctx;
1413         const char *attrs[] = { "objectGUID", NULL };
1414         int ret;
1415         struct ldb_result *res;
1416         struct GUID *ntds_guid;
1417
1418         /* see if we have a cached copy */
1419         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1420         if (ntds_guid) {
1421                 return ntds_guid;
1422         }
1423
1424         tmp_ctx = talloc_new(ldb);
1425         if (tmp_ctx == NULL) {
1426                 goto failed;
1427         }
1428
1429         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1430         if (ret) {
1431                 goto failed;
1432         }
1433
1434         if (res->count != 1) {
1435                 goto failed;
1436         }
1437
1438         ntds_guid = talloc(tmp_ctx, struct GUID);
1439         if (!ntds_guid) {
1440                 goto failed;
1441         }
1442
1443         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1444
1445         /* cache the domain_sid in the ldb */
1446         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1447                 goto failed;
1448         }
1449
1450         talloc_steal(ldb, ntds_guid);
1451         talloc_free(tmp_ctx);
1452
1453         return ntds_guid;
1454
1455 failed:
1456         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1457         talloc_free(tmp_ctx);
1458         return NULL;
1459 }
1460
1461 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1462 {
1463         TALLOC_CTX *tmp_ctx;
1464         struct GUID *ntds_guid_new;
1465         struct GUID *ntds_guid_old;
1466
1467         /* see if we have a cached copy */
1468         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1469
1470         tmp_ctx = talloc_new(ldb);
1471         if (tmp_ctx == NULL) {
1472                 goto failed;
1473         }
1474
1475         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1476         if (!ntds_guid_new) {
1477                 goto failed;
1478         }
1479
1480         *ntds_guid_new = *ntds_guid_in;
1481
1482         /* cache the domain_sid in the ldb */
1483         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1484                 goto failed;
1485         }
1486
1487         talloc_steal(ldb, ntds_guid_new);
1488         talloc_free(tmp_ctx);
1489         talloc_free(ntds_guid_old);
1490
1491         return true;
1492
1493 failed:
1494         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1495         talloc_free(tmp_ctx);
1496         return false;
1497 }
1498
1499 /*
1500   work out the server dn for the current open ldb
1501 */
1502 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1503 {
1504         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1505 }
1506
1507 /*
1508   work out the server dn for the current open ldb
1509 */
1510 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1511 {
1512         struct ldb_dn *server_dn;
1513         struct ldb_dn *server_site_dn;
1514
1515         server_dn = samdb_server_dn(ldb, mem_ctx);
1516         if (!server_dn) return NULL;
1517
1518         server_site_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1519
1520         talloc_free(server_dn);
1521         return server_site_dn;
1522 }
1523
1524 /*
1525   find a 'reference' DN that points at another object
1526   (eg. serverReference, rIDManagerReference etc)
1527  */
1528 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1529                        const char *attribute, struct ldb_dn **dn)
1530 {
1531         const char *attrs[2];
1532         struct ldb_result *res;
1533         int ret;
1534
1535         attrs[0] = attribute;
1536         attrs[1] = NULL;
1537
1538         ret = ldb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, NULL);
1539         if (ret != LDB_SUCCESS) {
1540                 return ret;
1541         }
1542         if (res->count != 1) {
1543                 talloc_free(res);
1544                 return LDB_ERR_NO_SUCH_OBJECT;
1545         }
1546
1547         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1548         if (!*dn) {
1549                 talloc_free(res);
1550                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1551         }
1552
1553         talloc_free(res);
1554         return LDB_SUCCESS;
1555 }
1556
1557 /*
1558   find our machine account via the serverReference attribute in the
1559   server DN
1560  */
1561 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1562 {
1563         struct ldb_dn *server_dn;
1564         int ret;
1565
1566         server_dn = samdb_server_dn(ldb, mem_ctx);
1567         if (server_dn == NULL) {
1568                 return LDB_ERR_NO_SUCH_OBJECT;
1569         }
1570
1571         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1572         talloc_free(server_dn);
1573
1574         return ret;
1575 }
1576
1577 /*
1578   find the RID Manager$ DN via the rIDManagerReference attribute in the
1579   base DN
1580  */
1581 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1582 {
1583         return samdb_reference_dn(ldb, mem_ctx, samdb_base_dn(ldb), "rIDManagerReference", dn);
1584 }
1585
1586 /*
1587   find the RID Set DN via the rIDSetReferences attribute in our
1588   machine account DN
1589  */
1590 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1591 {
1592         struct ldb_dn *server_ref_dn;
1593         int ret;
1594
1595         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1596         if (ret != LDB_SUCCESS) {
1597                 return ret;
1598         }
1599         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1600         talloc_free(server_ref_dn);
1601         return ret;
1602 }
1603
1604 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1605 {
1606         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb, mem_ctx));
1607
1608         if (val != NULL)
1609                 return (const char *) val->data;
1610         else
1611                 return NULL;
1612 }
1613
1614 /*
1615   work out if we are the PDC for the domain of the current open ldb
1616 */
1617 bool samdb_is_pdc(struct ldb_context *ldb)
1618 {
1619         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1620         int ret;
1621         struct ldb_result *dom_res;
1622         TALLOC_CTX *tmp_ctx;
1623         bool is_pdc;
1624         struct ldb_dn *pdc;
1625
1626         tmp_ctx = talloc_new(ldb);
1627         if (tmp_ctx == NULL) {
1628                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1629                 return false;
1630         }
1631
1632         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1633         if (ret) {
1634                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1635                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1636                          ldb_errstring(ldb)));
1637                 goto failed;
1638         }
1639         if (dom_res->count != 1) {
1640                 goto failed;
1641         }
1642
1643         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1644
1645         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1646                 is_pdc = true;
1647         } else {
1648                 is_pdc = false;
1649         }
1650
1651         talloc_free(tmp_ctx);
1652
1653         return is_pdc;
1654
1655 failed:
1656         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1657         talloc_free(tmp_ctx);
1658         return false;
1659 }
1660
1661 /*
1662   work out if we are a Global Catalog server for the domain of the current open ldb
1663 */
1664 bool samdb_is_gc(struct ldb_context *ldb)
1665 {
1666         const char *attrs[] = { "options", NULL };
1667         int ret, options;
1668         struct ldb_result *res;
1669         TALLOC_CTX *tmp_ctx;
1670
1671         tmp_ctx = talloc_new(ldb);
1672         if (tmp_ctx == NULL) {
1673                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1674                 return false;
1675         }
1676
1677         /* Query cn=ntds settings,.... */
1678         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1679         if (ret) {
1680                 talloc_free(tmp_ctx);
1681                 return false;
1682         }
1683         if (res->count != 1) {
1684                 talloc_free(tmp_ctx);
1685                 return false;
1686         }
1687
1688         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1689         talloc_free(tmp_ctx);
1690
1691         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1692         if (options & 0x000000001) {
1693                 return true;
1694         }
1695         return false;
1696 }
1697
1698 /* Find a domain object in the parents of a particular DN.  */
1699 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1700                                    struct ldb_dn **parent_dn, const char **errstring)
1701 {
1702         TALLOC_CTX *local_ctx;
1703         struct ldb_dn *sdn = dn;
1704         struct ldb_result *res = NULL;
1705         int ret = 0;
1706         const char *attrs[] = { NULL };
1707
1708         local_ctx = talloc_new(mem_ctx);
1709         if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1710
1711         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1712                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1713                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1714                 if (ret == LDB_SUCCESS) {
1715                         if (res->count == 1) {
1716                                 break;
1717                         }
1718                 } else {
1719                         break;
1720                 }
1721         }
1722
1723         if (ret != LDB_SUCCESS) {
1724                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1725                                              ldb_dn_get_linearized(dn),
1726                                              ldb_dn_get_linearized(sdn),
1727                                              ldb_errstring(ldb));
1728                 talloc_free(local_ctx);
1729                 return ret;
1730         }
1731         if (res->count != 1) {
1732                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1733                                              ldb_dn_get_linearized(dn));
1734                 DEBUG(0,(__location__ ": %s\n", *errstring));
1735                 talloc_free(local_ctx);
1736                 return LDB_ERR_CONSTRAINT_VIOLATION;
1737         }
1738
1739         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1740         talloc_free(local_ctx);
1741         return ret;
1742 }
1743
1744
1745 /*
1746  * Performs checks on a user password (plaintext UNIX format - attribute
1747  * "password"). The remaining parameters have to be extracted from the domain
1748  * object in the AD.
1749  *
1750  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1751  */
1752 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1753                                                 const uint32_t pwdProperties,
1754                                                 const uint32_t minPwdLength)
1755 {
1756         /* checks if the "minPwdLength" property is satisfied */
1757         if (minPwdLength > password->length)
1758                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1759
1760         /* checks the password complexity */
1761         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1762                         && (password->data != NULL)
1763                         && (!check_password_quality((const char *) password->data)))
1764                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1765
1766         return SAMR_VALIDATION_STATUS_SUCCESS;
1767 }
1768
1769 /*
1770  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1771  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1772  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1773  * gives some more informations if the changed failed.
1774  *
1775  * The caller should have a LDB transaction wrapping this.
1776  *
1777  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1778  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1779  *   NT_STATUS_PASSWORD_RESTRICTION
1780  */
1781 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1782                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1783                             struct ldb_message *mod,
1784                             const DATA_BLOB *new_password,
1785                             struct samr_Password *param_lmNewHash,
1786                             struct samr_Password *param_ntNewHash,
1787                             bool user_change,
1788                             enum samPwdChangeReason *reject_reason,
1789                             struct samr_DomInfo1 **_dominfo)
1790 {
1791         const char * const user_attrs[] = { "userAccountControl",
1792                                             "lmPwdHistory",
1793                                             "ntPwdHistory", 
1794                                             "dBCSPwd", "unicodePwd", 
1795                                             "objectSid", 
1796                                             "pwdLastSet", NULL };
1797         const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1798                                               "pwdHistoryLength",
1799                                               "maxPwdAge", "minPwdAge", NULL };
1800         NTTIME pwdLastSet;
1801         uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1802         int64_t maxPwdAge, minPwdAge;
1803         uint32_t userAccountControl;
1804         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1805                 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1806         struct samr_Password local_lmNewHash, local_ntNewHash;
1807         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1808         struct dom_sid *domain_sid;
1809         struct ldb_message **res;
1810         bool restrictions;
1811         int count;
1812         time_t now = time(NULL);
1813         NTTIME now_nt;
1814         int i;
1815
1816         /* we need to know the time to compute password age */
1817         unix_to_nt_time(&now_nt, now);
1818
1819         /* pull all the user parameters */
1820         count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1821         if (count != 1) {
1822                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1823         }
1824         userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1825         sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1826                                          "lmPwdHistory", &sambaLMPwdHistory);
1827         sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1828                                          "ntPwdHistory", &sambaNTPwdHistory);
1829         lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1830         ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1831         pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1832
1833         /* Copy parameters */
1834         lmNewHash = param_lmNewHash;
1835         ntNewHash = param_ntNewHash;
1836
1837         /* Only non-trust accounts have restrictions (possibly this
1838          * test is the wrong way around, but I like to be restrictive
1839          * if possible */
1840         restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1841                                                |UF_WORKSTATION_TRUST_ACCOUNT
1842                                                |UF_SERVER_TRUST_ACCOUNT)); 
1843
1844         if (domain_dn != NULL) {
1845                 /* pull the domain parameters */
1846                 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1847                                                                 domain_attrs);
1848                 if (count != 1) {
1849                         DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n", 
1850                                   ldb_dn_get_linearized(domain_dn),
1851                                   ldb_dn_get_linearized(user_dn)));
1852                         return NT_STATUS_NO_SUCH_DOMAIN;
1853                 }
1854         } else {
1855                 /* work out the domain sid, and pull the domain from there */
1856                 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1857                                                                 "objectSid");
1858                 if (domain_sid == NULL) {
1859                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1860                 }
1861
1862                 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs, 
1863                                 "(objectSid=%s)",
1864                                 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1865                 if (count != 1) {
1866                         DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n", 
1867                                   dom_sid_string(mem_ctx, domain_sid),
1868                                   ldb_dn_get_linearized(user_dn)));
1869                         return NT_STATUS_NO_SUCH_DOMAIN;
1870                 }
1871         }
1872
1873         minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1874         pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1875         pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1876         maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1877         minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1878
1879         if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1880                 /* see [MS-ADTS] 2.2.15 */
1881                 minPwdLength = 0;
1882         }
1883
1884         if (_dominfo != NULL) {
1885                 struct samr_DomInfo1 *dominfo;
1886                 /* on failure we need to fill in the reject reasons */
1887                 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1888                 if (dominfo == NULL) {
1889                         return NT_STATUS_NO_MEMORY;
1890                 }
1891                 dominfo->min_password_length     = minPwdLength;
1892                 dominfo->password_properties     = pwdProperties;
1893                 dominfo->password_history_length = pwdHistoryLength;
1894                 dominfo->max_password_age        = maxPwdAge;
1895                 dominfo->min_password_age        = minPwdAge;
1896                 *_dominfo = dominfo;
1897         }
1898
1899         if ((restrictions != 0) && (new_password != 0)) {
1900                 char *new_pass;
1901
1902                 /* checks if the "minPwdLength" property is satisfied */
1903                 if ((restrictions != 0)
1904                         && (minPwdLength > utf16_len_n(
1905                                 new_password->data, new_password->length)/2)) {
1906                         if (reject_reason) {
1907                                 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1908                         }
1909                         return NT_STATUS_PASSWORD_RESTRICTION;
1910                 }
1911
1912                 /* Create the NT hash */
1913                 mdfour(local_ntNewHash.hash, new_password->data,
1914                                                         new_password->length);
1915
1916                 ntNewHash = &local_ntNewHash;
1917
1918                 /* Only check complexity if we can convert it at all.  Assuming unconvertable passwords are 'strong' */
1919                 if (convert_string_talloc_convenience(mem_ctx,
1920                           lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
1921                           CH_UTF16, CH_UNIX,
1922                           new_password->data, new_password->length,
1923                           (void **)&new_pass, NULL, false)) {
1924
1925                         /* checks the password complexity */
1926                         if ((restrictions != 0)
1927                                 && ((pwdProperties
1928                                         & DOMAIN_PASSWORD_COMPLEX) != 0)
1929                                 && (!check_password_quality(new_pass))) {
1930                                 if (reject_reason) {
1931                                         *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
1932                                 }
1933                                 return NT_STATUS_PASSWORD_RESTRICTION;
1934                         }
1935
1936                         /* compute the new lm hashes (for checking history - case insenitivly!) */
1937                         if (E_deshash(new_pass, local_lmNewHash.hash)) {
1938                                 lmNewHash = &local_lmNewHash;
1939                         }
1940                 }
1941         }
1942
1943         if ((restrictions != 0) && user_change) {
1944                 /* are all password changes disallowed? */
1945                 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
1946                         if (reject_reason) {
1947                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1948                         }
1949                         return NT_STATUS_PASSWORD_RESTRICTION;
1950                 }
1951
1952                 /* can this user change the password? */
1953                 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
1954                         if (reject_reason) {
1955                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1956                         }
1957                         return NT_STATUS_PASSWORD_RESTRICTION;
1958                 }
1959
1960                 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
1961                 if (pwdLastSet - minPwdAge > now_nt) {
1962                         if (reject_reason) {
1963                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1964                         }
1965                         return NT_STATUS_PASSWORD_RESTRICTION;
1966                 }
1967
1968                 /* check the immediately past password */
1969                 if (pwdHistoryLength > 0) {
1970                         if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
1971                                         lmPwdHash->hash, 16) == 0) {
1972                                 if (reject_reason) {
1973                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1974                                 }
1975                                 return NT_STATUS_PASSWORD_RESTRICTION;
1976                         }
1977                         if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
1978                                         ntPwdHash->hash, 16) == 0) {
1979                                 if (reject_reason) {
1980                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1981                                 }
1982                                 return NT_STATUS_PASSWORD_RESTRICTION;
1983                         }
1984                 }
1985
1986                 /* check the password history */
1987                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
1988                                                         pwdHistoryLength);
1989                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
1990                                                         pwdHistoryLength);
1991
1992                 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
1993                         if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
1994                                         16) == 0) {
1995                                 if (reject_reason) {
1996                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1997                                 }
1998                                 return NT_STATUS_PASSWORD_RESTRICTION;
1999                         }
2000                 }
2001                 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
2002                         if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
2003                                          16) == 0) {
2004                                 if (reject_reason) {
2005                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2006                                 }
2007                                 return NT_STATUS_PASSWORD_RESTRICTION;
2008                         }
2009                 }
2010         }
2011
2012 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
2013
2014         /* the password is acceptable. Start forming the new fields */
2015         if (new_password != NULL) {
2016                 /* if we know the cleartext UTF16 password, then set it.
2017                  * Modules in ldb will set all the appropriate
2018                  * hashes */
2019                 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
2020         } else {
2021                 /* we don't have the cleartext, so set what we have of the
2022                  * hashes */
2023
2024                 if (lmNewHash) {
2025                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
2026                 }
2027
2028                 if (ntNewHash) {
2029                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
2030                 }
2031         }
2032
2033         if (reject_reason) {
2034                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2035         }
2036         return NT_STATUS_OK;
2037 }
2038
2039
2040 /*
2041  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2042  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2043  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
2044  * gives some more informations if the changed failed.
2045  *
2046  * This wrapper function for "samdb_set_password" takes a SID as input rather
2047  * than a user DN.
2048  *
2049  * This call encapsulates a new LDB transaction for changing the password;
2050  * therefore the user hasn't to start a new one.
2051  *
2052  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2053  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2054  *   NT_STATUS_PASSWORD_RESTRICTION
2055  */
2056 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2057                                 const struct dom_sid *user_sid,
2058                                 const DATA_BLOB *new_password,
2059                                 struct samr_Password *lmNewHash, 
2060                                 struct samr_Password *ntNewHash,
2061                                 bool user_change,
2062                                 enum samPwdChangeReason *reject_reason,
2063                                 struct samr_DomInfo1 **_dominfo) 
2064 {
2065         NTSTATUS nt_status;
2066         struct ldb_dn *user_dn;
2067         struct ldb_message *msg;
2068         int ret;
2069
2070         ret = ldb_transaction_start(ldb);
2071         if (ret != LDB_SUCCESS) {
2072                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2073                 return NT_STATUS_TRANSACTION_ABORTED;
2074         }
2075
2076         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2077                                   "(&(objectSid=%s)(objectClass=user))", 
2078                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2079         if (!user_dn) {
2080                 ldb_transaction_cancel(ldb);
2081                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2082                           dom_sid_string(mem_ctx, user_sid)));
2083                 return NT_STATUS_NO_SUCH_USER;
2084         }
2085
2086         msg = ldb_msg_new(mem_ctx);
2087         if (msg == NULL) {
2088                 ldb_transaction_cancel(ldb);
2089                 talloc_free(user_dn);
2090                 return NT_STATUS_NO_MEMORY;
2091         }
2092
2093         msg->dn = ldb_dn_copy(msg, user_dn);
2094         if (!msg->dn) {
2095                 ldb_transaction_cancel(ldb);
2096                 talloc_free(user_dn);
2097                 talloc_free(msg);
2098                 return NT_STATUS_NO_MEMORY;
2099         }
2100
2101         nt_status = samdb_set_password(ldb, mem_ctx,
2102                                        user_dn, NULL,
2103                                        msg, new_password,
2104                                        lmNewHash, ntNewHash,
2105                                        user_change,
2106                                        reject_reason, _dominfo);
2107         if (!NT_STATUS_IS_OK(nt_status)) {
2108                 ldb_transaction_cancel(ldb);
2109                 talloc_free(user_dn);
2110                 talloc_free(msg);
2111                 return nt_status;
2112         }
2113
2114         /* modify the samdb record */
2115         ret = samdb_replace(ldb, mem_ctx, msg);
2116         if (ret != LDB_SUCCESS) {
2117                 ldb_transaction_cancel(ldb);
2118                 talloc_free(user_dn);
2119                 talloc_free(msg);
2120                 return NT_STATUS_ACCESS_DENIED;
2121         }
2122
2123         talloc_free(msg);
2124
2125         ret = ldb_transaction_commit(ldb);
2126         if (ret != LDB_SUCCESS) {
2127                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2128                          ldb_dn_get_linearized(user_dn),
2129                          ldb_errstring(ldb)));
2130                 talloc_free(user_dn);
2131                 return NT_STATUS_TRANSACTION_ABORTED;
2132         }
2133
2134         talloc_free(user_dn);
2135         return NT_STATUS_OK;
2136 }
2137
2138
2139 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2140                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2141 {
2142         struct ldb_message *msg;
2143         struct ldb_dn *basedn;
2144         char *sidstr;
2145         int ret;
2146
2147         sidstr = dom_sid_string(mem_ctx, sid);
2148         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2149
2150         /* We might have to create a ForeignSecurityPrincipal, even if this user
2151          * is in our own domain */
2152
2153         msg = ldb_msg_new(sidstr);
2154         if (msg == NULL) {
2155                 talloc_free(sidstr);
2156                 return NT_STATUS_NO_MEMORY;
2157         }
2158
2159         ret = dsdb_wellknown_dn(sam_ctx, sidstr, samdb_base_dn(sam_ctx),
2160                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2161                                 &basedn);
2162         if (ret != LDB_SUCCESS) {
2163                 DEBUG(0, ("Failed to find DN for "
2164                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2165                 talloc_free(sidstr);
2166                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2167         }
2168
2169         /* add core elements to the ldb_message for the alias */
2170         msg->dn = basedn;
2171         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2172                 talloc_free(sidstr);
2173                 return NT_STATUS_NO_MEMORY;
2174         }
2175
2176         samdb_msg_add_string(sam_ctx, msg, msg,
2177                              "objectClass",
2178                              "foreignSecurityPrincipal");
2179
2180         /* create the alias */
2181         ret = ldb_add(sam_ctx, msg);
2182         if (ret != LDB_SUCCESS) {
2183                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2184                          "record %s: %s\n", 
2185                          ldb_dn_get_linearized(msg->dn),
2186                          ldb_errstring(sam_ctx)));
2187                 talloc_free(sidstr);
2188                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2189         }
2190
2191         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2192         talloc_free(sidstr);
2193
2194         return NT_STATUS_OK;
2195 }
2196
2197
2198 /*
2199   Find the DN of a domain, assuming it to be a dotted.dns name
2200 */
2201
2202 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2203 {
2204         int i;
2205         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2206         const char *binary_encoded;
2207         const char **split_realm;
2208         struct ldb_dn *dn;
2209
2210         if (!tmp_ctx) {
2211                 return NULL;
2212         }
2213
2214         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2215         if (!split_realm) {
2216                 talloc_free(tmp_ctx);
2217                 return NULL;
2218         }
2219         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2220         for (i=0; split_realm[i]; i++) {
2221                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2222                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2223                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2224                                   binary_encoded, ldb_dn_get_linearized(dn)));
2225                         talloc_free(tmp_ctx);
2226                         return NULL;
2227                 }
2228         }
2229         if (!ldb_dn_validate(dn)) {
2230                 DEBUG(2, ("Failed to validated DN %s\n",
2231                           ldb_dn_get_linearized(dn)));
2232                 talloc_free(tmp_ctx);
2233                 return NULL;
2234         }
2235         talloc_free(tmp_ctx);
2236         return dn;
2237 }
2238
2239 /*
2240   Find the DN of a domain, be it the netbios or DNS name 
2241 */
2242 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2243                                   const char *domain_name) 
2244 {
2245         const char * const domain_ref_attrs[] = {
2246                 "ncName", NULL
2247         };
2248         const char * const domain_ref2_attrs[] = {
2249                 NULL
2250         };
2251         struct ldb_result *res_domain_ref;
2252         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2253         /* find the domain's DN */
2254         int ret_domain = ldb_search(ldb, mem_ctx,
2255                                             &res_domain_ref, 
2256                                             samdb_partitions_dn(ldb, mem_ctx), 
2257                                             LDB_SCOPE_ONELEVEL, 
2258                                             domain_ref_attrs,
2259                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2260                                             escaped_domain);
2261         if (ret_domain != 0) {
2262                 return NULL;
2263         }
2264
2265         if (res_domain_ref->count == 0) {
2266                 ret_domain = ldb_search(ldb, mem_ctx,
2267                                                 &res_domain_ref, 
2268                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2269                                                 LDB_SCOPE_BASE,
2270                                                 domain_ref2_attrs,
2271                                                 "(objectclass=domain)");
2272                 if (ret_domain != 0) {
2273                         return NULL;
2274                 }
2275
2276                 if (res_domain_ref->count == 1) {
2277                         return res_domain_ref->msgs[0]->dn;
2278                 }
2279                 return NULL;
2280         }
2281
2282         if (res_domain_ref->count > 1) {
2283                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2284                          ret_domain, domain_name));
2285                 return NULL;
2286         }
2287
2288         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2289
2290 }
2291
2292
2293 /*
2294   use a GUID to find a DN
2295  */
2296 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2297                          TALLOC_CTX *mem_ctx,
2298                          const char *guid_str, struct ldb_dn **dn)
2299 {
2300         int ret;
2301         struct ldb_result *res;
2302         const char *attrs[] = { NULL };
2303         struct ldb_request *search_req;
2304         char *expression;
2305         struct ldb_search_options_control *options;
2306
2307         expression = talloc_asprintf(mem_ctx, "objectGUID=%s", guid_str);
2308         if (!expression) {
2309                 DEBUG(0, (__location__ ": out of memory\n"));
2310                 return LDB_ERR_OPERATIONS_ERROR;
2311         }
2312
2313         res = talloc_zero(expression, struct ldb_result);
2314         if (!res) {
2315                 DEBUG(0, (__location__ ": out of memory\n"));
2316                 talloc_free(expression);
2317                 return LDB_ERR_OPERATIONS_ERROR;
2318         }
2319
2320         ret = ldb_build_search_req(&search_req, ldb, expression,
2321                                    ldb_get_default_basedn(ldb),
2322                                    LDB_SCOPE_SUBTREE,
2323                                    expression, attrs,
2324                                    NULL,
2325                                    res, ldb_search_default_callback,
2326                                    NULL);
2327         if (ret != LDB_SUCCESS) {
2328                 talloc_free(expression);
2329                 return ret;
2330         }
2331
2332         /* we need to cope with cross-partition links, so search for
2333            the GUID over all partitions */
2334         options = talloc(search_req, struct ldb_search_options_control);
2335         if (options == NULL) {
2336                 DEBUG(0, (__location__ ": out of memory\n"));
2337                 talloc_free(expression);
2338                 return LDB_ERR_OPERATIONS_ERROR;
2339         }
2340         options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
2341
2342         ret = ldb_request_add_control(search_req, LDB_CONTROL_EXTENDED_DN_OID, true, NULL);
2343         if (ret != LDB_SUCCESS) {
2344                 talloc_free(expression);
2345                 return ret;
2346         }
2347
2348         ret = ldb_request_add_control(search_req,
2349                                       LDB_CONTROL_SEARCH_OPTIONS_OID,
2350                                       true, options);
2351         if (ret != LDB_SUCCESS) {
2352                 talloc_free(expression);
2353                 return ret;
2354         }
2355
2356         ret = ldb_request(ldb, search_req);
2357         if (ret != LDB_SUCCESS) {
2358                 talloc_free(expression);
2359                 return ret;
2360         }
2361
2362         ret = ldb_wait(search_req->handle, LDB_WAIT_ALL);
2363         if (ret != LDB_SUCCESS) {
2364                 talloc_free(expression);
2365                 return ret;
2366         }
2367
2368         /* this really should be exactly 1, but there is a bug in the
2369            partitions module that can return two here with the
2370            search_options control set */
2371         if (res->count < 1) {
2372                 talloc_free(expression);
2373                 return LDB_ERR_NO_SUCH_OBJECT;
2374         }
2375
2376         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2377         talloc_free(expression);
2378
2379         return LDB_SUCCESS;
2380 }
2381
2382 /*
2383   search for attrs on one DN, allowing for deleted objects
2384  */
2385 int dsdb_search_dn_with_deleted(struct ldb_context *ldb,
2386                                 TALLOC_CTX *mem_ctx,
2387                                 struct ldb_result **_res,
2388                                 struct ldb_dn *basedn,
2389                                 const char * const *attrs)
2390 {
2391         int ret;
2392         struct ldb_request *req;
2393         TALLOC_CTX *tmp_ctx;
2394         struct ldb_result *res;
2395
2396         tmp_ctx = talloc_new(mem_ctx);
2397
2398         res = talloc_zero(tmp_ctx, struct ldb_result);
2399         if (!res) {
2400                 talloc_free(tmp_ctx);
2401                 return LDB_ERR_OPERATIONS_ERROR;
2402         }
2403
2404         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2405                                    basedn,
2406                                    LDB_SCOPE_BASE,
2407                                    NULL,
2408                                    attrs,
2409                                    NULL,
2410                                    res,
2411                                    ldb_search_default_callback,
2412                                    NULL);
2413         if (ret != LDB_SUCCESS) {
2414                 talloc_free(tmp_ctx);
2415                 return ret;
2416         }
2417
2418         ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
2419         if (ret != LDB_SUCCESS) {
2420                 talloc_free(tmp_ctx);
2421                 return ret;
2422         }
2423
2424         ret = ldb_request(ldb, req);
2425         if (ret == LDB_SUCCESS) {
2426                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2427         }
2428
2429         *_res = talloc_steal(mem_ctx, res);
2430         talloc_free(tmp_ctx);
2431         return ret;
2432 }
2433
2434
2435 /*
2436   use a DN to find a GUID with a given attribute name
2437  */
2438 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2439                               struct ldb_dn *dn, const char *attribute,
2440                               struct GUID *guid)
2441 {
2442         int ret;
2443         struct ldb_result *res;
2444         const char *attrs[2];
2445         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2446
2447         attrs[0] = attribute;
2448         attrs[1] = NULL;
2449
2450         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2451         if (ret != LDB_SUCCESS) {
2452                 talloc_free(tmp_ctx);
2453                 return ret;
2454         }
2455         if (res->count < 1) {
2456                 talloc_free(tmp_ctx);
2457                 return LDB_ERR_NO_SUCH_OBJECT;
2458         }
2459         *guid = samdb_result_guid(res->msgs[0], attribute);
2460         talloc_free(tmp_ctx);
2461         return LDB_SUCCESS;
2462 }
2463
2464 /*
2465   use a DN to find a GUID
2466  */
2467 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2468                          struct ldb_dn *dn, struct GUID *guid)
2469 {
2470         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2471 }
2472
2473
2474
2475 /*
2476  adds the given GUID to the given ldb_message. This value is added
2477  for the given attr_name (may be either "objectGUID" or "parentGUID").
2478  */
2479 int dsdb_msg_add_guid(struct ldb_message *msg,
2480                 struct GUID *guid,
2481                 const char *attr_name)
2482 {
2483         int ret;
2484         struct ldb_val v;
2485         NTSTATUS status;
2486         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2487
2488         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2489         if (!NT_STATUS_IS_OK(status)) {
2490                 ret = LDB_ERR_OPERATIONS_ERROR;
2491                 goto done;
2492         }
2493
2494         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2495         if (ret != LDB_SUCCESS) {
2496                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2497                                          attr_name));
2498                 goto done;
2499         }
2500
2501         ret = LDB_SUCCESS;
2502
2503 done:
2504         talloc_free(tmp_ctx);
2505         return ret;
2506
2507 }
2508
2509
2510 /*
2511   use a DN to find a SID
2512  */
2513 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2514                         struct ldb_dn *dn, struct dom_sid *sid)
2515 {
2516         int ret;
2517         struct ldb_result *res;
2518         const char *attrs[] = { "objectSID", NULL };
2519         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2520         struct dom_sid *s;
2521
2522         ZERO_STRUCTP(sid);
2523
2524         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2525         if (ret != LDB_SUCCESS) {
2526                 talloc_free(tmp_ctx);
2527                 return ret;
2528         }
2529         if (res->count < 1) {
2530                 talloc_free(tmp_ctx);
2531                 return LDB_ERR_NO_SUCH_OBJECT;
2532         }
2533         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2534         if (s == NULL) {
2535                 talloc_free(tmp_ctx);
2536                 return LDB_ERR_NO_SUCH_OBJECT;
2537         }
2538         *sid = *s;
2539         talloc_free(tmp_ctx);
2540         return LDB_SUCCESS;
2541 }
2542
2543
2544
2545 /*
2546   load a repsFromTo blob list for a given partition GUID
2547   attr must be "repsFrom" or "repsTo"
2548  */
2549 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2550                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2551 {
2552         const char *attrs[] = { attr, NULL };
2553         struct ldb_result *res = NULL;
2554         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2555         int i;
2556         struct ldb_message_element *el;
2557
2558         *r = NULL;
2559         *count = 0;
2560
2561         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2562             res->count < 1) {
2563                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2564                 talloc_free(tmp_ctx);
2565                 return WERR_DS_DRA_INTERNAL_ERROR;
2566         }
2567
2568         el = ldb_msg_find_element(res->msgs[0], attr);
2569         if (el == NULL) {
2570                 /* it's OK to be empty */
2571                 talloc_free(tmp_ctx);
2572                 return WERR_OK;
2573         }
2574
2575         *count = el->num_values;
2576         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2577         if (*r == NULL) {
2578                 talloc_free(tmp_ctx);
2579                 return WERR_DS_DRA_INTERNAL_ERROR;
2580         }
2581
2582         for (i=0; i<(*count); i++) {
2583                 enum ndr_err_code ndr_err;
2584                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2585                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2586                                                &(*r)[i], 
2587                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2588                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2589                         talloc_free(tmp_ctx);
2590                         return WERR_DS_DRA_INTERNAL_ERROR;
2591                 }
2592         }
2593
2594         talloc_free(tmp_ctx);
2595         
2596         return WERR_OK;
2597 }
2598
2599 /*
2600   save the repsFromTo blob list for a given partition GUID
2601   attr must be "repsFrom" or "repsTo"
2602  */
2603 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2604                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2605 {
2606         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2607         struct ldb_message *msg;
2608         struct ldb_message_element *el;
2609         int i;
2610
2611         msg = ldb_msg_new(tmp_ctx);
2612         msg->dn = dn;
2613         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2614                 goto failed;
2615         }
2616
2617         el->values = talloc_array(msg, struct ldb_val, count);
2618         if (!el->values) {
2619                 goto failed;
2620         }
2621
2622         for (i=0; i<count; i++) {
2623                 struct ldb_val v;
2624                 enum ndr_err_code ndr_err;
2625
2626                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2627                                                &r[i], 
2628                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2629                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2630                         goto failed;
2631                 }
2632
2633                 el->num_values++;
2634                 el->values[i] = v;
2635         }
2636
2637         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2638                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2639                 goto failed;
2640         }
2641
2642         talloc_free(tmp_ctx);
2643         
2644         return WERR_OK;
2645
2646 failed:
2647         talloc_free(tmp_ctx);
2648         return WERR_DS_DRA_INTERNAL_ERROR;
2649 }
2650
2651
2652 /*
2653   load the uSNHighest attribute from the @REPLCHANGED object for a
2654   partition
2655  */
2656 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t *uSN)
2657 {
2658         struct ldb_request *req;
2659         int ret;
2660         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2661         struct dsdb_control_current_partition *p_ctrl;
2662         struct ldb_result *res;
2663
2664         res = talloc_zero(tmp_ctx, struct ldb_result);
2665         if (!res) {
2666                 talloc_free(tmp_ctx);
2667                 return LDB_ERR_OPERATIONS_ERROR;
2668         }
2669
2670         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2671                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2672                                    LDB_SCOPE_BASE,
2673                                    NULL, NULL,
2674                                    NULL,
2675                                    res, ldb_search_default_callback,
2676                                    NULL);
2677         if (ret != LDB_SUCCESS) {
2678                 talloc_free(tmp_ctx);
2679                 return ret;
2680         }
2681
2682         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2683         if (p_ctrl == NULL) {
2684                 talloc_free(res);
2685                 return LDB_ERR_OPERATIONS_ERROR;
2686         }
2687         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2688         p_ctrl->dn = dn;
2689         
2690
2691         ret = ldb_request_add_control(req,
2692                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2693                                       false, p_ctrl);
2694         if (ret != LDB_SUCCESS) {
2695                 talloc_free(tmp_ctx);
2696                 return ret;
2697         }
2698         
2699         /* Run the new request */
2700         ret = ldb_request(ldb, req);
2701         
2702         if (ret == LDB_SUCCESS) {
2703                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2704         }
2705
2706         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2707                 /* it hasn't been created yet, which means
2708                    an implicit value of zero */
2709                 *uSN = 0;
2710                 talloc_free(tmp_ctx);
2711                 return LDB_SUCCESS;
2712         }
2713
2714         if (ret != LDB_SUCCESS) {
2715                 talloc_free(tmp_ctx);
2716                 return ret;
2717         }
2718
2719         if (res->count < 1) {
2720                 *uSN = 0;
2721         } else {
2722                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2723         }
2724
2725         talloc_free(tmp_ctx);
2726
2727         return LDB_SUCCESS;     
2728 }
2729
2730 /*
2731   save the uSNHighest attribute in the @REPLCHANGED object for a
2732   partition
2733  */
2734 int dsdb_save_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t uSN)
2735 {
2736         struct ldb_request *req;
2737         struct ldb_message *msg;
2738         struct dsdb_control_current_partition *p_ctrl;
2739         int ret;
2740
2741         msg = ldb_msg_new(ldb);
2742         if (msg == NULL) {
2743                 return LDB_ERR_OPERATIONS_ERROR;
2744         }
2745
2746         msg->dn = ldb_dn_new(msg, ldb, "@REPLCHANGED");
2747         if (msg->dn == NULL) {
2748                 talloc_free(msg);
2749                 return LDB_ERR_OPERATIONS_ERROR;
2750         }
2751         
2752         ret = ldb_msg_add_fmt(msg, "uSNHighest", "%llu", (unsigned long long)uSN);
2753         if (ret != LDB_SUCCESS) {
2754                 talloc_free(msg);
2755                 return ret;
2756         }
2757         msg->elements[0].flags = LDB_FLAG_MOD_REPLACE;
2758         
2759
2760         p_ctrl = talloc(msg, struct dsdb_control_current_partition);
2761         if (p_ctrl == NULL) {
2762                 talloc_free(msg);
2763                 return LDB_ERR_OPERATIONS_ERROR;
2764         }
2765         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2766         p_ctrl->dn = dn;
2767
2768         ret = ldb_build_mod_req(&req, ldb, msg,
2769                                 msg,
2770                                 NULL,
2771                                 NULL, ldb_op_default_callback,
2772                                 NULL);
2773 again:
2774         if (ret != LDB_SUCCESS) {
2775                 talloc_free(msg);
2776                 return ret;
2777         }
2778         
2779         ret = ldb_request_add_control(req,
2780                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2781                                       false, p_ctrl);
2782         if (ret != LDB_SUCCESS) {
2783                 talloc_free(msg);
2784                 return ret;
2785         }
2786         
2787         /* Run the new request */
2788         ret = ldb_request(ldb, req);
2789         
2790         if (ret == LDB_SUCCESS) {
2791                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2792         }
2793         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2794                 ret = ldb_build_add_req(&req, ldb, msg,
2795                                         msg,
2796                                         NULL,
2797                                         NULL, ldb_op_default_callback,
2798                                         NULL);
2799                 goto again;
2800         }
2801         
2802         talloc_free(msg);
2803         
2804         return ret;
2805 }
2806
2807 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2808                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2809 {
2810         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2811 }
2812
2813 /*
2814   see if we are a RODC
2815
2816   TODO: This should take a sam_ctx, and lookup the right object (with
2817   a cache)
2818 */
2819 bool samdb_rodc(struct loadparm_context *lp_ctx)
2820 {
2821         return lp_parm_bool(lp_ctx, NULL, "repl", "RODC", false);
2822 }
2823
2824
2825 /*
2826   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2827
2828   flags are DS_NTDS_OPTION_*
2829 */
2830 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2831 {
2832         TALLOC_CTX *tmp_ctx;
2833         const char *attrs[] = { "options", NULL };
2834         int ret;
2835         struct ldb_result *res;
2836
2837         tmp_ctx = talloc_new(ldb);
2838         if (tmp_ctx == NULL) {
2839                 goto failed;
2840         }
2841
2842         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2843         if (ret) {
2844                 goto failed;
2845         }
2846
2847         if (res->count != 1) {
2848                 goto failed;
2849         }
2850
2851         *options = samdb_result_uint(res->msgs[0], "options", 0);
2852
2853         talloc_free(tmp_ctx);
2854
2855         return LDB_SUCCESS;
2856
2857 failed:
2858         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
2859         talloc_free(tmp_ctx);
2860         return LDB_ERR_NO_SUCH_OBJECT;
2861 }
2862
2863 /*
2864  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2865  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2866  */
2867 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2868 {
2869         char **tokens, *ret;
2870         size_t i;
2871
2872         tokens = str_list_make(mem_ctx, cn, " -_");
2873         if (tokens == NULL)
2874                 return NULL;
2875
2876         /* "tolower()" and "toupper()" should also work properly on 0x00 */
2877         tokens[0][0] = tolower(tokens[0][0]);
2878         for (i = 1; i < str_list_length((const char **)tokens); i++)
2879                 tokens[i][0] = toupper(tokens[i][0]);
2880
2881         ret = talloc_strdup(mem_ctx, tokens[0]);
2882         for (i = 1; i < str_list_length((const char **)tokens); i++)
2883                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2884
2885         talloc_free(tokens);
2886
2887         return ret;
2888 }
2889
2890 /*
2891   return domain functional level
2892   returns DS_DOMAIN_FUNCTION_*
2893  */
2894 int dsdb_functional_level(struct ldb_context *ldb)
2895 {
2896         int *domainFunctionality =
2897                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2898         if (!domainFunctionality) {
2899                 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2900                 return DS_DOMAIN_FUNCTION_2000;
2901         }
2902         return *domainFunctionality;
2903 }
2904
2905 /*
2906   set a GUID in an extended DN structure
2907  */
2908 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
2909 {
2910         struct ldb_val v;
2911         NTSTATUS status;
2912         int ret;
2913
2914         status = GUID_to_ndr_blob(guid, dn, &v);
2915         if (!NT_STATUS_IS_OK(status)) {
2916                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
2917         }
2918
2919         ret = ldb_dn_set_extended_component(dn, component_name, &v);
2920         data_blob_free(&v);
2921         return ret;
2922 }
2923
2924 /*
2925   return a GUID from a extended DN structure
2926  */
2927 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
2928 {
2929         const struct ldb_val *v;
2930
2931         v = ldb_dn_get_extended_component(dn, component_name);
2932         if (v == NULL) {
2933                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2934         }
2935
2936         return GUID_from_ndr_blob(v, guid);
2937 }
2938
2939 /*
2940   return a uint64_t from a extended DN structure
2941  */
2942 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
2943 {
2944         const struct ldb_val *v;
2945         char *s;
2946
2947         v = ldb_dn_get_extended_component(dn, component_name);
2948         if (v == NULL) {
2949                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2950         }
2951         s = talloc_strndup(dn, (const char *)v->data, v->length);
2952         NT_STATUS_HAVE_NO_MEMORY(s);
2953
2954         *val = strtoull(s, NULL, 0);
2955
2956         talloc_free(s);
2957         return NT_STATUS_OK;
2958 }
2959
2960 /*
2961   return a NTTIME from a extended DN structure
2962  */
2963 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
2964 {
2965         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
2966 }
2967
2968 /*
2969   return a uint32_t from a extended DN structure
2970  */
2971 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
2972 {
2973         const struct ldb_val *v;
2974         char *s;
2975
2976         v = ldb_dn_get_extended_component(dn, component_name);
2977         if (v == NULL) {
2978                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2979         }
2980
2981         s = talloc_strndup(dn, (const char *)v->data, v->length);
2982         NT_STATUS_HAVE_NO_MEMORY(s);
2983
2984         *val = strtoul(s, NULL, 0);
2985
2986         talloc_free(s);
2987         return NT_STATUS_OK;
2988 }
2989
2990 /*
2991   return RMD_FLAGS directly from a ldb_dn
2992   returns 0 if not found
2993  */
2994 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
2995 {
2996         const struct ldb_val *v;
2997         char buf[32];
2998         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
2999         if (!v || v->length > sizeof(buf)-1) return 0;
3000         strncpy(buf, (const char *)v->data, v->length);
3001         buf[v->length] = 0;
3002         return strtoul(buf, NULL, 10);
3003 }
3004
3005 /*
3006   return RMD_FLAGS directly from a ldb_val for a DN
3007   returns 0 if RMD_FLAGS is not found
3008  */
3009 uint32_t dsdb_dn_val_rmd_flags(struct ldb_val *val)
3010 {
3011         const char *p;
3012         uint32_t flags;
3013         char *end;
3014
3015         if (val->length < 13) {
3016                 return 0;
3017         }
3018         p = memmem(val->data, val->length-2, "<RMD_FLAGS=", 11);
3019         if (!p) {
3020                 return 0;
3021         }
3022         flags = strtoul(p+11, &end, 10);
3023         if (!end || *end != '>') {
3024                 /* it must end in a > */
3025                 return 0;
3026         }
3027         return flags;
3028 }
3029
3030 /*
3031   return true if a ldb_val containing a DN in storage form is deleted
3032  */
3033 bool dsdb_dn_is_deleted_val(struct ldb_val *val)
3034 {
3035         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3036 }
3037
3038 /*
3039   return true if a ldb_val containing a DN in storage form is
3040   in the upgraded w2k3 linked attribute format
3041  */
3042 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3043 {
3044         return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
3045 }
3046
3047 /*
3048   return a DN for a wellknown GUID
3049  */
3050 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3051                       struct ldb_dn *nc_root, const char *wk_guid,
3052                       struct ldb_dn **wkguid_dn)
3053 {
3054         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3055         const char *attrs[] = { NULL };
3056         int ret;
3057         struct ldb_dn *dn;
3058         struct ldb_result *res;
3059
3060         /* construct the magic WKGUID DN */
3061         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3062                             wk_guid, ldb_dn_get_linearized(nc_root));
3063         if (!wkguid_dn) {
3064                 talloc_free(tmp_ctx);
3065                 return LDB_ERR_OPERATIONS_ERROR;
3066         }
3067
3068         ret = dsdb_search_dn_with_deleted(samdb, tmp_ctx, &res, dn, attrs);
3069         if (ret != LDB_SUCCESS) {
3070                 talloc_free(tmp_ctx);
3071                 return ret;
3072         }
3073
3074         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3075         talloc_free(tmp_ctx);
3076         return LDB_SUCCESS;
3077 }
3078
3079
3080 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3081 {
3082         return ldb_dn_compare(*dn1, *dn2);
3083 }
3084
3085 /*
3086   find a NC root given a DN within the NC
3087  */
3088 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3089                       struct ldb_dn **nc_root)
3090 {
3091         const char *root_attrs[] = { "namingContexts", NULL };
3092         TALLOC_CTX *tmp_ctx;
3093         int ret;
3094         struct ldb_message_element *el;
3095         struct ldb_result *root_res;
3096         int i;
3097         struct ldb_dn **nc_dns;
3098
3099         tmp_ctx = talloc_new(samdb);
3100         if (tmp_ctx == NULL) {
3101                 return LDB_ERR_OPERATIONS_ERROR;
3102         }
3103
3104         ret = ldb_search(samdb, tmp_ctx, &root_res,
3105                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3106         if (ret) {
3107                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3108                 talloc_free(tmp_ctx);
3109                 return ret;
3110        }
3111
3112        el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3113        if (!el) {
3114                DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
3115                         ldb_errstring(samdb)));
3116                talloc_free(tmp_ctx);
3117                return LDB_ERR_NO_SUCH_ATTRIBUTE;
3118        }
3119
3120        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3121        if (!nc_dns) {
3122                talloc_free(tmp_ctx);
3123                return LDB_ERR_OPERATIONS_ERROR;
3124        }
3125
3126        for (i=0; i<el->num_values; i++) {
3127                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3128                if (nc_dns[i] == NULL) {
3129                        talloc_free(tmp_ctx);
3130                        return LDB_ERR_OPERATIONS_ERROR;
3131                }
3132        }
3133
3134        qsort(nc_dns, el->num_values, sizeof(nc_dns[0]), (comparison_fn_t)dsdb_dn_compare_ptrs);
3135
3136        for (i=0; i<el->num_values; i++) {
3137                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3138                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3139                        talloc_free(tmp_ctx);
3140                        return LDB_SUCCESS;
3141                }
3142        }
3143
3144        talloc_free(tmp_ctx);
3145        return LDB_ERR_NO_SUCH_OBJECT;
3146 }
3147
3148
3149 /*
3150   find the deleted objects DN for any object, by looking for the NC
3151   root, then looking up the wellknown GUID
3152  */
3153 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3154                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3155                                 struct ldb_dn **do_dn)
3156 {
3157         struct ldb_dn *nc_root;
3158         int ret;
3159
3160         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3161         if (ret != LDB_SUCCESS) {
3162                 return ret;
3163         }
3164
3165         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3166         talloc_free(nc_root);
3167         return ret;
3168 }
3169
3170 /*
3171   return the tombstoneLifetime, in days
3172  */
3173 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3174 {
3175         struct ldb_dn *dn;
3176         dn = samdb_config_dn(ldb);
3177         if (!dn) {
3178                 return LDB_ERR_NO_SUCH_OBJECT;
3179         }
3180         dn = ldb_dn_copy(ldb, dn);
3181         if (!dn) {
3182                 return LDB_ERR_OPERATIONS_ERROR;
3183         }
3184         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3185          be a wellknown GUID for this */
3186         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT")) {
3187                 talloc_free(dn);
3188                 return LDB_ERR_OPERATIONS_ERROR;
3189         }
3190
3191         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3192         talloc_free(dn);
3193         return LDB_SUCCESS;
3194 }