s4:samdb_set_password - Return the maximum password age when requested (not the minim...
[samba.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
41 /*
42   search the sam for the specified attributes in a specific domain, filter on
43   objectSid being in domain_sid.
44 */
45 int samdb_search_domain(struct ldb_context *sam_ldb,
46                         TALLOC_CTX *mem_ctx, 
47                         struct ldb_dn *basedn,
48                         struct ldb_message ***res,
49                         const char * const *attrs,
50                         const struct dom_sid *domain_sid,
51                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
52 {
53         va_list ap;
54         int i, count;
55
56         va_start(ap, format);
57         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
58                                res, attrs, format, ap);
59         va_end(ap);
60
61         i=0;
62
63         while (i<count) {
64                 struct dom_sid *entry_sid;
65
66                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
67
68                 if ((entry_sid == NULL) ||
69                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
70                         /* Delete that entry from the result set */
71                         (*res)[i] = (*res)[count-1];
72                         count -= 1;
73                         talloc_free(entry_sid);
74                         continue;
75                 }
76                 talloc_free(entry_sid);
77                 i += 1;
78         }
79
80         return count;
81 }
82
83 /*
84   search the sam for a single string attribute in exactly 1 record
85 */
86 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
87                                   TALLOC_CTX *mem_ctx,
88                                   struct ldb_dn *basedn,
89                                   const char *attr_name,
90                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
91 {
92         int count;
93         const char *attrs[2] = { NULL, NULL };
94         struct ldb_message **res = NULL;
95
96         attrs[0] = attr_name;
97
98         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
99         if (count > 1) {                
100                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
101                          attr_name, format, count));
102         }
103         if (count != 1) {
104                 talloc_free(res);
105                 return NULL;
106         }
107
108         return samdb_result_string(res[0], attr_name, NULL);
109 }
110
111 /*
112   search the sam for a single string attribute in exactly 1 record
113 */
114 const char *samdb_search_string(struct ldb_context *sam_ldb,
115                                 TALLOC_CTX *mem_ctx,
116                                 struct ldb_dn *basedn,
117                                 const char *attr_name,
118                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
119 {
120         va_list ap;
121         const char *str;
122
123         va_start(ap, format);
124         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
125         va_end(ap);
126
127         return str;
128 }
129
130 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
131                                TALLOC_CTX *mem_ctx,
132                                struct ldb_dn *basedn,
133                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
134 {
135         va_list ap;
136         struct ldb_dn *ret;
137         struct ldb_message **res = NULL;
138         int count;
139
140         va_start(ap, format);
141         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
142         va_end(ap);
143
144         if (count != 1) return NULL;
145
146         ret = talloc_steal(mem_ctx, res[0]->dn);
147         talloc_free(res);
148
149         return ret;
150 }
151
152 /*
153   search the sam for a dom_sid attribute in exactly 1 record
154 */
155 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
156                                      TALLOC_CTX *mem_ctx,
157                                      struct ldb_dn *basedn,
158                                      const char *attr_name,
159                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
160 {
161         va_list ap;
162         int count;
163         struct ldb_message **res;
164         const char *attrs[2] = { NULL, NULL };
165         struct dom_sid *sid;
166
167         attrs[0] = attr_name;
168
169         va_start(ap, format);
170         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
171         va_end(ap);
172         if (count > 1) {                
173                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
174                          attr_name, format, count));
175         }
176         if (count != 1) {
177                 talloc_free(res);
178                 return NULL;
179         }
180         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
181         talloc_free(res);
182         return sid;     
183 }
184
185 /*
186   return the count of the number of records in the sam matching the query
187 */
188 int samdb_search_count(struct ldb_context *sam_ldb,
189                        TALLOC_CTX *mem_ctx,
190                        struct ldb_dn *basedn,
191                        const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
192 {
193         va_list ap;
194         struct ldb_message **res;
195         const char * const attrs[] = { NULL };
196         int ret;
197
198         va_start(ap, format);
199         ret = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
200         va_end(ap);
201
202         return ret;
203 }
204
205
206 /*
207   search the sam for a single integer attribute in exactly 1 record
208 */
209 uint_t samdb_search_uint(struct ldb_context *sam_ldb,
210                          TALLOC_CTX *mem_ctx,
211                          uint_t default_value,
212                          struct ldb_dn *basedn,
213                          const char *attr_name,
214                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
215 {
216         va_list ap;
217         int count;
218         struct ldb_message **res;
219         const char *attrs[2] = { NULL, NULL };
220
221         attrs[0] = attr_name;
222
223         va_start(ap, format);
224         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
225         va_end(ap);
226
227         if (count != 1) {
228                 return default_value;
229         }
230
231         return samdb_result_uint(res[0], attr_name, default_value);
232 }
233
234 /*
235   search the sam for a single signed 64 bit integer attribute in exactly 1 record
236 */
237 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
238                            TALLOC_CTX *mem_ctx,
239                            int64_t default_value,
240                            struct ldb_dn *basedn,
241                            const char *attr_name,
242                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
243 {
244         va_list ap;
245         int count;
246         struct ldb_message **res;
247         const char *attrs[2] = { NULL, NULL };
248
249         attrs[0] = attr_name;
250
251         va_start(ap, format);
252         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
253         va_end(ap);
254
255         if (count != 1) {
256                 return default_value;
257         }
258
259         return samdb_result_int64(res[0], attr_name, default_value);
260 }
261
262 /*
263   search the sam for multipe records each giving a single string attribute
264   return the number of matches, or -1 on error
265 */
266 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
267                                  TALLOC_CTX *mem_ctx,
268                                  struct ldb_dn *basedn,
269                                  const char ***strs,
270                                  const char *attr_name,
271                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
272 {
273         va_list ap;
274         int count, i;
275         const char *attrs[2] = { NULL, NULL };
276         struct ldb_message **res = NULL;
277
278         attrs[0] = attr_name;
279
280         va_start(ap, format);
281         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
282         va_end(ap);
283
284         if (count <= 0) {
285                 return count;
286         }
287
288         /* make sure its single valued */
289         for (i=0;i<count;i++) {
290                 if (res[i]->num_elements != 1) {
291                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
292                                  attr_name, format));
293                         talloc_free(res);
294                         return -1;
295                 }
296         }
297
298         *strs = talloc_array(mem_ctx, const char *, count+1);
299         if (! *strs) {
300                 talloc_free(res);
301                 return -1;
302         }
303
304         for (i=0;i<count;i++) {
305                 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
306         }
307         (*strs)[count] = NULL;
308
309         return count;
310 }
311
312 /*
313   pull a uint from a result set. 
314 */
315 uint_t samdb_result_uint(const struct ldb_message *msg, const char *attr, uint_t default_value)
316 {
317         return ldb_msg_find_attr_as_uint(msg, attr, default_value);
318 }
319
320 /*
321   pull a (signed) int64 from a result set. 
322 */
323 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
324 {
325         return ldb_msg_find_attr_as_int64(msg, attr, default_value);
326 }
327
328 /*
329   pull a string from a result set. 
330 */
331 const char *samdb_result_string(const struct ldb_message *msg, const char *attr, 
332                                 const char *default_value)
333 {
334         return ldb_msg_find_attr_as_string(msg, attr, default_value);
335 }
336
337 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
338                                const char *attr, struct ldb_dn *default_value)
339 {
340         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
341         if (!ret_dn) {
342                 return default_value;
343         }
344         return ret_dn;
345 }
346
347 /*
348   pull a rid from a objectSid in a result set. 
349 */
350 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
351                                    const char *attr, uint32_t default_value)
352 {
353         struct dom_sid *sid;
354         uint32_t rid;
355
356         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
357         if (sid == NULL) {
358                 return default_value;
359         }
360         rid = sid->sub_auths[sid->num_auths-1];
361         talloc_free(sid);
362         return rid;
363 }
364
365 /*
366   pull a dom_sid structure from a objectSid in a result set. 
367 */
368 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
369                                      const char *attr)
370 {
371         const struct ldb_val *v;
372         struct dom_sid *sid;
373         enum ndr_err_code ndr_err;
374         v = ldb_msg_find_ldb_val(msg, attr);
375         if (v == NULL) {
376                 return NULL;
377         }
378         sid = talloc(mem_ctx, struct dom_sid);
379         if (sid == NULL) {
380                 return NULL;
381         }
382         ndr_err = ndr_pull_struct_blob(v, sid, NULL, sid,
383                                        (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
384         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
385                 talloc_free(sid);
386                 return NULL;
387         }
388         return sid;
389 }
390
391 /*
392   pull a guid structure from a objectGUID in a result set. 
393 */
394 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
395 {
396         const struct ldb_val *v;
397         enum ndr_err_code ndr_err;
398         struct GUID guid;
399         TALLOC_CTX *mem_ctx;
400
401         ZERO_STRUCT(guid);
402
403         v = ldb_msg_find_ldb_val(msg, attr);
404         if (!v) return guid;
405
406         mem_ctx = talloc_named_const(NULL, 0, "samdb_result_guid");
407         if (!mem_ctx) return guid;
408         ndr_err = ndr_pull_struct_blob(v, mem_ctx, NULL, &guid,
409                                        (ndr_pull_flags_fn_t)ndr_pull_GUID);
410         talloc_free(mem_ctx);
411         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
412                 return guid;
413         }
414
415         return guid;
416 }
417
418 /*
419   pull a sid prefix from a objectSid in a result set. 
420   this is used to find the domain sid for a user
421 */
422 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
423                                         const char *attr)
424 {
425         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
426         if (!sid || sid->num_auths < 1) return NULL;
427         sid->num_auths--;
428         return sid;
429 }
430
431 /*
432   pull a NTTIME in a result set. 
433 */
434 NTTIME samdb_result_nttime(struct ldb_message *msg, const char *attr, NTTIME default_value)
435 {
436         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
437 }
438
439 /*
440  * Windows stores 0 for lastLogoff.
441  * But when a MS DC return the lastLogoff (as Logoff Time)
442  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
443  * cause windows 2008 and newer version to fail for SMB requests
444  */
445 NTTIME samdb_result_last_logoff(struct ldb_message *msg)
446 {
447         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
448
449         if (ret == 0)
450                 ret = 0x7FFFFFFFFFFFFFFFULL;
451
452         return ret;
453 }
454
455 /*
456  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
457  * indicate an account doesn't expire.
458  *
459  * When Windows initially creates an account, it sets
460  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
461  * when changing from an account having a specific expiration date to
462  * that account never expiring, it sets accountExpires = 0.
463  *
464  * Consolidate that logic here to allow clearer logic for account expiry in
465  * the rest of the code.
466  */
467 NTTIME samdb_result_account_expires(struct ldb_message *msg)
468 {
469         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
470                                                  0);
471
472         if (ret == 0)
473                 ret = 0x7FFFFFFFFFFFFFFFULL;
474
475         return ret;
476 }
477
478 /*
479   pull a uint64_t from a result set. 
480 */
481 uint64_t samdb_result_uint64(struct ldb_message *msg, const char *attr, uint64_t default_value)
482 {
483         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
484 }
485
486
487 /*
488   construct the allow_password_change field from the PwdLastSet attribute and the 
489   domain password settings
490 */
491 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
492                                           TALLOC_CTX *mem_ctx, 
493                                           struct ldb_dn *domain_dn, 
494                                           struct ldb_message *msg, 
495                                           const char *attr)
496 {
497         uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
498         int64_t minPwdAge;
499
500         if (attr_time == 0) {
501                 return 0;
502         }
503
504         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
505
506         /* yes, this is a -= not a += as minPwdAge is stored as the negative
507            of the number of 100-nano-seconds */
508         attr_time -= minPwdAge;
509
510         return attr_time;
511 }
512
513 /*
514   construct the force_password_change field from the PwdLastSet
515   attribute, the userAccountControl and the domain password settings
516 */
517 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb, 
518                                           TALLOC_CTX *mem_ctx, 
519                                           struct ldb_dn *domain_dn, 
520                                           struct ldb_message *msg)
521 {
522         uint64_t attr_time = samdb_result_uint64(msg, "pwdLastSet", 0);
523         uint32_t userAccountControl = samdb_result_uint64(msg, "userAccountControl", 0);
524         int64_t maxPwdAge;
525
526         /* Machine accounts don't expire, and there is a flag for 'no expiry' */
527         if (!(userAccountControl & UF_NORMAL_ACCOUNT)
528             || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
529                 return 0x7FFFFFFFFFFFFFFFULL;
530         }
531
532         if (attr_time == 0) {
533                 return 0;
534         }
535
536         maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "maxPwdAge", NULL);
537         if (maxPwdAge == 0) {
538                 return 0x7FFFFFFFFFFFFFFFULL;
539         } else {
540                 attr_time -= maxPwdAge;
541         }
542
543         return attr_time;
544 }
545
546 /*
547   pull a samr_Password structutre from a result set. 
548 */
549 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
550 {
551         struct samr_Password *hash = NULL;
552         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
553         if (val && (val->length >= sizeof(hash->hash))) {
554                 hash = talloc(mem_ctx, struct samr_Password);
555                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
556         }
557         return hash;
558 }
559
560 /*
561   pull an array of samr_Password structutres from a result set. 
562 */
563 uint_t samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
564                            const char *attr, struct samr_Password **hashes)
565 {
566         uint_t count = 0;
567         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
568         int i;
569
570         *hashes = NULL;
571         if (!val) {
572                 return 0;
573         }
574         count = val->length / 16;
575         if (count == 0) {
576                 return 0;
577         }
578
579         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
580         if (! *hashes) {
581                 return 0;
582         }
583
584         for (i=0;i<count;i++) {
585                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
586         }
587
588         return count;
589 }
590
591 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg, 
592                                 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd) 
593 {
594         struct samr_Password *lmPwdHash, *ntPwdHash;
595         if (nt_pwd) {
596                 int num_nt;
597                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
598                 if (num_nt == 0) {
599                         *nt_pwd = NULL;
600                 } else if (num_nt > 1) {
601                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
602                 } else {
603                         *nt_pwd = &ntPwdHash[0];
604                 }
605         }
606         if (lm_pwd) {
607                 /* Ensure that if we have turned off LM
608                  * authentication, that we never use the LM hash, even
609                  * if we store it */
610                 if (lp_lanman_auth(lp_ctx)) {
611                         int num_lm;
612                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
613                         if (num_lm == 0) {
614                                 *lm_pwd = NULL;
615                         } else if (num_lm > 1) {
616                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
617                         } else {
618                                 *lm_pwd = &lmPwdHash[0];
619                         }
620                 } else {
621                         *lm_pwd = NULL;
622                 }
623         }
624         return NT_STATUS_OK;
625 }
626
627 /*
628   pull a samr_LogonHours structutre from a result set. 
629 */
630 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
631 {
632         struct samr_LogonHours hours;
633         const int units_per_week = 168;
634         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
635         ZERO_STRUCT(hours);
636         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week);
637         if (!hours.bits) {
638                 return hours;
639         }
640         hours.units_per_week = units_per_week;
641         memset(hours.bits, 0xFF, units_per_week);
642         if (val) {
643                 memcpy(hours.bits, val->data, MIN(val->length, units_per_week));
644         }
645         return hours;
646 }
647
648 /*
649   pull a set of account_flags from a result set. 
650
651   This requires that the attributes: 
652    pwdLastSet
653    userAccountControl
654   be included in 'msg'
655 */
656 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
657                                  struct ldb_message *msg, struct ldb_dn *domain_dn)
658 {
659         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
660         uint32_t acct_flags = ds_uf2acb(userAccountControl);
661         NTTIME must_change_time;
662         NTTIME now;
663
664         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
665                                                               domain_dn, msg);
666
667         /* Test account expire time */
668         unix_to_nt_time(&now, time(NULL));
669         /* check for expired password */
670         if (must_change_time < now) {
671                 acct_flags |= ACB_PW_EXPIRED;
672         }
673         return acct_flags;
674 }
675
676 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
677                                                 struct ldb_message *msg,
678                                                 const char *attr)
679 {
680         struct lsa_BinaryString s;
681         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
682
683         ZERO_STRUCT(s);
684
685         if (!val) {
686                 return s;
687         }
688
689         s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
690         if (!s.array) {
691                 return s;
692         }
693         s.length = s.size = val->length/2;
694         memcpy(s.array, val->data, val->length);
695
696         return s;
697 }
698
699 /* Find an attribute, with a particular value */
700
701 /* The current callers of this function expect a very specific
702  * behaviour: In particular, objectClass subclass equivilance is not
703  * wanted.  This means that we should not lookup the schema for the
704  * comparison function */
705 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb, 
706                                                  const struct ldb_message *msg, 
707                                                  const char *name, const char *value)
708 {
709         int i;
710         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
711
712         if (!el) {
713                 return NULL;
714         }
715
716         for (i=0;i<el->num_values;i++) {
717                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
718                         return el;
719                 }
720         }
721
722         return NULL;
723 }
724
725 int samdb_find_or_add_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
726 {
727         if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
728                 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
729         }
730         return LDB_SUCCESS;
731 }
732
733 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
734 {
735         struct ldb_message_element *el;
736
737         el = ldb_msg_find_element(msg, name);
738         if (el) {
739                 return LDB_SUCCESS;
740         }
741
742         return samdb_msg_add_string(ldb, msg, msg, name, set_value);
743 }
744
745
746
747 /*
748   add a string element to a message
749 */
750 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
751                          const char *attr_name, const char *str)
752 {
753         char *s = talloc_strdup(mem_ctx, str);
754         char *a = talloc_strdup(mem_ctx, attr_name);
755         if (s == NULL || a == NULL) {
756                 return LDB_ERR_OPERATIONS_ERROR;
757         }
758         return ldb_msg_add_string(msg, a, s);
759 }
760
761 /*
762   add a dom_sid element to a message
763 */
764 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
765                          const char *attr_name, struct dom_sid *sid)
766 {
767         struct ldb_val v;
768         enum ndr_err_code ndr_err;
769
770         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
771                                        lp_iconv_convenience(ldb_get_opaque(sam_ldb, "loadparm")),
772                                        sid,
773                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
774         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
775                 return -1;
776         }
777         return ldb_msg_add_value(msg, attr_name, &v, NULL);
778 }
779
780
781 /*
782   add a delete element operation to a message
783 */
784 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
785                          const char *attr_name)
786 {
787         /* we use an empty replace rather than a delete, as it allows for 
788            samdb_replace() to be used everywhere */
789         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
790 }
791
792 /*
793   add a add attribute value to a message
794 */
795 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
796                          const char *attr_name, const char *value)
797 {
798         struct ldb_message_element *el;
799         char *a, *v;
800         int ret;
801         a = talloc_strdup(mem_ctx, attr_name);
802         if (a == NULL)
803                 return -1;
804         v = talloc_strdup(mem_ctx, value);
805         if (v == NULL)
806                 return -1;
807         ret = ldb_msg_add_string(msg, a, v);
808         if (ret != 0)
809                 return ret;
810         el = ldb_msg_find_element(msg, a);
811         if (el == NULL)
812                 return -1;
813         el->flags = LDB_FLAG_MOD_ADD;
814         return 0;
815 }
816
817 /*
818   add a delete attribute value to a message
819 */
820 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
821                          const char *attr_name, const char *value)
822 {
823         struct ldb_message_element *el;
824         char *a, *v;
825         int ret;
826         a = talloc_strdup(mem_ctx, attr_name);
827         if (a == NULL)
828                 return -1;
829         v = talloc_strdup(mem_ctx, value);
830         if (v == NULL)
831                 return -1;
832         ret = ldb_msg_add_string(msg, a, v);
833         if (ret != 0)
834                 return ret;
835         el = ldb_msg_find_element(msg, a);
836         if (el == NULL)
837                 return -1;
838         el->flags = LDB_FLAG_MOD_DELETE;
839         return 0;
840 }
841
842 /*
843   add a int element to a message
844 */
845 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
846                        const char *attr_name, int v)
847 {
848         const char *s = talloc_asprintf(mem_ctx, "%d", v);
849         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
850 }
851
852 /*
853   add a uint_t element to a message
854 */
855 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
856                        const char *attr_name, uint_t v)
857 {
858         const char *s = talloc_asprintf(mem_ctx, "%u", v);
859         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
860 }
861
862 /*
863   add a (signed) int64_t element to a message
864 */
865 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
866                         const char *attr_name, int64_t v)
867 {
868         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
869         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
870 }
871
872 /*
873   add a uint64_t element to a message
874 */
875 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
876                         const char *attr_name, uint64_t v)
877 {
878         const char *s = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)v);
879         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
880 }
881
882 /*
883   add a samr_Password element to a message
884 */
885 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
886                        const char *attr_name, struct samr_Password *hash)
887 {
888         struct ldb_val val;
889         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
890         if (!val.data) {
891                 return -1;
892         }
893         val.length = 16;
894         return ldb_msg_add_value(msg, attr_name, &val, NULL);
895 }
896
897 /*
898   add a samr_Password array to a message
899 */
900 int samdb_msg_add_hashes(TALLOC_CTX *mem_ctx, struct ldb_message *msg,
901                          const char *attr_name, struct samr_Password *hashes, uint_t count)
902 {
903         struct ldb_val val;
904         int i;
905         val.data = talloc_array_size(mem_ctx, 16, count);
906         val.length = count*16;
907         if (!val.data) {
908                 return -1;
909         }
910         for (i=0;i<count;i++) {
911                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
912         }
913         return ldb_msg_add_value(msg, attr_name, &val, NULL);
914 }
915
916 /*
917   add a acct_flags element to a message
918 */
919 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
920                              const char *attr_name, uint32_t v)
921 {
922         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
923 }
924
925 /*
926   add a logon_hours element to a message
927 */
928 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
929                               const char *attr_name, struct samr_LogonHours *hours)
930 {
931         struct ldb_val val;
932         val.length = hours->units_per_week / 8;
933         val.data = hours->bits;
934         return ldb_msg_add_value(msg, attr_name, &val, NULL);
935 }
936
937 /*
938   add a parameters element to a message
939 */
940 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
941                              const char *attr_name, struct lsa_BinaryString *parameters)
942 {
943         struct ldb_val val;
944         val.length = parameters->length * 2;
945         val.data = (uint8_t *)parameters->array;
946         return ldb_msg_add_value(msg, attr_name, &val, NULL);
947 }
948 /*
949   add a general value element to a message
950 */
951 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
952                               const char *attr_name, const struct ldb_val *val)
953 {
954         return ldb_msg_add_value(msg, attr_name, val, NULL);
955 }
956
957 /*
958   sets a general value element to a message
959 */
960 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
961                         const char *attr_name, const struct ldb_val *val)
962 {
963         struct ldb_message_element *el;
964
965         el = ldb_msg_find_element(msg, attr_name);
966         if (el) {
967                 el->num_values = 0;
968         }
969         return ldb_msg_add_value(msg, attr_name, val, NULL);
970 }
971
972 /*
973   set a string element in a message
974 */
975 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
976                          const char *attr_name, const char *str)
977 {
978         struct ldb_message_element *el;
979
980         el = ldb_msg_find_element(msg, attr_name);
981         if (el) {
982                 el->num_values = 0;
983         }
984         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
985 }
986
987 /*
988   replace elements in a record
989 */
990 int samdb_replace(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg)
991 {
992         int i;
993
994         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
995         for (i=0;i<msg->num_elements;i++) {
996                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
997         }
998
999         /* modify the samdb record */
1000         return ldb_modify(sam_ldb, msg);
1001 }
1002
1003 /*
1004   return a default security descriptor
1005 */
1006 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1007 {
1008         struct security_descriptor *sd;
1009
1010         sd = security_descriptor_initialise(mem_ctx);
1011
1012         return sd;
1013 }
1014
1015 struct ldb_dn *samdb_base_dn(struct ldb_context *sam_ctx) 
1016 {
1017         return ldb_get_default_basedn(sam_ctx);
1018 }
1019
1020 struct ldb_dn *samdb_config_dn(struct ldb_context *sam_ctx) 
1021 {
1022         return ldb_get_config_basedn(sam_ctx);
1023 }
1024
1025 struct ldb_dn *samdb_schema_dn(struct ldb_context *sam_ctx) 
1026 {
1027         return ldb_get_schema_basedn(sam_ctx);
1028 }
1029
1030 struct ldb_dn *samdb_root_dn(struct ldb_context *sam_ctx) 
1031 {
1032         return ldb_get_root_basedn(sam_ctx);
1033 }
1034
1035 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1036 {
1037         struct ldb_dn *new_dn;
1038
1039         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1040         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1041                 talloc_free(new_dn);
1042                 return NULL;
1043         }
1044         return new_dn;
1045 }
1046
1047 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1048 {
1049         struct ldb_dn *new_dn;
1050
1051         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1052         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1053                 talloc_free(new_dn);
1054                 return NULL;
1055         }
1056         return new_dn;
1057 }
1058
1059 /*
1060   work out the domain sid for the current open ldb
1061 */
1062 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1063 {
1064         TALLOC_CTX *tmp_ctx;
1065         const struct dom_sid *domain_sid;
1066         const char *attrs[] = {
1067                 "objectSid",
1068                 NULL
1069         };
1070         struct ldb_result *res;
1071         int ret;
1072
1073         /* see if we have a cached copy */
1074         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1075         if (domain_sid) {
1076                 return domain_sid;
1077         }
1078
1079         tmp_ctx = talloc_new(ldb);
1080         if (tmp_ctx == NULL) {
1081                 goto failed;
1082         }
1083
1084         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1085
1086         if (ret != LDB_SUCCESS) {
1087                 goto failed;
1088         }
1089
1090         if (res->count != 1) {
1091                 goto failed;
1092         }
1093
1094         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1095         if (domain_sid == NULL) {
1096                 goto failed;
1097         }
1098
1099         /* cache the domain_sid in the ldb */
1100         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1101                 goto failed;
1102         }
1103
1104         talloc_steal(ldb, domain_sid);
1105         talloc_free(tmp_ctx);
1106
1107         return domain_sid;
1108
1109 failed:
1110         DEBUG(1,("Failed to find domain_sid for open ldb\n"));
1111         talloc_free(tmp_ctx);
1112         return NULL;
1113 }
1114
1115 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1116 {
1117         TALLOC_CTX *tmp_ctx;
1118         struct dom_sid *dom_sid_new;
1119         struct dom_sid *dom_sid_old;
1120
1121         /* see if we have a cached copy */
1122         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1123                                                      "cache.domain_sid"), struct dom_sid);
1124
1125         tmp_ctx = talloc_new(ldb);
1126         if (tmp_ctx == NULL) {
1127                 goto failed;
1128         }
1129
1130         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1131         if (!dom_sid_new) {
1132                 goto failed;
1133         }
1134
1135         /* cache the domain_sid in the ldb */
1136         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1137                 goto failed;
1138         }
1139
1140         talloc_steal(ldb, dom_sid_new);
1141         talloc_free(tmp_ctx);
1142         talloc_free(dom_sid_old);
1143
1144         return true;
1145
1146 failed:
1147         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1148         talloc_free(tmp_ctx);
1149         return false;
1150 }
1151
1152 /* Obtain the short name of the flexible single master operator
1153  * (FSMO), such as the PDC Emulator */
1154 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
1155                              const char *attr)
1156 {
1157         /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1158         struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1159         const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1160         const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1161
1162         if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1163                 /* Ensure this matches the format.  This gives us a
1164                  * bit more confidence that a 'cn' value will be a
1165                  * ascii string */
1166                 return NULL;
1167         }
1168         if (val) {
1169                 return (char *)val->data;
1170         }
1171         return NULL;
1172 }
1173
1174 /*
1175   work out the ntds settings dn for the current open ldb
1176 */
1177 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1178 {
1179         TALLOC_CTX *tmp_ctx;
1180         const char *root_attrs[] = { "dsServiceName", NULL };
1181         int ret;
1182         struct ldb_result *root_res;
1183         struct ldb_dn *settings_dn;
1184
1185         /* see if we have a cached copy */
1186         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.settings_dn");
1187         if (settings_dn) {
1188                 return settings_dn;
1189         }
1190
1191         tmp_ctx = talloc_new(ldb);
1192         if (tmp_ctx == NULL) {
1193                 goto failed;
1194         }
1195
1196         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1197         if (ret) {
1198                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1199                          ldb_errstring(ldb)));
1200                 goto failed;
1201         }
1202
1203         if (root_res->count != 1) {
1204                 goto failed;
1205         }
1206
1207         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1208
1209         /* cache the domain_sid in the ldb */
1210         if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1211                 goto failed;
1212         }
1213
1214         talloc_steal(ldb, settings_dn);
1215         talloc_free(tmp_ctx);
1216
1217         return settings_dn;
1218
1219 failed:
1220         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1221         talloc_free(tmp_ctx);
1222         return NULL;
1223 }
1224
1225 /*
1226   work out the ntds settings invocationId for the current open ldb
1227 */
1228 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1229 {
1230         TALLOC_CTX *tmp_ctx;
1231         const char *attrs[] = { "invocationId", NULL };
1232         int ret;
1233         struct ldb_result *res;
1234         struct GUID *invocation_id;
1235
1236         /* see if we have a cached copy */
1237         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1238         if (invocation_id) {
1239                 return invocation_id;
1240         }
1241
1242         tmp_ctx = talloc_new(ldb);
1243         if (tmp_ctx == NULL) {
1244                 goto failed;
1245         }
1246
1247         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1248         if (ret) {
1249                 goto failed;
1250         }
1251
1252         if (res->count != 1) {
1253                 goto failed;
1254         }
1255
1256         invocation_id = talloc(tmp_ctx, struct GUID);
1257         if (!invocation_id) {
1258                 goto failed;
1259         }
1260
1261         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1262
1263         /* cache the domain_sid in the ldb */
1264         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1265                 goto failed;
1266         }
1267
1268         talloc_steal(ldb, invocation_id);
1269         talloc_free(tmp_ctx);
1270
1271         return invocation_id;
1272
1273 failed:
1274         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1275         talloc_free(tmp_ctx);
1276         return NULL;
1277 }
1278
1279 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1280 {
1281         TALLOC_CTX *tmp_ctx;
1282         struct GUID *invocation_id_new;
1283         struct GUID *invocation_id_old;
1284
1285         /* see if we have a cached copy */
1286         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1287                                                          "cache.invocation_id");
1288
1289         tmp_ctx = talloc_new(ldb);
1290         if (tmp_ctx == NULL) {
1291                 goto failed;
1292         }
1293
1294         invocation_id_new = talloc(tmp_ctx, struct GUID);
1295         if (!invocation_id_new) {
1296                 goto failed;
1297         }
1298
1299         *invocation_id_new = *invocation_id_in;
1300
1301         /* cache the domain_sid in the ldb */
1302         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1303                 goto failed;
1304         }
1305
1306         talloc_steal(ldb, invocation_id_new);
1307         talloc_free(tmp_ctx);
1308         talloc_free(invocation_id_old);
1309
1310         return true;
1311
1312 failed:
1313         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1314         talloc_free(tmp_ctx);
1315         return false;
1316 }
1317
1318 /*
1319   work out the ntds settings objectGUID for the current open ldb
1320 */
1321 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1322 {
1323         TALLOC_CTX *tmp_ctx;
1324         const char *attrs[] = { "objectGUID", NULL };
1325         int ret;
1326         struct ldb_result *res;
1327         struct GUID *ntds_guid;
1328
1329         /* see if we have a cached copy */
1330         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1331         if (ntds_guid) {
1332                 return ntds_guid;
1333         }
1334
1335         tmp_ctx = talloc_new(ldb);
1336         if (tmp_ctx == NULL) {
1337                 goto failed;
1338         }
1339
1340         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1341         if (ret) {
1342                 goto failed;
1343         }
1344
1345         if (res->count != 1) {
1346                 goto failed;
1347         }
1348
1349         ntds_guid = talloc(tmp_ctx, struct GUID);
1350         if (!ntds_guid) {
1351                 goto failed;
1352         }
1353
1354         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1355
1356         /* cache the domain_sid in the ldb */
1357         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1358                 goto failed;
1359         }
1360
1361         talloc_steal(ldb, ntds_guid);
1362         talloc_free(tmp_ctx);
1363
1364         return ntds_guid;
1365
1366 failed:
1367         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1368         talloc_free(tmp_ctx);
1369         return NULL;
1370 }
1371
1372 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1373 {
1374         TALLOC_CTX *tmp_ctx;
1375         struct GUID *ntds_guid_new;
1376         struct GUID *ntds_guid_old;
1377
1378         /* see if we have a cached copy */
1379         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1380
1381         tmp_ctx = talloc_new(ldb);
1382         if (tmp_ctx == NULL) {
1383                 goto failed;
1384         }
1385
1386         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1387         if (!ntds_guid_new) {
1388                 goto failed;
1389         }
1390
1391         *ntds_guid_new = *ntds_guid_in;
1392
1393         /* cache the domain_sid in the ldb */
1394         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1395                 goto failed;
1396         }
1397
1398         talloc_steal(ldb, ntds_guid_new);
1399         talloc_free(tmp_ctx);
1400         talloc_free(ntds_guid_old);
1401
1402         return true;
1403
1404 failed:
1405         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1406         talloc_free(tmp_ctx);
1407         return false;
1408 }
1409
1410 /*
1411   work out the server dn for the current open ldb
1412 */
1413 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1414 {
1415         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1416 }
1417
1418 /*
1419   work out the server dn for the current open ldb
1420 */
1421 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1422 {
1423         struct ldb_dn *server_dn;
1424         struct ldb_dn *server_site_dn;
1425
1426         server_dn = samdb_server_dn(ldb, mem_ctx);
1427         if (!server_dn) return NULL;
1428
1429         server_site_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1430
1431         talloc_free(server_dn);
1432         return server_site_dn;
1433 }
1434
1435 /*
1436   work out if we are the PDC for the domain of the current open ldb
1437 */
1438 bool samdb_is_pdc(struct ldb_context *ldb)
1439 {
1440         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1441         int ret;
1442         struct ldb_result *dom_res;
1443         TALLOC_CTX *tmp_ctx;
1444         bool is_pdc;
1445         struct ldb_dn *pdc;
1446
1447         tmp_ctx = talloc_new(ldb);
1448         if (tmp_ctx == NULL) {
1449                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1450                 return false;
1451         }
1452
1453         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1454         if (ret) {
1455                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1456                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1457                          ldb_errstring(ldb)));
1458                 goto failed;
1459         }
1460         if (dom_res->count != 1) {
1461                 goto failed;
1462         }
1463
1464         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1465
1466         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1467                 is_pdc = true;
1468         } else {
1469                 is_pdc = false;
1470         }
1471
1472         talloc_free(tmp_ctx);
1473
1474         return is_pdc;
1475
1476 failed:
1477         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1478         talloc_free(tmp_ctx);
1479         return false;
1480 }
1481
1482 /*
1483   work out if we are a Global Catalog server for the domain of the current open ldb
1484 */
1485 bool samdb_is_gc(struct ldb_context *ldb)
1486 {
1487         const char *attrs[] = { "options", NULL };
1488         int ret, options;
1489         struct ldb_result *res;
1490         TALLOC_CTX *tmp_ctx;
1491
1492         tmp_ctx = talloc_new(ldb);
1493         if (tmp_ctx == NULL) {
1494                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1495                 return false;
1496         }
1497
1498         /* Query cn=ntds settings,.... */
1499         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1500         if (ret) {
1501                 talloc_free(tmp_ctx);
1502                 return false;
1503         }
1504         if (res->count != 1) {
1505                 talloc_free(tmp_ctx);
1506                 return false;
1507         }
1508
1509         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1510         talloc_free(tmp_ctx);
1511
1512         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1513         if (options & 0x000000001) {
1514                 return true;
1515         }
1516         return false;
1517 }
1518
1519 /* Find a domain object in the parents of a particular DN.  */
1520 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1521                                    struct ldb_dn **parent_dn, const char **errstring)
1522 {
1523         TALLOC_CTX *local_ctx;
1524         struct ldb_dn *sdn = dn;
1525         struct ldb_result *res = NULL;
1526         int ret = 0;
1527         const char *attrs[] = { NULL };
1528
1529         local_ctx = talloc_new(mem_ctx);
1530         if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1531
1532         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1533                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1534                                  "(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain))");
1535                 if (ret == LDB_SUCCESS) {
1536                         if (res->count == 1) {
1537                                 break;
1538                         }
1539                 } else {
1540                         break;
1541                 }
1542         }
1543
1544         if (ret != LDB_SUCCESS) {
1545                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1546                                              ldb_dn_get_linearized(dn),
1547                                              ldb_dn_get_linearized(sdn),
1548                                              ldb_errstring(ldb));
1549                 talloc_free(local_ctx);
1550                 return ret;
1551         }
1552         if (res->count != 1) {
1553                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1554                                              ldb_dn_get_linearized(dn));
1555                 DEBUG(0,(__location__ ": %s\n", *errstring));
1556                 talloc_free(local_ctx);
1557                 return LDB_ERR_CONSTRAINT_VIOLATION;
1558         }
1559
1560         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1561         talloc_free(local_ctx);
1562         return ret;
1563 }
1564
1565
1566 /*
1567   set the user password using plaintext, obeying any user or domain
1568   password restrictions
1569
1570   note that this function doesn't actually store the result in the
1571   database, it just fills in the "mod" structure with ldb modify
1572   elements to setup the correct change when samdb_replace() is
1573   called. This allows the caller to combine the change with other
1574   changes (as is needed by some of the set user info levels)
1575
1576   The caller should probably have a transaction wrapping this
1577 */
1578 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1579                             struct ldb_dn *user_dn,
1580                             struct ldb_dn *domain_dn,
1581                             struct ldb_message *mod,
1582                             const DATA_BLOB *new_password,
1583                             struct samr_Password *param_lmNewHash,
1584                             struct samr_Password *param_ntNewHash,
1585                             bool user_change,
1586                             enum samr_RejectReason *reject_reason,
1587                             struct samr_DomInfo1 **_dominfo)
1588 {
1589         const char * const user_attrs[] = { "userAccountControl",
1590                                             "lmPwdHistory",
1591                                             "ntPwdHistory", 
1592                                             "dBCSPwd", "unicodePwd", 
1593                                             "objectSid", 
1594                                             "pwdLastSet", NULL };
1595         const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1596                                               "pwdHistoryLength",
1597                                               "maxPwdAge", "minPwdAge", NULL };
1598         NTTIME pwdLastSet;
1599         uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1600         int64_t maxPwdAge, minPwdAge;
1601         uint32_t userAccountControl;
1602         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1603                 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1604         struct samr_Password local_lmNewHash, local_ntNewHash;
1605         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1606         struct dom_sid *domain_sid;
1607         struct ldb_message **res;
1608         bool restrictions;
1609         int count;
1610         time_t now = time(NULL);
1611         NTTIME now_nt;
1612         int i;
1613
1614         /* we need to know the time to compute password age */
1615         unix_to_nt_time(&now_nt, now);
1616
1617         /* pull all the user parameters */
1618         count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1619         if (count != 1) {
1620                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1621         }
1622         userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1623         sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1624                                          "lmPwdHistory", &sambaLMPwdHistory);
1625         sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1626                                          "ntPwdHistory", &sambaNTPwdHistory);
1627         lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1628         ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1629         pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1630
1631         /* Copy parameters */
1632         lmNewHash = param_lmNewHash;
1633         ntNewHash = param_ntNewHash;
1634
1635         /* Only non-trust accounts have restrictions (possibly this
1636          * test is the wrong way around, but I like to be restrictive
1637          * if possible */
1638         restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1639                                                |UF_WORKSTATION_TRUST_ACCOUNT
1640                                                |UF_SERVER_TRUST_ACCOUNT)); 
1641
1642         if (domain_dn != NULL) {
1643                 /* pull the domain parameters */
1644                 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1645                                                                 domain_attrs);
1646                 if (count != 1) {
1647                         DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n", 
1648                                   ldb_dn_get_linearized(domain_dn),
1649                                   ldb_dn_get_linearized(user_dn)));
1650                         return NT_STATUS_NO_SUCH_DOMAIN;
1651                 }
1652         } else {
1653                 /* work out the domain sid, and pull the domain from there */
1654                 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1655                                                                 "objectSid");
1656                 if (domain_sid == NULL) {
1657                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1658                 }
1659
1660                 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs, 
1661                                 "(objectSid=%s)",
1662                                 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1663                 if (count != 1) {
1664                         DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n", 
1665                                   dom_sid_string(mem_ctx, domain_sid),
1666                                   ldb_dn_get_linearized(user_dn)));
1667                         return NT_STATUS_NO_SUCH_DOMAIN;
1668                 }
1669         }
1670
1671         minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1672         pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1673         pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1674         maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1675         minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1676
1677         if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1678                 /* see [MS-ADTS] 2.2.15 */
1679                 minPwdLength = 0;
1680         }
1681
1682         if (_dominfo != NULL) {
1683                 struct samr_DomInfo1 *dominfo;
1684                 /* on failure we need to fill in the reject reasons */
1685                 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1686                 if (dominfo == NULL) {
1687                         return NT_STATUS_NO_MEMORY;
1688                 }
1689                 dominfo->min_password_length     = minPwdLength;
1690                 dominfo->password_properties     = pwdProperties;
1691                 dominfo->password_history_length = pwdHistoryLength;
1692                 dominfo->max_password_age        = maxPwdAge;
1693                 dominfo->min_password_age        = minPwdAge;
1694                 *_dominfo = dominfo;
1695         }
1696
1697         if ((restrictions != 0) && (new_password != 0)) {
1698                 char *new_pass;
1699
1700                 /* checks if the "minPwdLength" property is satisfied */
1701                 if ((restrictions != 0)
1702                         && (minPwdLength > utf16_len_n(
1703                                 new_password->data, new_password->length)/2)) {
1704                         if (reject_reason) {
1705                                 *reject_reason = SAMR_REJECT_TOO_SHORT;
1706                         }
1707                         return NT_STATUS_PASSWORD_RESTRICTION;
1708                 }
1709
1710                 /* Create the NT hash */
1711                 mdfour(local_ntNewHash.hash, new_password->data,
1712                                                         new_password->length);
1713
1714                 ntNewHash = &local_ntNewHash;
1715
1716                 /* Only check complexity if we can convert it at all.  Assuming unconvertable passwords are 'strong' */
1717                 if (convert_string_talloc_convenience(mem_ctx,
1718                           lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
1719                           CH_UTF16, CH_UNIX,
1720                           new_password->data, new_password->length,
1721                           (void **)&new_pass, NULL, false)) {
1722
1723                         /* checks the password complexity */
1724                         if ((restrictions != 0)
1725                                 && ((pwdProperties
1726                                         & DOMAIN_PASSWORD_COMPLEX) != 0)
1727                                 && (!check_password_quality(new_pass))) {
1728                                 if (reject_reason) {
1729                                         *reject_reason = SAMR_REJECT_COMPLEXITY;
1730                                 }
1731                                 return NT_STATUS_PASSWORD_RESTRICTION;
1732                         }
1733
1734                         /* compute the new lm hashes (for checking history - case insenitivly!) */
1735                         if (E_deshash(new_pass, local_lmNewHash.hash)) {
1736                                 lmNewHash = &local_lmNewHash;
1737                         }
1738                 }
1739         }
1740
1741         if ((restrictions != 0) && user_change) {
1742                 /* are all password changes disallowed? */
1743                 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
1744                         if (reject_reason) {
1745                                 *reject_reason = SAMR_REJECT_OTHER;
1746                         }
1747                         return NT_STATUS_PASSWORD_RESTRICTION;
1748                 }
1749
1750                 /* can this user change the password? */
1751                 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
1752                         if (reject_reason) {
1753                                 *reject_reason = SAMR_REJECT_OTHER;
1754                         }
1755                         return NT_STATUS_PASSWORD_RESTRICTION;
1756                 }
1757
1758                 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
1759                 if (pwdLastSet - minPwdAge > now_nt) {
1760                         if (reject_reason) {
1761                                 *reject_reason = SAMR_REJECT_OTHER;
1762                         }
1763                         return NT_STATUS_PASSWORD_RESTRICTION;
1764                 }
1765
1766                 /* check the immediately past password */
1767                 if (pwdHistoryLength > 0) {
1768                         if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
1769                                         lmPwdHash->hash, 16) == 0) {
1770                                 if (reject_reason) {
1771                                         *reject_reason = SAMR_REJECT_IN_HISTORY;
1772                                 }
1773                                 return NT_STATUS_PASSWORD_RESTRICTION;
1774                         }
1775                         if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
1776                                         ntPwdHash->hash, 16) == 0) {
1777                                 if (reject_reason) {
1778                                         *reject_reason = SAMR_REJECT_IN_HISTORY;
1779                                 }
1780                                 return NT_STATUS_PASSWORD_RESTRICTION;
1781                         }
1782                 }
1783
1784                 /* check the password history */
1785                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
1786                                                         pwdHistoryLength);
1787                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
1788                                                         pwdHistoryLength);
1789
1790                 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
1791                         if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
1792                                         16) == 0) {
1793                                 if (reject_reason) {
1794                                         *reject_reason = SAMR_REJECT_IN_HISTORY;
1795                                 }
1796                                 return NT_STATUS_PASSWORD_RESTRICTION;
1797                         }
1798                 }
1799                 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
1800                         if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
1801                                          16) == 0) {
1802                                 if (reject_reason) {
1803                                         *reject_reason = SAMR_REJECT_IN_HISTORY;
1804                                 }
1805                                 return NT_STATUS_PASSWORD_RESTRICTION;
1806                         }
1807                 }
1808         }
1809
1810 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
1811
1812         /* the password is acceptable. Start forming the new fields */
1813         if (new_password != NULL) {
1814                 /* if we know the cleartext UTF16 password, then set it.
1815                  * Modules in ldb will set all the appropriate
1816                  * hashes */
1817                 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
1818         } else {
1819                 /* We don't have the cleartext, so delete the old one
1820                  * and set what we have of the hashes */
1821                 CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "clearTextPassword"));
1822
1823                 if (lmNewHash) {
1824                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
1825                 } else {
1826                         CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "dBCSPwd"));
1827                 }
1828
1829                 if (ntNewHash) {
1830                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
1831                 } else {
1832                         CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "unicodePwd"));
1833                 }
1834         }
1835
1836         return NT_STATUS_OK;
1837 }
1838
1839
1840 /*
1841   set the user password using plaintext, obeying any user or domain
1842   password restrictions
1843
1844   This wrapper function takes a SID as input, rather than a user DN,
1845   and actually performs the password change
1846
1847 */
1848 NTSTATUS samdb_set_password_sid(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1849                                 const struct dom_sid *user_sid,
1850                                 const DATA_BLOB *new_pass,
1851                                 struct samr_Password *lmNewHash, 
1852                                 struct samr_Password *ntNewHash,
1853                                 bool user_change,
1854                                 enum samr_RejectReason *reject_reason,
1855                                 struct samr_DomInfo1 **_dominfo) 
1856 {
1857         NTSTATUS nt_status;
1858         struct ldb_dn *user_dn;
1859         struct ldb_message *msg;
1860         int ret;
1861
1862         ret = ldb_transaction_start(ctx);
1863         if (ret) {
1864                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ctx)));
1865                 return NT_STATUS_TRANSACTION_ABORTED;
1866         }
1867
1868         user_dn = samdb_search_dn(ctx, mem_ctx, NULL, 
1869                                   "(&(objectSid=%s)(objectClass=user))", 
1870                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
1871         if (!user_dn) {
1872                 ldb_transaction_cancel(ctx);
1873                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
1874                           dom_sid_string(mem_ctx, user_sid)));
1875                 return NT_STATUS_NO_SUCH_USER;
1876         }
1877
1878         msg = ldb_msg_new(mem_ctx);
1879         if (msg == NULL) {
1880                 ldb_transaction_cancel(ctx);
1881                 return NT_STATUS_NO_MEMORY;
1882         }
1883
1884         msg->dn = ldb_dn_copy(msg, user_dn);
1885         if (!msg->dn) {
1886                 ldb_transaction_cancel(ctx);
1887                 return NT_STATUS_NO_MEMORY;
1888         }
1889
1890         nt_status = samdb_set_password(ctx, mem_ctx,
1891                                        user_dn, NULL,
1892                                        msg, new_pass, 
1893                                        lmNewHash, ntNewHash,
1894                                        user_change, /* This is a password set, not change */
1895                                        reject_reason, _dominfo);
1896         if (!NT_STATUS_IS_OK(nt_status)) {
1897                 ldb_transaction_cancel(ctx);
1898                 return nt_status;
1899         }
1900
1901         /* modify the samdb record */
1902         ret = samdb_replace(ctx, mem_ctx, msg);
1903         if (ret != 0) {
1904                 ldb_transaction_cancel(ctx);
1905                 return NT_STATUS_ACCESS_DENIED;
1906         }
1907
1908         ret = ldb_transaction_commit(ctx);
1909         if (ret != 0) {
1910                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
1911                          ldb_dn_get_linearized(msg->dn),
1912                          ldb_errstring(ctx)));
1913                 return NT_STATUS_TRANSACTION_ABORTED;
1914         }
1915         return NT_STATUS_OK;
1916 }
1917
1918
1919
1920 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
1921                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
1922 {
1923         struct ldb_message *msg;
1924         struct ldb_dn *basedn;
1925         const char *sidstr;
1926         int ret;
1927
1928         sidstr = dom_sid_string(mem_ctx, sid);
1929         NT_STATUS_HAVE_NO_MEMORY(sidstr);
1930
1931         /* We might have to create a ForeignSecurityPrincipal, even if this user
1932          * is in our own domain */
1933
1934         msg = ldb_msg_new(mem_ctx);
1935         if (msg == NULL) {
1936                 return NT_STATUS_NO_MEMORY;
1937         }
1938
1939         /* TODO: Hmmm. This feels wrong. How do I find the base dn to
1940          * put the ForeignSecurityPrincipals? d_state->domain_dn does
1941          * not work, this is wrong for the Builtin domain, there's no
1942          * cn=For...,cn=Builtin,dc={BASEDN}.  -- vl
1943          */
1944
1945         basedn = samdb_search_dn(sam_ctx, mem_ctx, NULL,
1946                                  "(&(objectClass=container)(cn=ForeignSecurityPrincipals))");
1947
1948         if (basedn == NULL) {
1949                 DEBUG(0, ("Failed to find DN for "
1950                           "ForeignSecurityPrincipal container\n"));
1951                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1952         }
1953
1954         /* add core elements to the ldb_message for the alias */
1955         msg->dn = ldb_dn_copy(mem_ctx, basedn);
1956         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr))
1957                 return NT_STATUS_NO_MEMORY;
1958
1959         samdb_msg_add_string(sam_ctx, mem_ctx, msg,
1960                              "objectClass",
1961                              "foreignSecurityPrincipal");
1962
1963         /* create the alias */
1964         ret = ldb_add(sam_ctx, msg);
1965         if (ret != 0) {
1966                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
1967                          "record %s: %s\n", 
1968                          ldb_dn_get_linearized(msg->dn),
1969                          ldb_errstring(sam_ctx)));
1970                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1971         }
1972         *ret_dn = msg->dn;
1973         return NT_STATUS_OK;
1974 }
1975
1976
1977 /*
1978   Find the DN of a domain, assuming it to be a dotted.dns name
1979 */
1980
1981 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
1982 {
1983         int i;
1984         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1985         const char *binary_encoded;
1986         const char **split_realm;
1987         struct ldb_dn *dn;
1988
1989         if (!tmp_ctx) {
1990                 return NULL;
1991         }
1992
1993         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
1994         if (!split_realm) {
1995                 talloc_free(tmp_ctx);
1996                 return NULL;
1997         }
1998         dn = ldb_dn_new(mem_ctx, ldb, NULL);
1999         for (i=0; split_realm[i]; i++) {
2000                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2001                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2002                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2003                                   binary_encoded, ldb_dn_get_linearized(dn)));
2004                         talloc_free(tmp_ctx);
2005                         return NULL;
2006                 }
2007         }
2008         if (!ldb_dn_validate(dn)) {
2009                 DEBUG(2, ("Failed to validated DN %s\n",
2010                           ldb_dn_get_linearized(dn)));
2011                 return NULL;
2012         }
2013         return dn;
2014 }
2015 /*
2016   Find the DN of a domain, be it the netbios or DNS name 
2017 */
2018
2019 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2020                                   const char *domain_name) 
2021 {
2022         const char * const domain_ref_attrs[] = {
2023                 "ncName", NULL
2024         };
2025         const char * const domain_ref2_attrs[] = {
2026                 NULL
2027         };
2028         struct ldb_result *res_domain_ref;
2029         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2030         /* find the domain's DN */
2031         int ret_domain = ldb_search(ldb, mem_ctx,
2032                                             &res_domain_ref, 
2033                                             samdb_partitions_dn(ldb, mem_ctx), 
2034                                             LDB_SCOPE_ONELEVEL, 
2035                                             domain_ref_attrs,
2036                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2037                                             escaped_domain);
2038         if (ret_domain != 0) {
2039                 return NULL;
2040         }
2041
2042         if (res_domain_ref->count == 0) {
2043                 ret_domain = ldb_search(ldb, mem_ctx,
2044                                                 &res_domain_ref, 
2045                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2046                                                 LDB_SCOPE_BASE,
2047                                                 domain_ref2_attrs,
2048                                                 "(objectclass=domain)");
2049                 if (ret_domain != 0) {
2050                         return NULL;
2051                 }
2052
2053                 if (res_domain_ref->count == 1) {
2054                         return res_domain_ref->msgs[0]->dn;
2055                 }
2056                 return NULL;
2057         }
2058
2059         if (res_domain_ref->count > 1) {
2060                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2061                          ret_domain, domain_name));
2062                 return NULL;
2063         }
2064
2065         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2066
2067 }
2068
2069
2070 /*
2071   use a GUID to find a DN
2072  */
2073 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2074                          TALLOC_CTX *mem_ctx,
2075                          const char *guid_str, struct ldb_dn **dn)
2076 {
2077         int ret;
2078         struct ldb_result *res;
2079         const char *attrs[] = { NULL };
2080         struct ldb_request *search_req;
2081         char *expression;
2082         struct ldb_search_options_control *options;
2083
2084         expression = talloc_asprintf(mem_ctx, "objectGUID=%s", guid_str);
2085         if (!expression) {
2086                 DEBUG(0, (__location__ ": out of memory\n"));
2087                 return LDB_ERR_OPERATIONS_ERROR;
2088         }
2089
2090         res = talloc_zero(mem_ctx, struct ldb_result);
2091         if (!res) {
2092                 DEBUG(0, (__location__ ": out of memory\n"));
2093                 return LDB_ERR_OPERATIONS_ERROR;
2094         }
2095
2096         ret = ldb_build_search_req(&search_req, ldb, mem_ctx,
2097                                    ldb_get_default_basedn(ldb),
2098                                    LDB_SCOPE_SUBTREE,
2099                                    expression, attrs,
2100                                    NULL,
2101                                    res, ldb_search_default_callback,
2102                                    NULL);
2103         if (ret != LDB_SUCCESS) {
2104                 return ret;
2105         }
2106
2107         /* we need to cope with cross-partition links, so search for
2108            the GUID over all partitions */
2109         options = talloc(search_req, struct ldb_search_options_control);
2110         if (options == NULL) {
2111                 DEBUG(0, (__location__ ": out of memory\n"));
2112                 return LDB_ERR_OPERATIONS_ERROR;
2113         }
2114         options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
2115
2116         ret = ldb_request_add_control(search_req, LDB_CONTROL_EXTENDED_DN_OID, true, NULL);
2117         if (ret != LDB_SUCCESS) {
2118                 return ret;
2119         }
2120
2121         ret = ldb_request_add_control(search_req,
2122                                       LDB_CONTROL_SEARCH_OPTIONS_OID,
2123                                       true, options);
2124         if (ret != LDB_SUCCESS) {
2125                 return ret;
2126         }
2127
2128         ret = ldb_request(ldb, search_req);
2129         if (ret != LDB_SUCCESS) {
2130                 return ret;
2131         }
2132
2133         ret = ldb_wait(search_req->handle, LDB_WAIT_ALL);
2134         if (ret != LDB_SUCCESS) {
2135                 return ret;
2136         }
2137
2138         /* this really should be exactly 1, but there is a bug in the
2139            partitions module that can return two here with the
2140            search_options control set */
2141         if (res->count < 1) {
2142                 return LDB_ERR_NO_SUCH_OBJECT;
2143         }
2144
2145         *dn = res->msgs[0]->dn;
2146
2147         return LDB_SUCCESS;
2148 }
2149
2150 /*
2151   search for attrs on one DN, allowing for deleted objects
2152  */
2153 int dsdb_search_dn_with_deleted(struct ldb_context *ldb,
2154                                 TALLOC_CTX *mem_ctx,
2155                                 struct ldb_result **_res,
2156                                 struct ldb_dn *basedn,
2157                                 const char * const *attrs)
2158 {
2159         int ret;
2160         struct ldb_request *req;
2161         TALLOC_CTX *tmp_ctx;
2162         struct ldb_result *res;
2163
2164         tmp_ctx = talloc_new(mem_ctx);
2165
2166         res = talloc_zero(tmp_ctx, struct ldb_result);
2167         if (!res) {
2168                 return LDB_ERR_OPERATIONS_ERROR;
2169         }
2170
2171         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2172                                    basedn,
2173                                    LDB_SCOPE_BASE,
2174                                    NULL,
2175                                    attrs,
2176                                    NULL,
2177                                    res,
2178                                    ldb_search_default_callback,
2179                                    NULL);
2180         if (ret != LDB_SUCCESS) {
2181                 talloc_free(tmp_ctx);
2182                 return ret;
2183         }
2184
2185         ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
2186         if (ret != LDB_SUCCESS) {
2187                 return ret;
2188         }
2189
2190         ret = ldb_request(ldb, req);
2191         if (ret == LDB_SUCCESS) {
2192                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2193         }
2194
2195         talloc_free(req);
2196         *_res = talloc_steal(mem_ctx, res);
2197         return ret;
2198 }
2199
2200
2201 /*
2202   use a DN to find a GUID
2203  */
2204 int dsdb_find_guid_by_dn(struct ldb_context *ldb, 
2205                          struct ldb_dn *dn, struct GUID *guid)
2206 {
2207         int ret;
2208         struct ldb_result *res;
2209         const char *attrs[] = { "objectGUID", NULL };
2210         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2211
2212         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2213         if (ret != LDB_SUCCESS) {
2214                 talloc_free(tmp_ctx);
2215                 return ret;
2216         }
2217         if (res->count < 1) {
2218                 talloc_free(tmp_ctx);
2219                 return LDB_ERR_NO_SUCH_OBJECT;
2220         }
2221         *guid = samdb_result_guid(res->msgs[0], "objectGUID");
2222         talloc_free(tmp_ctx);
2223         return LDB_SUCCESS;
2224 }
2225
2226 /*
2227   use a DN to find a SID
2228  */
2229 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2230                         struct ldb_dn *dn, struct dom_sid *sid)
2231 {
2232         int ret;
2233         struct ldb_result *res;
2234         const char *attrs[] = { "objectSID", NULL };
2235         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2236         struct dom_sid *s;
2237
2238         ZERO_STRUCTP(sid);
2239
2240         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2241         if (ret != LDB_SUCCESS) {
2242                 talloc_free(tmp_ctx);
2243                 return ret;
2244         }
2245         if (res->count < 1) {
2246                 talloc_free(tmp_ctx);
2247                 return LDB_ERR_NO_SUCH_OBJECT;
2248         }
2249         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2250         if (s == NULL) {
2251                 talloc_free(tmp_ctx);
2252                 return LDB_ERR_NO_SUCH_OBJECT;
2253         }
2254         *sid = *s;
2255         talloc_free(tmp_ctx);
2256         return LDB_SUCCESS;
2257 }
2258
2259
2260
2261 /*
2262   load a repsFromTo blob list for a given partition GUID
2263   attr must be "repsFrom" or "repsTo"
2264  */
2265 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2266                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2267 {
2268         const char *attrs[] = { attr, NULL };
2269         struct ldb_result *res = NULL;
2270         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2271         int i;
2272         struct ldb_message_element *el;
2273
2274         *r = NULL;
2275         *count = 0;
2276
2277         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2278             res->count < 1) {
2279                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2280                 talloc_free(tmp_ctx);
2281                 return WERR_DS_DRA_INTERNAL_ERROR;
2282         }
2283
2284         el = ldb_msg_find_element(res->msgs[0], attr);
2285         if (el == NULL) {
2286                 /* it's OK to be empty */
2287                 talloc_free(tmp_ctx);
2288                 return WERR_OK;
2289         }
2290
2291         *count = el->num_values;
2292         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2293         if (*r == NULL) {
2294                 talloc_free(tmp_ctx);
2295                 return WERR_DS_DRA_INTERNAL_ERROR;
2296         }
2297
2298         for (i=0; i<(*count); i++) {
2299                 enum ndr_err_code ndr_err;
2300                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2301                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2302                                                &(*r)[i], 
2303                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2304                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2305                         talloc_free(tmp_ctx);
2306                         return WERR_DS_DRA_INTERNAL_ERROR;
2307                 }
2308         }
2309
2310         talloc_free(tmp_ctx);
2311         
2312         return WERR_OK;
2313 }
2314
2315 /*
2316   save the repsFromTo blob list for a given partition GUID
2317   attr must be "repsFrom" or "repsTo"
2318  */
2319 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2320                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2321 {
2322         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2323         struct ldb_message *msg;
2324         struct ldb_message_element *el;
2325         int i;
2326
2327         msg = ldb_msg_new(tmp_ctx);
2328         msg->dn = dn;
2329         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2330                 goto failed;
2331         }
2332
2333         el->values = talloc_array(msg, struct ldb_val, count);
2334         if (!el->values) {
2335                 goto failed;
2336         }
2337
2338         for (i=0; i<count; i++) {
2339                 struct ldb_val v;
2340                 enum ndr_err_code ndr_err;
2341
2342                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2343                                                &r[i], 
2344                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2345                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2346                         goto failed;
2347                 }
2348
2349                 el->num_values++;
2350                 el->values[i] = v;
2351         }
2352
2353         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2354                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2355                 goto failed;
2356         }
2357
2358         talloc_free(tmp_ctx);
2359         
2360         return WERR_OK;
2361
2362 failed:
2363         talloc_free(tmp_ctx);
2364         return WERR_DS_DRA_INTERNAL_ERROR;
2365 }
2366
2367
2368 /*
2369   load the uSNHighest attribute from the @REPLCHANGED object for a
2370   partition
2371  */
2372 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t *uSN)
2373 {
2374         struct ldb_request *req;
2375         int ret;
2376         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2377         struct dsdb_control_current_partition *p_ctrl;
2378         struct ldb_result *res;
2379
2380         res = talloc_zero(tmp_ctx, struct ldb_result);
2381         if (!res) {
2382                 talloc_free(tmp_ctx);
2383                 return LDB_ERR_OPERATIONS_ERROR;
2384         }
2385
2386         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2387                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2388                                    LDB_SCOPE_BASE,
2389                                    NULL, NULL,
2390                                    NULL,
2391                                    res, ldb_search_default_callback,
2392                                    NULL);
2393         if (ret != LDB_SUCCESS) {
2394                 talloc_free(tmp_ctx);
2395                 return ret;
2396         }
2397
2398         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2399         if (p_ctrl == NULL) {
2400                 talloc_free(res);
2401                 return LDB_ERR_OPERATIONS_ERROR;
2402         }
2403         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2404         p_ctrl->dn = dn;
2405         
2406
2407         ret = ldb_request_add_control(req,
2408                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2409                                       false, p_ctrl);
2410         if (ret != LDB_SUCCESS) {
2411                 talloc_free(tmp_ctx);
2412                 return ret;
2413         }
2414         
2415         /* Run the new request */
2416         ret = ldb_request(ldb, req);
2417         
2418         if (ret == LDB_SUCCESS) {
2419                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2420         }
2421
2422         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2423                 /* it hasn't been created yet, which means
2424                    an implicit value of zero */
2425                 *uSN = 0;
2426                 talloc_free(tmp_ctx);
2427                 return LDB_SUCCESS;
2428         }
2429
2430         if (ret != LDB_SUCCESS) {
2431                 talloc_free(tmp_ctx);
2432                 return ret;
2433         }
2434
2435         if (res->count < 1) {
2436                 *uSN = 0;
2437         } else {
2438                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2439         }
2440
2441         talloc_free(tmp_ctx);
2442
2443         return LDB_SUCCESS;     
2444 }
2445
2446 /*
2447   save the uSNHighest attribute in the @REPLCHANGED object for a
2448   partition
2449  */
2450 int dsdb_save_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t uSN)
2451 {
2452         struct ldb_request *req;
2453         struct ldb_message *msg;
2454         struct dsdb_control_current_partition *p_ctrl;
2455         int ret;
2456
2457         msg = ldb_msg_new(ldb);
2458         if (msg == NULL) {
2459                 return LDB_ERR_OPERATIONS_ERROR;
2460         }
2461
2462         msg->dn = ldb_dn_new(msg, ldb, "@REPLCHANGED");
2463         if (msg->dn == NULL) {
2464                 talloc_free(msg);
2465                 return LDB_ERR_OPERATIONS_ERROR;
2466         }
2467         
2468         ret = ldb_msg_add_fmt(msg, "uSNHighest", "%llu", (unsigned long long)uSN);
2469         if (ret != LDB_SUCCESS) {
2470                 talloc_free(msg);
2471                 return ret;
2472         }
2473         msg->elements[0].flags = LDB_FLAG_MOD_REPLACE;
2474         
2475
2476         p_ctrl = talloc(msg, struct dsdb_control_current_partition);
2477         if (p_ctrl == NULL) {
2478                 talloc_free(msg);
2479                 return LDB_ERR_OPERATIONS_ERROR;
2480         }
2481         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2482         p_ctrl->dn = dn;
2483
2484         ret = ldb_build_mod_req(&req, ldb, msg,
2485                                 msg,
2486                                 NULL,
2487                                 NULL, ldb_op_default_callback,
2488                                 NULL);
2489 again:
2490         if (ret != LDB_SUCCESS) {
2491                 talloc_free(msg);
2492                 return ret;
2493         }
2494         
2495         ret = ldb_request_add_control(req,
2496                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2497                                       false, p_ctrl);
2498         if (ret != LDB_SUCCESS) {
2499                 talloc_free(msg);
2500                 return ret;
2501         }
2502         
2503         /* Run the new request */
2504         ret = ldb_request(ldb, req);
2505         
2506         if (ret == LDB_SUCCESS) {
2507                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2508         }
2509         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2510                 ret = ldb_build_add_req(&req, ldb, msg,
2511                                         msg,
2512                                         NULL,
2513                                         NULL, ldb_op_default_callback,
2514                                         NULL);
2515                 goto again;
2516         }
2517         
2518         talloc_free(msg);
2519         
2520         return ret;
2521 }
2522
2523 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2524                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2525 {
2526         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2527 }