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