s4:dsdb/common: if we don't have the ip of the client return the server site as clien...
[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         /*
1613          * if we don't have a client ip e.g. ncalrpc
1614          * the server site is the client site
1615          */
1616         if (ip_address == NULL) {
1617                 return samdb_server_site_name(ldb, mem_ctx);
1618         }
1619
1620         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1621         if (sites_container_dn == NULL) {
1622                 return NULL;
1623         }
1624
1625         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1626         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1627                 talloc_free(sites_container_dn);
1628                 talloc_free(subnets_dn);
1629                 return NULL;
1630         }
1631
1632         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1633                          attrs, NULL);
1634         if (ret != LDB_SUCCESS) {
1635                 talloc_free(sites_container_dn);
1636                 talloc_free(subnets_dn);
1637                 return NULL;
1638         }
1639
1640         for (i = 0; i < res->count; i++) {
1641                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1642                                                             NULL);
1643
1644                 allow_list[0] = l_subnet_name;
1645
1646                 if (allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1647                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1648                                                            res->msgs[i],
1649                                                            "siteObject");
1650                         if (sites_dn == NULL) {
1651                                 /* No reference, maybe another subnet matches */
1652                                 continue;
1653                         }
1654
1655                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1656                         val = ldb_dn_get_rdn_val(sites_dn);
1657                         site_name = talloc_strdup(mem_ctx,
1658                                                   (const char *) val->data);
1659
1660                         talloc_free(sites_dn);
1661
1662                         break;
1663                 }
1664         }
1665
1666         if (site_name == NULL) {
1667                 /* This is the Windows Server fallback rule: when no subnet
1668                  * exists and we have only one site available then use it (it
1669                  * is for sure the same as our server site). If more sites do
1670                  * exist then we don't know which one to use and set the site
1671                  * name to "". */
1672                 cnt = samdb_search_count(ldb, sites_container_dn,
1673                                          "(objectClass=site)");
1674                 if (cnt == 1) {
1675                         site_name = samdb_server_site_name(ldb, mem_ctx);
1676                 } else {
1677                         site_name = talloc_strdup(mem_ctx, "");
1678                 }
1679                 l_subnet_name = NULL;
1680         }
1681
1682         if (subnet_name != NULL) {
1683                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1684         }
1685
1686         talloc_free(sites_container_dn);
1687         talloc_free(subnets_dn);
1688         talloc_free(res);
1689
1690         return site_name;
1691 }
1692
1693 /*
1694   work out if we are the PDC for the domain of the current open ldb
1695 */
1696 bool samdb_is_pdc(struct ldb_context *ldb)
1697 {
1698         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1699         int ret;
1700         struct ldb_result *dom_res;
1701         TALLOC_CTX *tmp_ctx;
1702         bool is_pdc;
1703         struct ldb_dn *pdc;
1704
1705         tmp_ctx = talloc_new(ldb);
1706         if (tmp_ctx == NULL) {
1707                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1708                 return false;
1709         }
1710
1711         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1712         if (ret) {
1713                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1714                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1715                          ldb_errstring(ldb)));
1716                 goto failed;
1717         }
1718         if (dom_res->count != 1) {
1719                 goto failed;
1720         }
1721
1722         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1723
1724         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1725                 is_pdc = true;
1726         } else {
1727                 is_pdc = false;
1728         }
1729
1730         talloc_free(tmp_ctx);
1731
1732         return is_pdc;
1733
1734 failed:
1735         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1736         talloc_free(tmp_ctx);
1737         return false;
1738 }
1739
1740 /*
1741   work out if we are a Global Catalog server for the domain of the current open ldb
1742 */
1743 bool samdb_is_gc(struct ldb_context *ldb)
1744 {
1745         const char *attrs[] = { "options", NULL };
1746         int ret, options;
1747         struct ldb_result *res;
1748         TALLOC_CTX *tmp_ctx;
1749
1750         tmp_ctx = talloc_new(ldb);
1751         if (tmp_ctx == NULL) {
1752                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1753                 return false;
1754         }
1755
1756         /* Query cn=ntds settings,.... */
1757         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1758         if (ret) {
1759                 talloc_free(tmp_ctx);
1760                 return false;
1761         }
1762         if (res->count != 1) {
1763                 talloc_free(tmp_ctx);
1764                 return false;
1765         }
1766
1767         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1768         talloc_free(tmp_ctx);
1769
1770         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1771         if (options & 0x000000001) {
1772                 return true;
1773         }
1774         return false;
1775 }
1776
1777 /* Find a domain object in the parents of a particular DN.  */
1778 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1779                                    struct ldb_dn **parent_dn, const char **errstring)
1780 {
1781         TALLOC_CTX *local_ctx;
1782         struct ldb_dn *sdn = dn;
1783         struct ldb_result *res = NULL;
1784         int ret = 0;
1785         const char *attrs[] = { NULL };
1786
1787         local_ctx = talloc_new(mem_ctx);
1788         if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1789
1790         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1791                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1792                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1793                 if (ret == LDB_SUCCESS) {
1794                         if (res->count == 1) {
1795                                 break;
1796                         }
1797                 } else {
1798                         break;
1799                 }
1800         }
1801
1802         if (ret != LDB_SUCCESS) {
1803                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1804                                              ldb_dn_get_linearized(dn),
1805                                              ldb_dn_get_linearized(sdn),
1806                                              ldb_errstring(ldb));
1807                 talloc_free(local_ctx);
1808                 return ret;
1809         }
1810         if (res->count != 1) {
1811                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1812                                              ldb_dn_get_linearized(dn));
1813                 DEBUG(0,(__location__ ": %s\n", *errstring));
1814                 talloc_free(local_ctx);
1815                 return LDB_ERR_CONSTRAINT_VIOLATION;
1816         }
1817
1818         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1819         talloc_free(local_ctx);
1820         return ret;
1821 }
1822
1823
1824 /*
1825  * Performs checks on a user password (plaintext UNIX format - attribute
1826  * "password"). The remaining parameters have to be extracted from the domain
1827  * object in the AD.
1828  *
1829  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1830  */
1831 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1832                                                 const uint32_t pwdProperties,
1833                                                 const uint32_t minPwdLength)
1834 {
1835         /* checks if the "minPwdLength" property is satisfied */
1836         if (minPwdLength > password->length)
1837                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1838
1839         /* checks the password complexity */
1840         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1841                         && (password->data != NULL)
1842                         && (!check_password_quality((const char *) password->data)))
1843                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1844
1845         return SAMR_VALIDATION_STATUS_SUCCESS;
1846 }
1847
1848 /*
1849  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1850  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1851  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1852  * gives some more informations if the changed failed.
1853  *
1854  * The caller should have a LDB transaction wrapping this.
1855  *
1856  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1857  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1858  *   NT_STATUS_PASSWORD_RESTRICTION
1859  */
1860 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1861                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1862                             struct ldb_message *mod,
1863                             const DATA_BLOB *new_password,
1864                             struct samr_Password *param_lmNewHash,
1865                             struct samr_Password *param_ntNewHash,
1866                             bool user_change,
1867                             enum samPwdChangeReason *reject_reason,
1868                             struct samr_DomInfo1 **_dominfo)
1869 {
1870         const char * const user_attrs[] = { "userAccountControl",
1871                                             "lmPwdHistory",
1872                                             "ntPwdHistory", 
1873                                             "dBCSPwd", "unicodePwd", 
1874                                             "objectSid", 
1875                                             "pwdLastSet", NULL };
1876         const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1877                                               "pwdHistoryLength",
1878                                               "maxPwdAge", "minPwdAge", NULL };
1879         NTTIME pwdLastSet;
1880         uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1881         int64_t maxPwdAge, minPwdAge;
1882         uint32_t userAccountControl;
1883         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1884                 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1885         struct samr_Password local_lmNewHash, local_ntNewHash;
1886         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1887         struct dom_sid *domain_sid;
1888         struct ldb_message **res;
1889         bool restrictions;
1890         int count;
1891         time_t now = time(NULL);
1892         NTTIME now_nt;
1893         unsigned int i;
1894
1895         /* we need to know the time to compute password age */
1896         unix_to_nt_time(&now_nt, now);
1897
1898         /* pull all the user parameters */
1899         count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1900         if (count != 1) {
1901                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1902         }
1903         userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1904         sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1905                                          "lmPwdHistory", &sambaLMPwdHistory);
1906         sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1907                                          "ntPwdHistory", &sambaNTPwdHistory);
1908         lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1909         ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1910         pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1911
1912         /* Copy parameters */
1913         lmNewHash = param_lmNewHash;
1914         ntNewHash = param_ntNewHash;
1915
1916         /* Only non-trust accounts have restrictions (possibly this
1917          * test is the wrong way around, but I like to be restrictive
1918          * if possible */
1919         restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1920                                                |UF_WORKSTATION_TRUST_ACCOUNT
1921                                                |UF_SERVER_TRUST_ACCOUNT)); 
1922
1923         if (domain_dn != NULL) {
1924                 /* pull the domain parameters */
1925                 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1926                                                                 domain_attrs);
1927                 if (count != 1) {
1928                         DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n", 
1929                                   ldb_dn_get_linearized(domain_dn),
1930                                   ldb_dn_get_linearized(user_dn)));
1931                         return NT_STATUS_NO_SUCH_DOMAIN;
1932                 }
1933         } else {
1934                 /* work out the domain sid, and pull the domain from there */
1935                 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1936                                                                 "objectSid");
1937                 if (domain_sid == NULL) {
1938                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1939                 }
1940
1941                 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs, 
1942                                 "(objectSid=%s)",
1943                                 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1944                 if (count != 1) {
1945                         DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n", 
1946                                   dom_sid_string(mem_ctx, domain_sid),
1947                                   ldb_dn_get_linearized(user_dn)));
1948                         return NT_STATUS_NO_SUCH_DOMAIN;
1949                 }
1950         }
1951
1952         minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1953         pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1954         pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1955         maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1956         minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1957
1958         if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1959                 /* see [MS-ADTS] 2.2.15 */
1960                 minPwdLength = 0;
1961         }
1962
1963         if (_dominfo != NULL) {
1964                 struct samr_DomInfo1 *dominfo;
1965                 /* on failure we need to fill in the reject reasons */
1966                 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1967                 if (dominfo == NULL) {
1968                         return NT_STATUS_NO_MEMORY;
1969                 }
1970                 dominfo->min_password_length     = minPwdLength;
1971                 dominfo->password_properties     = pwdProperties;
1972                 dominfo->password_history_length = pwdHistoryLength;
1973                 dominfo->max_password_age        = maxPwdAge;
1974                 dominfo->min_password_age        = minPwdAge;
1975                 *_dominfo = dominfo;
1976         }
1977
1978         if ((restrictions != 0) && (new_password != 0)) {
1979                 char *new_pass;
1980
1981                 /* checks if the "minPwdLength" property is satisfied */
1982                 if ((restrictions != 0)
1983                         && (minPwdLength > utf16_len_n(
1984                                 new_password->data, new_password->length)/2)) {
1985                         if (reject_reason) {
1986                                 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1987                         }
1988                         return NT_STATUS_PASSWORD_RESTRICTION;
1989                 }
1990
1991                 /* Create the NT hash */
1992                 mdfour(local_ntNewHash.hash, new_password->data,
1993                                                         new_password->length);
1994
1995                 ntNewHash = &local_ntNewHash;
1996
1997                 /* Only check complexity if we can convert it at all.  Assuming unconvertable passwords are 'strong' */
1998                 if (convert_string_talloc_convenience(mem_ctx,
1999                           lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
2000                           CH_UTF16, CH_UNIX,
2001                           new_password->data, new_password->length,
2002                           (void **)&new_pass, NULL, false)) {
2003
2004                         /* checks the password complexity */
2005                         if ((restrictions != 0)
2006                                 && ((pwdProperties
2007                                         & DOMAIN_PASSWORD_COMPLEX) != 0)
2008                                 && (!check_password_quality(new_pass))) {
2009                                 if (reject_reason) {
2010                                         *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
2011                                 }
2012                                 return NT_STATUS_PASSWORD_RESTRICTION;
2013                         }
2014
2015                         /* compute the new lm hashes (for checking history - case insenitivly!) */
2016                         if (E_deshash(new_pass, local_lmNewHash.hash)) {
2017                                 lmNewHash = &local_lmNewHash;
2018                         }
2019                 }
2020         }
2021
2022         if ((restrictions != 0) && user_change) {
2023                 /* are all password changes disallowed? */
2024                 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
2025                         if (reject_reason) {
2026                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2027                         }
2028                         return NT_STATUS_PASSWORD_RESTRICTION;
2029                 }
2030
2031                 /* can this user change the password? */
2032                 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
2033                         if (reject_reason) {
2034                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2035                         }
2036                         return NT_STATUS_PASSWORD_RESTRICTION;
2037                 }
2038
2039                 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
2040                 if (pwdLastSet - minPwdAge > now_nt) {
2041                         if (reject_reason) {
2042                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2043                         }
2044                         return NT_STATUS_PASSWORD_RESTRICTION;
2045                 }
2046
2047                 /* check the immediately past password */
2048                 if (pwdHistoryLength > 0) {
2049                         if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
2050                                         lmPwdHash->hash, 16) == 0) {
2051                                 if (reject_reason) {
2052                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2053                                 }
2054                                 return NT_STATUS_PASSWORD_RESTRICTION;
2055                         }
2056                         if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
2057                                         ntPwdHash->hash, 16) == 0) {
2058                                 if (reject_reason) {
2059                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2060                                 }
2061                                 return NT_STATUS_PASSWORD_RESTRICTION;
2062                         }
2063                 }
2064
2065                 /* check the password history */
2066                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
2067                                                         pwdHistoryLength);
2068                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
2069                                                         pwdHistoryLength);
2070
2071                 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
2072                         if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
2073                                         16) == 0) {
2074                                 if (reject_reason) {
2075                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2076                                 }
2077                                 return NT_STATUS_PASSWORD_RESTRICTION;
2078                         }
2079                 }
2080                 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
2081                         if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
2082                                          16) == 0) {
2083                                 if (reject_reason) {
2084                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
2085                                 }
2086                                 return NT_STATUS_PASSWORD_RESTRICTION;
2087                         }
2088                 }
2089         }
2090
2091 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
2092
2093         /* the password is acceptable. Start forming the new fields */
2094         if (new_password != NULL) {
2095                 /* if we know the cleartext UTF16 password, then set it.
2096                  * Modules in ldb will set all the appropriate
2097                  * hashes */
2098                 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
2099         } else {
2100                 /* we don't have the cleartext, so set what we have of the
2101                  * hashes */
2102
2103                 if (lmNewHash) {
2104                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
2105                 }
2106
2107                 if (ntNewHash) {
2108                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
2109                 }
2110         }
2111
2112         if (reject_reason) {
2113                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2114         }
2115         return NT_STATUS_OK;
2116 }
2117
2118
2119 /*
2120  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2121  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2122  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
2123  * gives some more informations if the changed failed.
2124  *
2125  * This wrapper function for "samdb_set_password" takes a SID as input rather
2126  * than a user DN.
2127  *
2128  * This call encapsulates a new LDB transaction for changing the password;
2129  * therefore the user hasn't to start a new one.
2130  *
2131  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2132  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2133  *   NT_STATUS_PASSWORD_RESTRICTION
2134  */
2135 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2136                                 const struct dom_sid *user_sid,
2137                                 const DATA_BLOB *new_password,
2138                                 struct samr_Password *lmNewHash, 
2139                                 struct samr_Password *ntNewHash,
2140                                 bool user_change,
2141                                 enum samPwdChangeReason *reject_reason,
2142                                 struct samr_DomInfo1 **_dominfo) 
2143 {
2144         NTSTATUS nt_status;
2145         struct ldb_dn *user_dn;
2146         struct ldb_message *msg;
2147         int ret;
2148
2149         ret = ldb_transaction_start(ldb);
2150         if (ret != LDB_SUCCESS) {
2151                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2152                 return NT_STATUS_TRANSACTION_ABORTED;
2153         }
2154
2155         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2156                                   "(&(objectSid=%s)(objectClass=user))", 
2157                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2158         if (!user_dn) {
2159                 ldb_transaction_cancel(ldb);
2160                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2161                           dom_sid_string(mem_ctx, user_sid)));
2162                 return NT_STATUS_NO_SUCH_USER;
2163         }
2164
2165         msg = ldb_msg_new(mem_ctx);
2166         if (msg == NULL) {
2167                 ldb_transaction_cancel(ldb);
2168                 talloc_free(user_dn);
2169                 return NT_STATUS_NO_MEMORY;
2170         }
2171
2172         msg->dn = ldb_dn_copy(msg, user_dn);
2173         if (!msg->dn) {
2174                 ldb_transaction_cancel(ldb);
2175                 talloc_free(user_dn);
2176                 talloc_free(msg);
2177                 return NT_STATUS_NO_MEMORY;
2178         }
2179
2180         nt_status = samdb_set_password(ldb, mem_ctx,
2181                                        user_dn, NULL,
2182                                        msg, new_password,
2183                                        lmNewHash, ntNewHash,
2184                                        user_change,
2185                                        reject_reason, _dominfo);
2186         if (!NT_STATUS_IS_OK(nt_status)) {
2187                 ldb_transaction_cancel(ldb);
2188                 talloc_free(user_dn);
2189                 talloc_free(msg);
2190                 return nt_status;
2191         }
2192
2193         /* modify the samdb record */
2194         ret = dsdb_replace(ldb, msg, 0);
2195         if (ret != LDB_SUCCESS) {
2196                 ldb_transaction_cancel(ldb);
2197                 talloc_free(user_dn);
2198                 talloc_free(msg);
2199                 return NT_STATUS_ACCESS_DENIED;
2200         }
2201
2202         talloc_free(msg);
2203
2204         ret = ldb_transaction_commit(ldb);
2205         if (ret != LDB_SUCCESS) {
2206                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2207                          ldb_dn_get_linearized(user_dn),
2208                          ldb_errstring(ldb)));
2209                 talloc_free(user_dn);
2210                 return NT_STATUS_TRANSACTION_ABORTED;
2211         }
2212
2213         talloc_free(user_dn);
2214         return NT_STATUS_OK;
2215 }
2216
2217
2218 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2219                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2220 {
2221         struct ldb_message *msg;
2222         struct ldb_dn *basedn;
2223         char *sidstr;
2224         int ret;
2225
2226         sidstr = dom_sid_string(mem_ctx, sid);
2227         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2228
2229         /* We might have to create a ForeignSecurityPrincipal, even if this user
2230          * is in our own domain */
2231
2232         msg = ldb_msg_new(sidstr);
2233         if (msg == NULL) {
2234                 talloc_free(sidstr);
2235                 return NT_STATUS_NO_MEMORY;
2236         }
2237
2238         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2239                                 ldb_get_default_basedn(sam_ctx),
2240                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2241                                 &basedn);
2242         if (ret != LDB_SUCCESS) {
2243                 DEBUG(0, ("Failed to find DN for "
2244                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2245                 talloc_free(sidstr);
2246                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2247         }
2248
2249         /* add core elements to the ldb_message for the alias */
2250         msg->dn = basedn;
2251         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2252                 talloc_free(sidstr);
2253                 return NT_STATUS_NO_MEMORY;
2254         }
2255
2256         samdb_msg_add_string(sam_ctx, msg, msg,
2257                              "objectClass",
2258                              "foreignSecurityPrincipal");
2259
2260         /* create the alias */
2261         ret = ldb_add(sam_ctx, msg);
2262         if (ret != LDB_SUCCESS) {
2263                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2264                          "record %s: %s\n", 
2265                          ldb_dn_get_linearized(msg->dn),
2266                          ldb_errstring(sam_ctx)));
2267                 talloc_free(sidstr);
2268                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2269         }
2270
2271         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2272         talloc_free(sidstr);
2273
2274         return NT_STATUS_OK;
2275 }
2276
2277
2278 /*
2279   Find the DN of a domain, assuming it to be a dotted.dns name
2280 */
2281
2282 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2283 {
2284         unsigned int i;
2285         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2286         const char *binary_encoded;
2287         const char **split_realm;
2288         struct ldb_dn *dn;
2289
2290         if (!tmp_ctx) {
2291                 return NULL;
2292         }
2293
2294         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2295         if (!split_realm) {
2296                 talloc_free(tmp_ctx);
2297                 return NULL;
2298         }
2299         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2300         for (i=0; split_realm[i]; i++) {
2301                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2302                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2303                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2304                                   binary_encoded, ldb_dn_get_linearized(dn)));
2305                         talloc_free(tmp_ctx);
2306                         return NULL;
2307                 }
2308         }
2309         if (!ldb_dn_validate(dn)) {
2310                 DEBUG(2, ("Failed to validated DN %s\n",
2311                           ldb_dn_get_linearized(dn)));
2312                 talloc_free(tmp_ctx);
2313                 return NULL;
2314         }
2315         talloc_free(tmp_ctx);
2316         return dn;
2317 }
2318
2319 /*
2320   Find the DN of a domain, be it the netbios or DNS name 
2321 */
2322 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2323                                   const char *domain_name) 
2324 {
2325         const char * const domain_ref_attrs[] = {
2326                 "ncName", NULL
2327         };
2328         const char * const domain_ref2_attrs[] = {
2329                 NULL
2330         };
2331         struct ldb_result *res_domain_ref;
2332         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2333         /* find the domain's DN */
2334         int ret_domain = ldb_search(ldb, mem_ctx,
2335                                             &res_domain_ref, 
2336                                             samdb_partitions_dn(ldb, mem_ctx), 
2337                                             LDB_SCOPE_ONELEVEL, 
2338                                             domain_ref_attrs,
2339                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2340                                             escaped_domain);
2341         if (ret_domain != 0) {
2342                 return NULL;
2343         }
2344
2345         if (res_domain_ref->count == 0) {
2346                 ret_domain = ldb_search(ldb, mem_ctx,
2347                                                 &res_domain_ref, 
2348                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2349                                                 LDB_SCOPE_BASE,
2350                                                 domain_ref2_attrs,
2351                                                 "(objectclass=domain)");
2352                 if (ret_domain != 0) {
2353                         return NULL;
2354                 }
2355
2356                 if (res_domain_ref->count == 1) {
2357                         return res_domain_ref->msgs[0]->dn;
2358                 }
2359                 return NULL;
2360         }
2361
2362         if (res_domain_ref->count > 1) {
2363                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2364                          ret_domain, domain_name));
2365                 return NULL;
2366         }
2367
2368         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2369
2370 }
2371
2372
2373 /*
2374   use a GUID to find a DN
2375  */
2376 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2377                          TALLOC_CTX *mem_ctx,
2378                          const struct GUID *guid, struct ldb_dn **dn)
2379 {
2380         int ret;
2381         struct ldb_result *res;
2382         const char *attrs[] = { NULL };
2383         char *guid_str = GUID_string(mem_ctx, guid);
2384
2385         if (!guid_str) {
2386                 return LDB_ERR_OPERATIONS_ERROR;
2387         }
2388
2389         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2390                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2391                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2392                           DSDB_SEARCH_ONE_ONLY,
2393                           "objectGUID=%s", guid_str);
2394         talloc_free(guid_str);
2395         if (ret != LDB_SUCCESS) {
2396                 return ret;
2397         }
2398
2399         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2400         talloc_free(res);
2401
2402         return LDB_SUCCESS;
2403 }
2404
2405 /*
2406   use a DN to find a GUID with a given attribute name
2407  */
2408 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2409                               struct ldb_dn *dn, const char *attribute,
2410                               struct GUID *guid)
2411 {
2412         int ret;
2413         struct ldb_result *res;
2414         const char *attrs[2];
2415         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2416
2417         attrs[0] = attribute;
2418         attrs[1] = NULL;
2419
2420         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2421         if (ret != LDB_SUCCESS) {
2422                 talloc_free(tmp_ctx);
2423                 return ret;
2424         }
2425         if (res->count < 1) {
2426                 talloc_free(tmp_ctx);
2427                 return LDB_ERR_NO_SUCH_OBJECT;
2428         }
2429         *guid = samdb_result_guid(res->msgs[0], attribute);
2430         talloc_free(tmp_ctx);
2431         return LDB_SUCCESS;
2432 }
2433
2434 /*
2435   use a DN to find a GUID
2436  */
2437 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2438                          struct ldb_dn *dn, struct GUID *guid)
2439 {
2440         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2441 }
2442
2443
2444
2445 /*
2446  adds the given GUID to the given ldb_message. This value is added
2447  for the given attr_name (may be either "objectGUID" or "parentGUID").
2448  */
2449 int dsdb_msg_add_guid(struct ldb_message *msg,
2450                 struct GUID *guid,
2451                 const char *attr_name)
2452 {
2453         int ret;
2454         struct ldb_val v;
2455         NTSTATUS status;
2456         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2457
2458         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2459         if (!NT_STATUS_IS_OK(status)) {
2460                 ret = LDB_ERR_OPERATIONS_ERROR;
2461                 goto done;
2462         }
2463
2464         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2465         if (ret != LDB_SUCCESS) {
2466                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2467                                          attr_name));
2468                 goto done;
2469         }
2470
2471         ret = LDB_SUCCESS;
2472
2473 done:
2474         talloc_free(tmp_ctx);
2475         return ret;
2476
2477 }
2478
2479
2480 /*
2481   use a DN to find a SID
2482  */
2483 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2484                         struct ldb_dn *dn, struct dom_sid *sid)
2485 {
2486         int ret;
2487         struct ldb_result *res;
2488         const char *attrs[] = { "objectSID", NULL };
2489         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2490         struct dom_sid *s;
2491
2492         ZERO_STRUCTP(sid);
2493
2494         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2495         if (ret != LDB_SUCCESS) {
2496                 talloc_free(tmp_ctx);
2497                 return ret;
2498         }
2499         if (res->count < 1) {
2500                 talloc_free(tmp_ctx);
2501                 return LDB_ERR_NO_SUCH_OBJECT;
2502         }
2503         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2504         if (s == NULL) {
2505                 talloc_free(tmp_ctx);
2506                 return LDB_ERR_NO_SUCH_OBJECT;
2507         }
2508         *sid = *s;
2509         talloc_free(tmp_ctx);
2510         return LDB_SUCCESS;
2511 }
2512
2513
2514 /*
2515   load a repsFromTo blob list for a given partition GUID
2516   attr must be "repsFrom" or "repsTo"
2517  */
2518 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2519                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2520 {
2521         const char *attrs[] = { attr, NULL };
2522         struct ldb_result *res = NULL;
2523         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2524         unsigned int i;
2525         struct ldb_message_element *el;
2526
2527         *r = NULL;
2528         *count = 0;
2529
2530         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2531             res->count < 1) {
2532                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2533                 talloc_free(tmp_ctx);
2534                 return WERR_DS_DRA_INTERNAL_ERROR;
2535         }
2536
2537         el = ldb_msg_find_element(res->msgs[0], attr);
2538         if (el == NULL) {
2539                 /* it's OK to be empty */
2540                 talloc_free(tmp_ctx);
2541                 return WERR_OK;
2542         }
2543
2544         *count = el->num_values;
2545         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2546         if (*r == NULL) {
2547                 talloc_free(tmp_ctx);
2548                 return WERR_DS_DRA_INTERNAL_ERROR;
2549         }
2550
2551         for (i=0; i<(*count); i++) {
2552                 enum ndr_err_code ndr_err;
2553                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2554                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2555                                                &(*r)[i], 
2556                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2557                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2558                         talloc_free(tmp_ctx);
2559                         return WERR_DS_DRA_INTERNAL_ERROR;
2560                 }
2561         }
2562
2563         talloc_free(tmp_ctx);
2564         
2565         return WERR_OK;
2566 }
2567
2568 /*
2569   save the repsFromTo blob list for a given partition GUID
2570   attr must be "repsFrom" or "repsTo"
2571  */
2572 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2573                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2574 {
2575         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2576         struct ldb_message *msg;
2577         struct ldb_message_element *el;
2578         unsigned int i;
2579
2580         msg = ldb_msg_new(tmp_ctx);
2581         msg->dn = dn;
2582         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2583                 goto failed;
2584         }
2585
2586         el->values = talloc_array(msg, struct ldb_val, count);
2587         if (!el->values) {
2588                 goto failed;
2589         }
2590
2591         for (i=0; i<count; i++) {
2592                 struct ldb_val v;
2593                 enum ndr_err_code ndr_err;
2594
2595                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2596                                                &r[i], 
2597                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2598                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2599                         goto failed;
2600                 }
2601
2602                 el->num_values++;
2603                 el->values[i] = v;
2604         }
2605
2606         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2607                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2608                 goto failed;
2609         }
2610
2611         talloc_free(tmp_ctx);
2612         
2613         return WERR_OK;
2614
2615 failed:
2616         talloc_free(tmp_ctx);
2617         return WERR_DS_DRA_INTERNAL_ERROR;
2618 }
2619
2620
2621 /*
2622   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2623   object for a partition
2624  */
2625 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2626                                 uint64_t *uSN, uint64_t *urgent_uSN)
2627 {
2628         struct ldb_request *req;
2629         int ret;
2630         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2631         struct dsdb_control_current_partition *p_ctrl;
2632         struct ldb_result *res;
2633
2634         res = talloc_zero(tmp_ctx, struct ldb_result);
2635         if (!res) {
2636                 talloc_free(tmp_ctx);
2637                 return LDB_ERR_OPERATIONS_ERROR;
2638         }
2639
2640         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2641                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2642                                    LDB_SCOPE_BASE,
2643                                    NULL, NULL,
2644                                    NULL,
2645                                    res, ldb_search_default_callback,
2646                                    NULL);
2647         if (ret != LDB_SUCCESS) {
2648                 talloc_free(tmp_ctx);
2649                 return ret;
2650         }
2651
2652         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2653         if (p_ctrl == NULL) {
2654                 talloc_free(res);
2655                 return LDB_ERR_OPERATIONS_ERROR;
2656         }
2657         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2658         p_ctrl->dn = dn;
2659         
2660
2661         ret = ldb_request_add_control(req,
2662                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2663                                       false, p_ctrl);
2664         if (ret != LDB_SUCCESS) {
2665                 talloc_free(tmp_ctx);
2666                 return ret;
2667         }
2668         
2669         /* Run the new request */
2670         ret = ldb_request(ldb, req);
2671         
2672         if (ret == LDB_SUCCESS) {
2673                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2674         }
2675
2676         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2677                 /* it hasn't been created yet, which means
2678                    an implicit value of zero */
2679                 *uSN = 0;
2680                 talloc_free(tmp_ctx);
2681                 return LDB_SUCCESS;
2682         }
2683
2684         if (ret != LDB_SUCCESS) {
2685                 talloc_free(tmp_ctx);
2686                 return ret;
2687         }
2688
2689         if (res->count < 1) {
2690                 *uSN = 0;
2691                 if (urgent_uSN) {
2692                         *urgent_uSN = 0;
2693                 }
2694         } else {
2695                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2696                 if (urgent_uSN) {
2697                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2698                 }
2699         }
2700
2701         talloc_free(tmp_ctx);
2702
2703         return LDB_SUCCESS;     
2704 }
2705
2706 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2707                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2708 {
2709         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2710 }
2711
2712 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2713                                     const struct drsuapi_DsReplicaCursor *c2)
2714 {
2715         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2716 }
2717
2718
2719 /*
2720   see if a computer identified by its invocationId is a RODC
2721 */
2722 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *invocationId, bool *is_rodc)
2723 {
2724         /* 1) find the DN for this servers NTDSDSA object
2725            2) search for the msDS-isRODC attribute
2726            3) if not present then not a RODC
2727            4) if present and TRUE then is a RODC
2728         */
2729         struct ldb_dn *config_dn;
2730         const char *attrs[] = { "msDS-isRODC", NULL };
2731         int ret;
2732         struct ldb_result *res;
2733         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2734
2735         config_dn = ldb_get_config_basedn(sam_ctx);
2736         if (!config_dn) {
2737                 talloc_free(tmp_ctx);
2738                 return LDB_ERR_OPERATIONS_ERROR;
2739         }
2740
2741         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2742                           DSDB_SEARCH_ONE_ONLY, "invocationID=%s", GUID_string(tmp_ctx, invocationId));
2743         if (ret != LDB_SUCCESS) {
2744                 talloc_free(tmp_ctx);
2745                 return ret;
2746         }
2747
2748         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2749         *is_rodc = (ret == 1);
2750
2751         talloc_free(tmp_ctx);
2752         return LDB_SUCCESS;
2753 }
2754
2755
2756 /*
2757   see if we are a RODC
2758 */
2759 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2760 {
2761         const struct GUID *invocationId;
2762         invocationId = samdb_ntds_invocation_id(sam_ctx);
2763         if (!invocationId) {
2764                 return LDB_ERR_OPERATIONS_ERROR;
2765         }
2766         return samdb_is_rodc(sam_ctx, invocationId, am_rodc);
2767 }
2768
2769
2770
2771 /*
2772   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2773
2774   flags are DS_NTDS_OPTION_*
2775 */
2776 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2777 {
2778         TALLOC_CTX *tmp_ctx;
2779         const char *attrs[] = { "options", NULL };
2780         int ret;
2781         struct ldb_result *res;
2782
2783         tmp_ctx = talloc_new(ldb);
2784         if (tmp_ctx == NULL) {
2785                 goto failed;
2786         }
2787
2788         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2789         if (ret) {
2790                 goto failed;
2791         }
2792
2793         if (res->count != 1) {
2794                 goto failed;
2795         }
2796
2797         *options = samdb_result_uint(res->msgs[0], "options", 0);
2798
2799         talloc_free(tmp_ctx);
2800
2801         return LDB_SUCCESS;
2802
2803 failed:
2804         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
2805         talloc_free(tmp_ctx);
2806         return LDB_ERR_NO_SUCH_OBJECT;
2807 }
2808
2809 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
2810 {
2811         const char *attrs[] = { "objectCategory", NULL };
2812         int ret;
2813         struct ldb_result *res;
2814
2815         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2816         if (ret) {
2817                 goto failed;
2818         }
2819
2820         if (res->count != 1) {
2821                 goto failed;
2822         }
2823
2824         return samdb_result_string(res->msgs[0], "objectCategory", NULL);
2825
2826 failed:
2827         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
2828         return NULL;
2829 }
2830
2831 /*
2832  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2833  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2834  */
2835 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2836 {
2837         char **tokens, *ret;
2838         size_t i;
2839
2840         tokens = str_list_make(mem_ctx, cn, " -_");
2841         if (tokens == NULL)
2842                 return NULL;
2843
2844         /* "tolower()" and "toupper()" should also work properly on 0x00 */
2845         tokens[0][0] = tolower(tokens[0][0]);
2846         for (i = 1; i < str_list_length((const char **)tokens); i++)
2847                 tokens[i][0] = toupper(tokens[i][0]);
2848
2849         ret = talloc_strdup(mem_ctx, tokens[0]);
2850         for (i = 1; i < str_list_length((const char **)tokens); i++)
2851                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2852
2853         talloc_free(tokens);
2854
2855         return ret;
2856 }
2857
2858 /*
2859   return domain functional level
2860   returns DS_DOMAIN_FUNCTION_*
2861  */
2862 int dsdb_functional_level(struct ldb_context *ldb)
2863 {
2864         int *domainFunctionality =
2865                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2866         if (!domainFunctionality) {
2867                 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2868                 return DS_DOMAIN_FUNCTION_2000;
2869         }
2870         return *domainFunctionality;
2871 }
2872
2873 /*
2874   set a GUID in an extended DN structure
2875  */
2876 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
2877 {
2878         struct ldb_val v;
2879         NTSTATUS status;
2880         int ret;
2881
2882         status = GUID_to_ndr_blob(guid, dn, &v);
2883         if (!NT_STATUS_IS_OK(status)) {
2884                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
2885         }
2886
2887         ret = ldb_dn_set_extended_component(dn, component_name, &v);
2888         data_blob_free(&v);
2889         return ret;
2890 }
2891
2892 /*
2893   return a GUID from a extended DN structure
2894  */
2895 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
2896 {
2897         const struct ldb_val *v;
2898
2899         v = ldb_dn_get_extended_component(dn, component_name);
2900         if (v == NULL) {
2901                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2902         }
2903
2904         return GUID_from_ndr_blob(v, guid);
2905 }
2906
2907 /*
2908   return a uint64_t from a extended DN structure
2909  */
2910 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
2911 {
2912         const struct ldb_val *v;
2913         char *s;
2914
2915         v = ldb_dn_get_extended_component(dn, component_name);
2916         if (v == NULL) {
2917                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2918         }
2919         s = talloc_strndup(dn, (const char *)v->data, v->length);
2920         NT_STATUS_HAVE_NO_MEMORY(s);
2921
2922         *val = strtoull(s, NULL, 0);
2923
2924         talloc_free(s);
2925         return NT_STATUS_OK;
2926 }
2927
2928 /*
2929   return a NTTIME from a extended DN structure
2930  */
2931 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
2932 {
2933         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
2934 }
2935
2936 /*
2937   return a uint32_t from a extended DN structure
2938  */
2939 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
2940 {
2941         const struct ldb_val *v;
2942         char *s;
2943
2944         v = ldb_dn_get_extended_component(dn, component_name);
2945         if (v == NULL) {
2946                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2947         }
2948
2949         s = talloc_strndup(dn, (const char *)v->data, v->length);
2950         NT_STATUS_HAVE_NO_MEMORY(s);
2951
2952         *val = strtoul(s, NULL, 0);
2953
2954         talloc_free(s);
2955         return NT_STATUS_OK;
2956 }
2957
2958 /*
2959   return a dom_sid from a extended DN structure
2960  */
2961 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
2962 {
2963         const struct ldb_val *sid_blob;
2964         struct TALLOC_CTX *tmp_ctx;
2965         enum ndr_err_code ndr_err;
2966
2967         sid_blob = ldb_dn_get_extended_component(dn, "SID");
2968         if (!sid_blob) {
2969                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2970         }
2971
2972         tmp_ctx = talloc_new(NULL);
2973
2974         ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, NULL, sid,
2975                                            (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
2976         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2977                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
2978                 talloc_free(tmp_ctx);
2979                 return status;
2980         }
2981
2982         talloc_free(tmp_ctx);
2983         return NT_STATUS_OK;
2984 }
2985
2986
2987 /*
2988   return RMD_FLAGS directly from a ldb_dn
2989   returns 0 if not found
2990  */
2991 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
2992 {
2993         const struct ldb_val *v;
2994         char buf[32];
2995         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
2996         if (!v || v->length > sizeof(buf)-1) return 0;
2997         strncpy(buf, (const char *)v->data, v->length);
2998         buf[v->length] = 0;
2999         return strtoul(buf, NULL, 10);
3000 }
3001
3002 /*
3003   return RMD_FLAGS directly from a ldb_val for a DN
3004   returns 0 if RMD_FLAGS is not found
3005  */
3006 uint32_t dsdb_dn_val_rmd_flags(struct ldb_val *val)
3007 {
3008         const char *p;
3009         uint32_t flags;
3010         char *end;
3011
3012         if (val->length < 13) {
3013                 return 0;
3014         }
3015         p = memmem(val->data, val->length-2, "<RMD_FLAGS=", 11);
3016         if (!p) {
3017                 return 0;
3018         }
3019         flags = strtoul(p+11, &end, 10);
3020         if (!end || *end != '>') {
3021                 /* it must end in a > */
3022                 return 0;
3023         }
3024         return flags;
3025 }
3026
3027 /*
3028   return true if a ldb_val containing a DN in storage form is deleted
3029  */
3030 bool dsdb_dn_is_deleted_val(struct ldb_val *val)
3031 {
3032         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3033 }
3034
3035 /*
3036   return true if a ldb_val containing a DN in storage form is
3037   in the upgraded w2k3 linked attribute format
3038  */
3039 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3040 {
3041         return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
3042 }
3043
3044 /*
3045   return a DN for a wellknown GUID
3046  */
3047 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3048                       struct ldb_dn *nc_root, const char *wk_guid,
3049                       struct ldb_dn **wkguid_dn)
3050 {
3051         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3052         const char *attrs[] = { NULL };
3053         int ret;
3054         struct ldb_dn *dn;
3055         struct ldb_result *res;
3056
3057         /* construct the magic WKGUID DN */
3058         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3059                             wk_guid, ldb_dn_get_linearized(nc_root));
3060         if (!wkguid_dn) {
3061                 talloc_free(tmp_ctx);
3062                 return LDB_ERR_OPERATIONS_ERROR;
3063         }
3064
3065         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
3066         if (ret != LDB_SUCCESS) {
3067                 talloc_free(tmp_ctx);
3068                 return ret;
3069         }
3070
3071         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3072         talloc_free(tmp_ctx);
3073         return LDB_SUCCESS;
3074 }
3075
3076
3077 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3078 {
3079         return ldb_dn_compare(*dn1, *dn2);
3080 }
3081
3082 /*
3083   find a NC root given a DN within the NC
3084  */
3085 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3086                       struct ldb_dn **nc_root)
3087 {
3088         const char *root_attrs[] = { "namingContexts", NULL };
3089         TALLOC_CTX *tmp_ctx;
3090         int ret;
3091         struct ldb_message_element *el;
3092         struct ldb_result *root_res;
3093         int i;
3094         struct ldb_dn **nc_dns;
3095
3096         tmp_ctx = talloc_new(samdb);
3097         if (tmp_ctx == NULL) {
3098                 return LDB_ERR_OPERATIONS_ERROR;
3099         }
3100
3101         ret = ldb_search(samdb, tmp_ctx, &root_res,
3102                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3103         if (ret) {
3104                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3105                 talloc_free(tmp_ctx);
3106                 return ret;
3107        }
3108
3109        el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3110        if (!el) {
3111                DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
3112                         ldb_errstring(samdb)));
3113                talloc_free(tmp_ctx);
3114                return LDB_ERR_NO_SUCH_ATTRIBUTE;
3115        }
3116
3117        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3118        if (!nc_dns) {
3119                talloc_free(tmp_ctx);
3120                return LDB_ERR_OPERATIONS_ERROR;
3121        }
3122
3123        for (i=0; i<el->num_values; i++) {
3124                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3125                if (nc_dns[i] == NULL) {
3126                        talloc_free(tmp_ctx);
3127                        return LDB_ERR_OPERATIONS_ERROR;
3128                }
3129        }
3130
3131        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3132
3133        for (i=0; i<el->num_values; i++) {
3134                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3135                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3136                        talloc_free(tmp_ctx);
3137                        return LDB_SUCCESS;
3138                }
3139        }
3140
3141        talloc_free(tmp_ctx);
3142        return LDB_ERR_NO_SUCH_OBJECT;
3143 }
3144
3145
3146 /*
3147   find the deleted objects DN for any object, by looking for the NC
3148   root, then looking up the wellknown GUID
3149  */
3150 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3151                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3152                                 struct ldb_dn **do_dn)
3153 {
3154         struct ldb_dn *nc_root;
3155         int ret;
3156
3157         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3158         if (ret != LDB_SUCCESS) {
3159                 return ret;
3160         }
3161
3162         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3163         talloc_free(nc_root);
3164         return ret;
3165 }
3166
3167 /*
3168   return the tombstoneLifetime, in days
3169  */
3170 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3171 {
3172         struct ldb_dn *dn;
3173         dn = ldb_get_config_basedn(ldb);
3174         if (!dn) {
3175                 return LDB_ERR_NO_SUCH_OBJECT;
3176         }
3177         dn = ldb_dn_copy(ldb, dn);
3178         if (!dn) {
3179                 return LDB_ERR_OPERATIONS_ERROR;
3180         }
3181         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3182          be a wellknown GUID for this */
3183         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3184                 talloc_free(dn);
3185                 return LDB_ERR_OPERATIONS_ERROR;
3186         }
3187
3188         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3189         talloc_free(dn);
3190         return LDB_SUCCESS;
3191 }
3192
3193 /*
3194   compare a ldb_val to a string case insensitively
3195  */
3196 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3197 {
3198         size_t len = strlen(s);
3199         int ret;
3200         if (len > v->length) return 1;
3201         ret = strncasecmp(s, (const char *)v->data, v->length);
3202         if (ret != 0) return ret;
3203         if (v->length > len && v->data[len] != 0) {
3204                 return -1;
3205         }
3206         return 0;
3207 }
3208
3209
3210 /*
3211   load the UDV for a partition in v2 format
3212   The list is returned sorted, and with our local cursor added
3213  */
3214 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3215                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3216 {
3217         static const char *attrs[] = { "replUpToDateVector", NULL };
3218         struct ldb_result *r;
3219         const struct ldb_val *ouv_value;
3220         unsigned int i;
3221         int ret;
3222         uint64_t highest_usn;
3223         const struct GUID *our_invocation_id;
3224         struct timeval now = timeval_current();
3225
3226         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3227         if (ret != LDB_SUCCESS) {
3228                 return ret;
3229         }
3230
3231         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3232         if (ouv_value) {
3233                 enum ndr_err_code ndr_err;
3234                 struct replUpToDateVectorBlob ouv;
3235
3236                 ndr_err = ndr_pull_struct_blob(ouv_value, r,
3237                                                lp_iconv_convenience(ldb_get_opaque(samdb, "loadparm")), &ouv,
3238                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3239                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3240                         talloc_free(r);
3241                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3242                 }
3243                 if (ouv.version != 2) {
3244                         /* we always store as version 2, and
3245                          * replUpToDateVector is not replicated
3246                          */
3247                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3248                 }
3249
3250                 *count = ouv.ctr.ctr2.count;
3251                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3252         } else {
3253                 *count = 0;
3254                 *cursors = NULL;
3255         }
3256
3257         talloc_free(r);
3258
3259         our_invocation_id = samdb_ntds_invocation_id(samdb);
3260         if (!our_invocation_id) {
3261                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3262                 talloc_free(*cursors);
3263                 return LDB_ERR_OPERATIONS_ERROR;
3264         }
3265
3266         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3267         if (ret != LDB_SUCCESS) {
3268                 /* nothing to add - this can happen after a vampire */
3269                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3270                 return LDB_SUCCESS;
3271         }
3272
3273         for (i=0; i<*count; i++) {
3274                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3275                         (*cursors)[i].highest_usn = highest_usn;
3276                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3277                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3278                         return LDB_SUCCESS;
3279                 }
3280         }
3281
3282         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3283         if (! *cursors) {
3284                 return LDB_ERR_OPERATIONS_ERROR;
3285         }
3286
3287         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3288         (*cursors)[*count].highest_usn = highest_usn;
3289         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3290         (*count)++;
3291
3292         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3293
3294         return LDB_SUCCESS;
3295 }
3296
3297 /*
3298   load the UDV for a partition in version 1 format
3299   The list is returned sorted, and with our local cursor added
3300  */
3301 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3302                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3303 {
3304         struct drsuapi_DsReplicaCursor2 *v2;
3305         unsigned int i;
3306         int ret;
3307
3308         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3309         if (ret != LDB_SUCCESS) {
3310                 return ret;
3311         }
3312
3313         if (*count == 0) {
3314                 talloc_free(v2);
3315                 *cursors = NULL;
3316                 return LDB_SUCCESS;
3317         }
3318
3319         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3320         if (*cursors == NULL) {
3321                 talloc_free(v2);
3322                 return LDB_ERR_OPERATIONS_ERROR;
3323         }
3324
3325         for (i=0; i<*count; i++) {
3326                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3327                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3328         }
3329         talloc_free(v2);
3330         return LDB_SUCCESS;
3331 }
3332
3333 /*
3334   add a set of controls to a ldb_request structure based on a set of
3335   flags. See util.h for a list of available flags
3336  */
3337 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3338 {
3339         int ret;
3340         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3341                 struct ldb_search_options_control *options;
3342                 /* Using the phantom root control allows us to search all partitions */
3343                 options = talloc(req, struct ldb_search_options_control);
3344                 if (options == NULL) {
3345                         return LDB_ERR_OPERATIONS_ERROR;
3346                 }
3347                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3348
3349                 ret = ldb_request_add_control(req,
3350                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3351                                               true, options);
3352                 if (ret != LDB_SUCCESS) {
3353                         return ret;
3354                 }
3355         }
3356
3357         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3358                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3359                 if (ret != LDB_SUCCESS) {
3360                         return ret;
3361                 }
3362         }
3363
3364         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3365                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, true, NULL);
3366                 if (ret != LDB_SUCCESS) {
3367                         return ret;
3368                 }
3369         }
3370
3371         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3372                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3373                 if (!extended_ctrl) {
3374                         return LDB_ERR_OPERATIONS_ERROR;
3375                 }
3376                 extended_ctrl->type = 1;
3377
3378                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3379                 if (ret != LDB_SUCCESS) {
3380                         return ret;
3381                 }
3382         }
3383
3384         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3385                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3386                 if (ret != LDB_SUCCESS) {
3387                         return ret;
3388                 }
3389         }
3390
3391         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3392                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3393                 if (ret != LDB_SUCCESS) {
3394                         return ret;
3395                 }
3396         }
3397
3398         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3399                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3400                 if (ret != LDB_SUCCESS) {
3401                         return ret;
3402                 }
3403         }
3404
3405         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3406                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3407                 if (ret != LDB_SUCCESS) {
3408                         return ret;
3409                 }
3410         }
3411
3412         return LDB_SUCCESS;
3413 }
3414
3415 /*
3416   a modify with a set of controls
3417 */
3418 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3419                 uint32_t dsdb_flags)
3420 {
3421         struct ldb_request *req;
3422         int ret;
3423
3424         ret = ldb_build_mod_req(&req, ldb, ldb,
3425                                 message,
3426                                 NULL,
3427                                 NULL,
3428                                 ldb_op_default_callback,
3429                                 NULL);
3430
3431         if (ret != LDB_SUCCESS) return ret;
3432
3433         ret = dsdb_request_add_controls(req, dsdb_flags);
3434         if (ret != LDB_SUCCESS) {
3435                 talloc_free(req);
3436                 return ret;
3437         }
3438
3439         ret = dsdb_autotransaction_request(ldb, req);
3440
3441         talloc_free(req);
3442         return ret;
3443 }
3444
3445 /*
3446   like dsdb_modify() but set all the element flags to
3447   LDB_FLAG_MOD_REPLACE
3448  */
3449 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3450 {
3451         unsigned int i;
3452
3453         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3454         for (i=0;i<msg->num_elements;i++) {
3455                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3456         }
3457
3458         return dsdb_modify(ldb, msg, dsdb_flags);
3459 }
3460
3461
3462 /*
3463   search for attrs on one DN, allowing for dsdb_flags controls
3464  */
3465 int dsdb_search_dn(struct ldb_context *ldb,
3466                    TALLOC_CTX *mem_ctx,
3467                    struct ldb_result **_res,
3468                    struct ldb_dn *basedn,
3469                    const char * const *attrs,
3470                    uint32_t dsdb_flags)
3471 {
3472         int ret;
3473         struct ldb_request *req;
3474         struct ldb_result *res;
3475
3476         res = talloc_zero(mem_ctx, struct ldb_result);
3477         if (!res) {
3478                 return LDB_ERR_OPERATIONS_ERROR;
3479         }
3480
3481         ret = ldb_build_search_req(&req, ldb, res,
3482                                    basedn,
3483                                    LDB_SCOPE_BASE,
3484                                    NULL,
3485                                    attrs,
3486                                    NULL,
3487                                    res,
3488                                    ldb_search_default_callback,
3489                                    NULL);
3490         if (ret != LDB_SUCCESS) {
3491                 talloc_free(res);
3492                 return ret;
3493         }
3494
3495         ret = dsdb_request_add_controls(req, dsdb_flags);
3496         if (ret != LDB_SUCCESS) {
3497                 talloc_free(res);
3498                 return ret;
3499         }
3500
3501         ret = ldb_request(ldb, req);
3502         if (ret == LDB_SUCCESS) {
3503                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3504         }
3505
3506         talloc_free(req);
3507         if (ret != LDB_SUCCESS) {
3508                 talloc_free(res);
3509                 return ret;
3510         }
3511
3512         *_res = res;
3513         return LDB_SUCCESS;
3514 }
3515
3516 /*
3517   general search with dsdb_flags for controls
3518  */
3519 int dsdb_search(struct ldb_context *ldb,
3520                 TALLOC_CTX *mem_ctx,
3521                 struct ldb_result **_res,
3522                 struct ldb_dn *basedn,
3523                 enum ldb_scope scope,
3524                 const char * const *attrs,
3525                 uint32_t dsdb_flags,
3526                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3527 {
3528         int ret;
3529         struct ldb_request *req;
3530         struct ldb_result *res;
3531         va_list ap;
3532         char *expression = NULL;
3533         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3534
3535         res = talloc_zero(tmp_ctx, struct ldb_result);
3536         if (!res) {
3537                 talloc_free(tmp_ctx);
3538                 return LDB_ERR_OPERATIONS_ERROR;
3539         }
3540
3541         if (exp_fmt) {
3542                 va_start(ap, exp_fmt);
3543                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3544                 va_end(ap);
3545
3546                 if (!expression) {
3547                         talloc_free(tmp_ctx);
3548                         return LDB_ERR_OPERATIONS_ERROR;
3549                 }
3550         }
3551
3552         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3553                                    basedn,
3554                                    scope,
3555                                    expression,
3556                                    attrs,
3557                                    NULL,
3558                                    res,
3559                                    ldb_search_default_callback,
3560                                    NULL);
3561         if (ret != LDB_SUCCESS) {
3562                 talloc_free(tmp_ctx);
3563                 return ret;
3564         }
3565
3566         ret = dsdb_request_add_controls(req, dsdb_flags);
3567         if (ret != LDB_SUCCESS) {
3568                 talloc_free(tmp_ctx);
3569                 return ret;
3570         }
3571
3572         ret = ldb_request(ldb, req);
3573         if (ret == LDB_SUCCESS) {
3574                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3575         }
3576
3577         if (ret != LDB_SUCCESS) {
3578                 talloc_free(tmp_ctx);
3579                 return ret;
3580         }
3581
3582         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3583                 if (res->count == 0) {
3584                         talloc_free(tmp_ctx);
3585                         return LDB_ERR_NO_SUCH_OBJECT;
3586                 }
3587                 if (res->count != 1) {
3588                         talloc_free(tmp_ctx);
3589                         return LDB_ERR_CONSTRAINT_VIOLATION;
3590                 }
3591         }
3592
3593         *_res = talloc_steal(mem_ctx, res);
3594         talloc_free(tmp_ctx);
3595
3596         return LDB_SUCCESS;
3597 }
3598
3599
3600 /*
3601   general search with dsdb_flags for controls
3602   returns exactly 1 record or an error
3603  */
3604 int dsdb_search_one(struct ldb_context *ldb,
3605                     TALLOC_CTX *mem_ctx,
3606                     struct ldb_message **msg,
3607                     struct ldb_dn *basedn,
3608                     enum ldb_scope scope,
3609                     const char * const *attrs,
3610                     uint32_t dsdb_flags,
3611                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3612 {
3613         int ret;
3614         struct ldb_result *res;
3615         va_list ap;
3616         char *expression = NULL;
3617         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3618
3619         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
3620
3621         res = talloc_zero(tmp_ctx, struct ldb_result);
3622         if (!res) {
3623                 talloc_free(tmp_ctx);
3624                 return LDB_ERR_OPERATIONS_ERROR;
3625         }
3626
3627         if (exp_fmt) {
3628                 va_start(ap, exp_fmt);
3629                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3630                 va_end(ap);
3631
3632                 if (!expression) {
3633                         talloc_free(tmp_ctx);
3634                         return LDB_ERR_OPERATIONS_ERROR;
3635                 }
3636         }
3637
3638         ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3639                           dsdb_flags, "%s", expression);
3640         if (ret != LDB_SUCCESS) {
3641                 talloc_free(tmp_ctx);
3642                 return ret;
3643         }
3644
3645         *msg = talloc_steal(mem_ctx, res->msgs[0]);
3646         talloc_free(tmp_ctx);
3647
3648         return LDB_SUCCESS;
3649 }
3650
3651 /* returns back the forest DNS name */
3652 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
3653 {
3654         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
3655                                                           ldb_get_root_basedn(ldb));
3656         char *p;
3657
3658         if (forest_name == NULL) {
3659                 return NULL;
3660         }
3661
3662         p = strchr(forest_name, '/');
3663         if (p) {
3664                 *p = '\0';
3665         }
3666
3667         return forest_name;
3668 }
3669
3670 /*
3671    validate that an invocationID belongs to the specified user sid.
3672    The user SID must be a domain controller account (either RODC or
3673    RWDC)
3674  */
3675 int dsdb_validate_invocation_id(struct ldb_context *ldb,
3676                                 const struct GUID *invocation_id,
3677                                 const struct dom_sid *sid)
3678 {
3679         /* strategy:
3680             - find DN of record with the invocationID in the
3681               configuration partition
3682             - remote "NTDS Settings" component from DN
3683             - do a base search on that DN for serverReference with
3684               extended-dn enabled
3685             - extract objectSID from resulting serverReference
3686               attribute
3687             - check this sid matches the sid argument
3688         */
3689         struct ldb_dn *config_dn;
3690         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3691         struct ldb_message *msg;
3692         const char *attrs1[] = { NULL };
3693         const char *attrs2[] = { "serverReference", NULL };
3694         int ret;
3695         struct ldb_dn *dn, *account_dn;
3696         struct dom_sid sid2;
3697         NTSTATUS status;
3698
3699         config_dn = ldb_get_config_basedn(ldb);
3700
3701         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
3702                               attrs1, 0, "(&(invocationID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, invocation_id));
3703         if (ret != LDB_SUCCESS) {
3704                 DEBUG(1,(__location__ ": Failed to find invocationID %s for sid %s\n",
3705                          GUID_string(tmp_ctx, invocation_id), dom_sid_string(tmp_ctx, sid)));
3706                 talloc_free(tmp_ctx);
3707                 return LDB_ERR_OPERATIONS_ERROR;
3708         }
3709         dn = msg->dn;
3710
3711         if (!ldb_dn_remove_child_components(dn, 1)) {
3712                 talloc_free(tmp_ctx);
3713                 return LDB_ERR_OPERATIONS_ERROR;
3714         }
3715
3716         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
3717                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
3718                               "(objectClass=server)");
3719         if (ret != LDB_SUCCESS) {
3720                 DEBUG(1,(__location__ ": Failed to find server record 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         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
3727         if (account_dn == NULL) {
3728                 DEBUG(1,(__location__ ": Failed to find account_dn 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         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
3735         if (!NT_STATUS_IS_OK(status)) {
3736                 DEBUG(1,(__location__ ": Failed to find SID for invocationID %s, sid %s\n",
3737                          GUID_string(tmp_ctx, invocation_id), dom_sid_string(tmp_ctx, sid)));
3738                 talloc_free(tmp_ctx);
3739                 return LDB_ERR_OPERATIONS_ERROR;
3740         }
3741
3742         if (!dom_sid_equal(sid, &sid2)) {
3743                 /* someone is trying to spoof another account */
3744                 DEBUG(0,(__location__ ": Bad invocationID invocationID %s for sid %s - expected sid %s\n",
3745                          GUID_string(tmp_ctx, invocation_id),
3746                          dom_sid_string(tmp_ctx, sid),
3747                          dom_sid_string(tmp_ctx, &sid2)));
3748                 talloc_free(tmp_ctx);
3749                 return LDB_ERR_OPERATIONS_ERROR;
3750         }
3751
3752         talloc_free(tmp_ctx);
3753         return LDB_SUCCESS;
3754 }