Merge branch 'v4-0-test' of ssh://git.samba.org/data/git/samba into pac-verify
[ira/wip.git] / source4 / dsdb / samdb / ldb_modules / samldb.c
1 /* 
2    SAM ldb module
3
4    Copyright (C) Simo Sorce  2004
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
6
7    * NOTICE: this module is NOT released under the GNU LGPL license as
8    * other ldb code. This module is release under the GNU GPL v3 or
9    * later license.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 /*
26  *  Name: ldb
27  *
28  *  Component: ldb samldb module
29  *
30  *  Description: add embedded user/group creation functionality
31  *
32  *  Author: Simo Sorce
33  */
34
35 #include "includes.h"
36 #include "libcli/ldap/ldap_ndr.h"
37 #include "lib/ldb/include/ldb_errors.h"
38 #include "lib/ldb/include/ldb.h"
39 #include "lib/ldb/include/ldb_private.h"
40 #include "dsdb/samdb/samdb.h"
41 #include "libcli/security/security.h"
42 #include "librpc/gen_ndr/ndr_security.h"
43 #include "util/util_ldb.h"
44
45 int samldb_notice_sid(struct ldb_module *module, 
46                       TALLOC_CTX *mem_ctx, const struct dom_sid *sid);
47
48 static bool samldb_msg_add_sid(struct ldb_module *module, struct ldb_message *msg, const char *name, const struct dom_sid *sid)
49 {
50         struct ldb_val v;
51         enum ndr_err_code ndr_err;
52
53         ndr_err = ndr_push_struct_blob(&v, msg, NULL, sid,
54                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
55         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
56                 return false;
57         }
58         return (ldb_msg_add_value(msg, name, &v, NULL) == 0);
59 }
60
61 /*
62   allocate a new id, attempting to do it atomically
63   return 0 on failure, the id on success
64 */
65 static int samldb_set_next_rid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
66                                struct ldb_dn *dn, uint32_t old_id, uint32_t new_id)
67 {
68         struct ldb_message msg;
69         int ret;
70         struct ldb_val vals[2];
71         struct ldb_message_element els[2];
72
73         if (new_id == 0) {
74                 /* out of IDs ! */
75                 ldb_set_errstring(ldb, "Are we out of valid IDs ?\n");
76                 return LDB_ERR_OPERATIONS_ERROR;
77         }
78
79         /* we do a delete and add as a single operation. That prevents
80            a race, in case we are not actually on a transaction db */
81         ZERO_STRUCT(msg);
82         msg.dn = ldb_dn_copy(mem_ctx, dn);
83         if (!msg.dn) {
84                 ldb_oom(ldb);
85                 return LDB_ERR_OPERATIONS_ERROR;
86         }
87         msg.num_elements = 2;
88         msg.elements = els;
89
90         els[0].num_values = 1;
91         els[0].values = &vals[0];
92         els[0].flags = LDB_FLAG_MOD_DELETE;
93         els[0].name = talloc_strdup(mem_ctx, "nextRid");
94         if (!els[0].name) {
95                 ldb_oom(ldb);
96                 return LDB_ERR_OPERATIONS_ERROR;
97         }
98
99         els[1].num_values = 1;
100         els[1].values = &vals[1];
101         els[1].flags = LDB_FLAG_MOD_ADD;
102         els[1].name = els[0].name;
103
104         vals[0].data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", old_id);
105         if (!vals[0].data) {
106                 ldb_oom(ldb);
107                 return LDB_ERR_OPERATIONS_ERROR;
108         }
109         vals[0].length = strlen((char *)vals[0].data);
110
111         vals[1].data = (uint8_t *)talloc_asprintf(mem_ctx, "%u", new_id);
112         if (!vals[1].data) {
113                 ldb_oom(ldb);
114                 return LDB_ERR_OPERATIONS_ERROR;
115         }
116         vals[1].length = strlen((char *)vals[1].data);
117
118         ret = ldb_modify(ldb, &msg);
119         return ret;
120 }
121
122 /*
123   allocate a new id, attempting to do it atomically
124   return 0 on failure, the id on success
125 */
126 static int samldb_find_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
127                                 struct ldb_dn *dn, uint32_t *old_rid)
128 {
129         const char * const attrs[2] = { "nextRid", NULL };
130         struct ldb_result *res = NULL;
131         int ret;
132         const char *str;
133
134         ret = ldb_search(module->ldb, dn, LDB_SCOPE_BASE, "nextRid=*", attrs, &res);
135         if (ret != LDB_SUCCESS) {
136                 return ret;
137         }
138         if (res->count != 1) {
139                 talloc_free(res);
140                 return LDB_ERR_OPERATIONS_ERROR;
141         }
142
143         str = ldb_msg_find_attr_as_string(res->msgs[0], "nextRid", NULL);
144         if (str == NULL) {
145                 ldb_asprintf_errstring(module->ldb,
146                                         "attribute nextRid not found in %s\n",
147                                         ldb_dn_get_linearized(dn));
148                 talloc_free(res);
149                 return LDB_ERR_OPERATIONS_ERROR;
150         }
151
152         *old_rid = strtol(str, NULL, 0);
153         talloc_free(res);
154         return LDB_SUCCESS;
155 }
156
157 static int samldb_allocate_next_rid(struct ldb_module *module, TALLOC_CTX *mem_ctx,
158                                     struct ldb_dn *dn, const struct dom_sid *dom_sid, 
159                                     struct dom_sid **new_sid)
160 {
161         struct dom_sid *obj_sid;
162         uint32_t old_rid;
163         int ret;
164         
165         ret = samldb_find_next_rid(module, mem_ctx, dn, &old_rid);      
166         if (ret) {
167                 return ret;
168         }
169                 
170         /* return the new object sid */
171         obj_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid);
172                 
173         *new_sid = dom_sid_add_rid(mem_ctx, dom_sid, old_rid + 1);
174         if (!*new_sid) {
175                 return LDB_ERR_OPERATIONS_ERROR;
176         }
177
178         ret = samldb_notice_sid(module, mem_ctx, *new_sid);
179         if (ret != 0) {
180                 /* gah, there are conflicting sids.
181                  * This is a critical situation it means that someone messed up with
182                  * the DB and nextRid is not returning free RIDs, report an error
183                  * and refuse to create any user until the problem is fixed */
184                 ldb_asprintf_errstring(module->ldb,
185                                         "Critical Error: unconsistent DB, unable to retireve an unique RID to generate a new SID: %s",
186                                         ldb_errstring(module->ldb));
187                 return ret;
188         }
189         return ret;
190 }
191
192 /* search the domain related to the provided dn
193    allocate a new RID for the domain
194    return the new sid string
195 */
196 static int samldb_get_new_sid(struct ldb_module *module, 
197                               TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
198                               struct ldb_dn *dom_dn, 
199                               struct dom_sid **sid)
200 {
201         const char * const attrs[2] = { "objectSid", NULL };
202         struct ldb_result *res = NULL;
203         int ret;
204         struct dom_sid *dom_sid;
205
206         /* get the domain component part of the provided dn */
207
208         /* find the domain sid */
209
210         ret = ldb_search(module->ldb, dom_dn, LDB_SCOPE_BASE, "objectSid=*", attrs, &res);
211         if (ret != LDB_SUCCESS) {
212                 ldb_asprintf_errstring(module->ldb,
213                                         "samldb_get_new_sid: error retrieving domain sid from %s: %s!\n",
214                                         ldb_dn_get_linearized(dom_dn),
215                                         ldb_errstring(module->ldb));
216                 talloc_free(res);
217                 return ret;
218         }
219
220         if (res->count != 1) {
221                 ldb_asprintf_errstring(module->ldb,
222                                         "samldb_get_new_sid: error retrieving domain sid from %s: not found!\n",
223                                         ldb_dn_get_linearized(dom_dn));
224                 talloc_free(res);
225                 return LDB_ERR_CONSTRAINT_VIOLATION;
226         }
227
228         dom_sid = samdb_result_dom_sid(res, res->msgs[0], "objectSid");
229         if (dom_sid == NULL) {
230                 ldb_set_errstring(module->ldb, "samldb_get_new_sid: error parsing domain sid!\n");
231                 talloc_free(res);
232                 return LDB_ERR_CONSTRAINT_VIOLATION;
233         }
234
235         /* allocate a new Rid for the domain */
236         ret = samldb_allocate_next_rid(module, mem_ctx, dom_dn, dom_sid, sid);
237         if (ret != 0) {
238                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "Failed to increment nextRid of %s: %s\n", ldb_dn_get_linearized(dom_dn), ldb_errstring(module->ldb));
239                 talloc_free(res);
240                 return ret;
241         }
242
243         talloc_free(res);
244
245         return ret;
246 }
247
248 /* If we are adding new users/groups, we need to update the nextRid
249  * attribute to be 'above' all incoming users RIDs.  This tries to
250  * avoid clashes in future */
251
252 int samldb_notice_sid(struct ldb_module *module, 
253                       TALLOC_CTX *mem_ctx, const struct dom_sid *sid)
254 {
255         int ret;
256         struct ldb_dn *dom_dn;
257         struct dom_sid *dom_sid;
258         const char *attrs[] = { NULL };
259         struct ldb_result *dom_res;
260         struct ldb_result *res;
261         uint32_t old_rid;
262
263         /* find if this SID already exists */
264         ret = ldb_search_exp_fmt(module->ldb, mem_ctx, &res,
265                                  NULL, LDB_SCOPE_SUBTREE, attrs,
266                                  "(objectSid=%s)", ldap_encode_ndr_dom_sid(mem_ctx, sid));
267         if (ret == LDB_SUCCESS) {
268                 if (res->count > 0) {
269                         talloc_free(res);
270                         ldb_asprintf_errstring(module->ldb,
271                                                 "Attempt to add record with SID %s rejected,"
272                                                 " because this SID is already in the database",
273                                                 dom_sid_string(mem_ctx, sid));
274                         /* We have a duplicate SID, we must reject the add */
275                         return LDB_ERR_CONSTRAINT_VIOLATION;
276                 }
277                 talloc_free(res);
278         } else {
279                 ldb_asprintf_errstring(module->ldb,
280                                         "samldb_notice_sid: error searching to see if sid %s is in use: %s\n", 
281                                         dom_sid_string(mem_ctx, sid), 
282                                         ldb_errstring(module->ldb));
283                 return ret;
284         }
285
286         dom_sid = dom_sid_dup(mem_ctx, sid);
287         if (!dom_sid) {
288                 return LDB_ERR_OPERATIONS_ERROR;
289         }
290         /* get the domain component part of the provided SID */
291         dom_sid->num_auths--;
292
293         /* find the domain DN */
294         ret = ldb_search_exp_fmt(module->ldb, mem_ctx, &dom_res,
295                                  NULL, LDB_SCOPE_SUBTREE, attrs,
296                                  "(&(objectSid=%s)(|(|(objectClass=domain)(objectClass=builtinDomain))(objectClass=samba4LocalDomain)))", 
297                                  ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
298         if (ret == LDB_SUCCESS) {
299                 if (dom_res->count == 0) {
300                         talloc_free(dom_res);
301                         /* This isn't an operation on a domain we know about, so nothing to update */
302                         return LDB_SUCCESS;
303                 }
304
305                 if (dom_res->count > 1) {
306                         talloc_free(dom_res);
307                         ldb_asprintf_errstring(module->ldb,
308                                         "samldb_notice_sid: error retrieving domain from sid: duplicate (found %d) domain: %s!\n", 
309                                         dom_res->count, dom_sid_string(dom_res, dom_sid));
310                         return LDB_ERR_OPERATIONS_ERROR;
311                 }
312         } else {
313                 ldb_asprintf_errstring(module->ldb,
314                                         "samldb_notice_sid: error retrieving domain from sid: %s: %s\n", 
315                                         dom_sid_string(dom_res, dom_sid), 
316                                         ldb_errstring(module->ldb));
317                 return ret;
318         }
319
320         dom_dn = dom_res->msgs[0]->dn;
321
322         ret = samldb_find_next_rid(module, mem_ctx, 
323                                    dom_dn, &old_rid);
324         if (ret) {
325                 talloc_free(dom_res);
326                 return ret;
327         }
328
329         if (old_rid <= sid->sub_auths[sid->num_auths - 1]) {
330                 ret = samldb_set_next_rid(module->ldb, mem_ctx, dom_dn, old_rid, 
331                                           sid->sub_auths[sid->num_auths - 1] + 1);
332         }
333         talloc_free(dom_res);
334         return ret;
335 }
336
337 static int samldb_handle_sid(struct ldb_module *module, 
338                              TALLOC_CTX *mem_ctx, struct ldb_message *msg2,
339                              struct ldb_dn *parent_dn)
340 {
341         int ret;
342         
343         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg2, "objectSid");
344         if (sid == NULL) { 
345                 ret = samldb_get_new_sid(module, msg2, msg2->dn, parent_dn, &sid);
346                 if (ret != 0) {
347                         return ret;
348                 }
349
350                 if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
351                         talloc_free(sid);
352                         return LDB_ERR_OPERATIONS_ERROR;
353                 }
354                 talloc_free(sid);
355                 ret = LDB_SUCCESS;
356         } else {
357                 ret = samldb_notice_sid(module, msg2, sid);
358         }
359         return ret;
360 }
361
362 static int samldb_generate_samAccountName(struct ldb_module *module, TALLOC_CTX *mem_ctx, 
363                                           struct ldb_dn *dom_dn, char **name) 
364 {
365         const char *attrs[] = { NULL };
366         struct ldb_result *res;
367         int ret;
368         
369         /* Format: $000000-000000000000 */
370         
371         do {
372                 *name = talloc_asprintf(mem_ctx, "$%.6X-%.6X%.6X", (unsigned int)generate_random(), (unsigned int)generate_random(), (unsigned int)generate_random());
373                 /* TODO: Figure out exactly what this is meant to conflict with */
374                 ret = ldb_search_exp_fmt(module->ldb,
375                                          mem_ctx, &res, dom_dn, LDB_SCOPE_SUBTREE, attrs,
376                                          "samAccountName=%s",
377                                          ldb_binary_encode_string(mem_ctx, *name));
378                 if (ret != LDB_SUCCESS) {
379                         ldb_asprintf_errstring(module->ldb, "samldb: Failure searching to determine if samAccountName %s is unique: %s",
380                                                *name, ldb_errstring(module->ldb));
381                         return ret;
382                 }
383
384                 if (res->count == 0) {
385                         talloc_free(res);
386                         /* Great. There are no conflicting users/groups/etc */
387                         return LDB_SUCCESS;
388                 } else {
389                         talloc_free(*name);
390                         /* gah, there is a conflicting name, lets move around the loop again... */
391                 }
392         } while (1);
393 }
394
395 static int samldb_fill_group_object(struct ldb_module *module, const struct ldb_message *msg,
396                                                     struct ldb_message **ret_msg)
397 {
398         int ret;
399         unsigned int group_type;
400         char *name;
401         struct ldb_message *msg2;
402         struct ldb_dn *dom_dn;
403         const char *rdn_name;
404         TALLOC_CTX *mem_ctx = talloc_new(msg);
405         const char *errstr;
406         if (!mem_ctx) {
407                 return LDB_ERR_OPERATIONS_ERROR;
408         }
409
410         /* build the new msg */
411         msg2 = ldb_msg_copy(mem_ctx, msg);
412         if (!msg2) {
413                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: ldb_msg_copy failed!\n");
414                 talloc_free(mem_ctx);
415                 return LDB_ERR_OPERATIONS_ERROR;
416         }
417
418         ret = samdb_copy_template(module->ldb, msg2, 
419                                   "group",
420                                   &errstr);
421         if (ret != 0) {
422                 
423                 talloc_free(mem_ctx);
424                 return ret;
425         }
426
427         rdn_name = ldb_dn_get_rdn_name(msg2->dn);
428
429         if (strcasecmp(rdn_name, "cn") != 0) {
430                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_group_object: Bad RDN (%s) for group!\n", rdn_name);
431                 talloc_free(mem_ctx);
432                 return LDB_ERR_CONSTRAINT_VIOLATION;
433         }
434
435         ret = samdb_search_for_parent_domain(module->ldb, mem_ctx, msg2->dn, &dom_dn, &errstr);
436         if (ret != LDB_SUCCESS) {
437                 ldb_asprintf_errstring(module->ldb,
438                                        "samldb_fill_group_object: %s", errstr);
439                 return ret;
440         }
441
442         /* Generate a random name, if no samAccountName was supplied */
443         if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
444                 ret = samldb_generate_samAccountName(module, mem_ctx, dom_dn, &name);
445                 if (ret != LDB_SUCCESS) {
446                         talloc_free(mem_ctx);
447                         return ret;
448                 }
449                 ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
450                 if (ret) {
451                         talloc_free(mem_ctx);
452                         return ret;
453                 }
454         }
455         
456         if (ldb_msg_find_element(msg2, "sAMAccountType") != NULL) {
457                 ldb_asprintf_errstring(module->ldb, "sAMAccountType must not be specified");
458                 talloc_free(mem_ctx);
459                 return LDB_ERR_UNWILLING_TO_PERFORM;
460         }
461         group_type = samdb_result_uint(msg2, "groupType", 0);
462         if (group_type == 0) {
463                 ldb_asprintf_errstring(module->ldb, "groupType invalid");
464                 talloc_free(mem_ctx);
465                 return LDB_ERR_UNWILLING_TO_PERFORM;
466         } else {
467                 unsigned int account_type = samdb_gtype2atype(group_type);
468                 ret = samdb_msg_add_uint(module->ldb, msg2, msg2,
469                                          "sAMAccountType",
470                                          account_type);
471                 if (ret != LDB_SUCCESS) {
472                         return ret;
473                 }
474         }
475
476         /* Manage SID allocation, conflicts etc */
477         ret = samldb_handle_sid(module, mem_ctx, msg2, dom_dn); 
478
479         if (ret == LDB_SUCCESS) {
480                 talloc_steal(msg, msg2);
481                 *ret_msg = msg2;
482         }
483         talloc_free(mem_ctx);
484         return ret;
485 }
486
487 static int samldb_fill_user_or_computer_object(struct ldb_module *module, const struct ldb_message *msg, struct ldb_message **ret_msg)
488 {
489         int ret;
490         char *name;
491         struct ldb_message *msg2;
492         struct ldb_dn *dom_dn;
493         const char *rdn_name;
494         TALLOC_CTX *mem_ctx = talloc_new(msg);
495         const char *errstr;
496         unsigned int user_account_control;
497         if (!mem_ctx) {
498                 return LDB_ERR_OPERATIONS_ERROR;
499         }
500
501         /* build the new msg */
502         msg2 = ldb_msg_copy(mem_ctx, msg);
503         if (!msg2) {
504                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_user_or_computer_object: ldb_msg_copy failed!\n");
505                 talloc_free(mem_ctx);
506                 return LDB_ERR_OPERATIONS_ERROR;
507         }
508
509         ret = samdb_copy_template(module->ldb, msg2, 
510                                   "user",
511                                   &errstr);
512         if (ret) {
513                 ldb_asprintf_errstring(module->ldb, 
514                                        "samldb_fill_user_or_computer_object: Error copying user template: %s\n",
515                                        errstr);
516                 talloc_free(mem_ctx);
517                 return ret;
518         }
519
520         rdn_name = ldb_dn_get_rdn_name(msg2->dn);
521
522         if (strcasecmp(rdn_name, "cn") != 0) {
523                 ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for user/computer, should be CN=!\n", rdn_name);
524                 talloc_free(mem_ctx);
525                 return LDB_ERR_CONSTRAINT_VIOLATION;
526         }
527
528         ret = samdb_search_for_parent_domain(module->ldb, mem_ctx, msg2->dn, &dom_dn, &errstr);
529         if (ret != LDB_SUCCESS) {
530                 ldb_asprintf_errstring(module->ldb,
531                                        "samldb_fill_user_or_computer_object: %s", errstr);
532                 return ret;
533         }
534
535         if (ldb_msg_find_element(msg2, "samAccountName") == NULL) {
536                 ret = samldb_generate_samAccountName(module, mem_ctx, dom_dn, &name);
537                 if (ret != LDB_SUCCESS) {
538                         talloc_free(mem_ctx);
539                         return ret;
540                 }
541                 ret = samdb_find_or_add_attribute(module->ldb, msg2, "sAMAccountName", name);
542                 if (ret) {
543                         talloc_free(mem_ctx);
544                         return ret;
545                 }
546         }
547
548         if (ldb_msg_find_element(msg2, "sAMAccountType") != NULL) {
549                 ldb_asprintf_errstring(module->ldb, "sAMAccountType must not be specified");
550                 talloc_free(mem_ctx);
551                 return LDB_ERR_UNWILLING_TO_PERFORM;
552         }
553         user_account_control = samdb_result_uint(msg2, "userAccountControl", 0);
554         if (user_account_control == 0) {
555                 ldb_asprintf_errstring(module->ldb, "userAccountControl invalid");
556                 talloc_free(mem_ctx);
557                 return LDB_ERR_UNWILLING_TO_PERFORM;
558         } else {
559                 unsigned int account_type = samdb_uf2atype(user_account_control);
560                 ret = samdb_msg_add_uint(module->ldb, msg2, msg2,
561                                          "sAMAccountType",
562                                          account_type);
563                 if (ret != LDB_SUCCESS) {
564                         return ret;
565                 }
566         }
567
568         /* Manage SID allocation, conflicts etc */
569         ret = samldb_handle_sid(module, mem_ctx, msg2, dom_dn); 
570
571         /* TODO: userAccountControl, badPwdCount, codePage, countryCode, badPasswordTime, lastLogoff, lastLogon, pwdLastSet, primaryGroupID, accountExpires, logonCount */
572
573         if (ret == 0) {
574                 *ret_msg = msg2;
575                 talloc_steal(msg, msg2);
576         }
577         talloc_free(mem_ctx);
578         return ret;
579 }
580         
581 static int samldb_fill_foreignSecurityPrincipal_object(struct ldb_module *module, const struct ldb_message *msg, 
582                                                        struct ldb_message **ret_msg)
583 {
584         struct ldb_message *msg2;
585         const char *rdn_name;
586         struct dom_sid *dom_sid;
587         struct dom_sid *sid;
588         const char *dom_attrs[] = { "name", NULL };
589         struct ldb_message **dom_msgs;
590         const char *errstr;
591         int ret;
592
593         TALLOC_CTX *mem_ctx = talloc_new(msg);
594         if (!mem_ctx) {
595                 return LDB_ERR_OPERATIONS_ERROR;
596         }
597
598         /* build the new msg */
599         msg2 = ldb_msg_copy(mem_ctx, msg);
600         if (!msg2) {
601                 ldb_debug(module->ldb, LDB_DEBUG_FATAL, "samldb_fill_foreignSecurityPrincipal_object: ldb_msg_copy failed!\n");
602                 talloc_free(mem_ctx);
603                 return LDB_ERR_OPERATIONS_ERROR;
604         }
605
606         ret = samdb_copy_template(module->ldb, msg2, 
607                                   "ForeignSecurityPrincipal",
608                                   &errstr);
609         if (ret != 0) {
610                 ldb_asprintf_errstring(module->ldb, 
611                                        "samldb_fill_foreignSecurityPrincipal_object: "
612                                        "Error copying template: %s",
613                                     errstr);
614                 talloc_free(mem_ctx);
615                 return ret;
616         }
617
618         rdn_name = ldb_dn_get_rdn_name(msg2->dn);
619
620         if (strcasecmp(rdn_name, "cn") != 0) {
621                 ldb_asprintf_errstring(module->ldb, "Bad RDN (%s=) for ForeignSecurityPrincipal, should be CN=!", rdn_name);
622                 talloc_free(mem_ctx);
623                 return LDB_ERR_CONSTRAINT_VIOLATION;
624         }
625
626         sid = samdb_result_dom_sid(msg2, msg, "objectSid");
627         if (!sid) {
628                 /* Slightly different for the foreign sids.  We don't want
629                  * domain SIDs ending up there, it would cause all sorts of
630                  * pain */
631
632                 sid = dom_sid_parse_talloc(msg2, (const char *)ldb_dn_get_rdn_val(msg2->dn)->data);
633                 if (!sid) {
634                         ldb_set_errstring(module->ldb, "No valid found SID in ForeignSecurityPrincipal CN!");
635                         talloc_free(mem_ctx);
636                         return LDB_ERR_CONSTRAINT_VIOLATION;
637                 }
638
639                 if ( ! samldb_msg_add_sid(module, msg2, "objectSid", sid)) {
640                         talloc_free(sid);
641                         return LDB_ERR_OPERATIONS_ERROR;
642                 }
643
644                 dom_sid = dom_sid_dup(mem_ctx, sid);
645                 if (!dom_sid) {
646                         talloc_free(mem_ctx);
647                         return LDB_ERR_OPERATIONS_ERROR;
648                 }
649                 /* get the domain component part of the provided SID */
650                 dom_sid->num_auths--;
651
652                 /* find the domain DN */
653
654                 ret = gendb_search(module->ldb,
655                                    mem_ctx, NULL, &dom_msgs, dom_attrs,
656                                    "(&(objectSid=%s)(objectclass=domain))",
657                                    ldap_encode_ndr_dom_sid(mem_ctx, dom_sid));
658                 if (ret >= 1) {
659                         /* We don't really like the idea of foreign sids that are not foreign, but it happens */
660                         const char *name = samdb_result_string(dom_msgs[0], "name", NULL);
661                         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "NOTE (strange but valid): Adding foreign SID record with SID %s, but this domian (%s) is already in the database", 
662                                   dom_sid_string(mem_ctx, sid), name); 
663                 } else if (ret == -1) {
664                         ldb_asprintf_errstring(module->ldb,
665                                                 "samldb_fill_foreignSecurityPrincipal_object: error searching for a domain with this sid: %s\n", 
666                                                 dom_sid_string(mem_ctx, dom_sid));
667                         talloc_free(dom_msgs);
668                         return LDB_ERR_OPERATIONS_ERROR;
669                 }
670         }
671
672         /* This isn't an operation on a domain we know about, so just
673          * check for the SID, looking for duplicates via the common
674          * code */
675         ret = samldb_notice_sid(module, msg2, sid);
676         if (ret == 0) {
677                 talloc_steal(msg, msg2);
678                 *ret_msg = msg2;
679         }
680         
681         return ret;
682 }
683
684 /* add_record */
685
686 /*
687  * FIXME
688  *
689  * Actually this module is not async at all as it does a number of sync searches
690  * in the process. It still to be decided how to deal with it properly so it is
691  * left SYNC for now until we think of a good solution.
692  */
693
694 static int samldb_add(struct ldb_module *module, struct ldb_request *req)
695 {
696         const struct ldb_message *msg = req->op.add.message;
697         struct ldb_message *msg2 = NULL;
698         struct ldb_request *down_req;
699         int ret;
700
701         ldb_debug(module->ldb, LDB_DEBUG_TRACE, "samldb_add_record\n");
702
703         if (ldb_dn_is_special(msg->dn)) { /* do not manipulate our control entries */
704                 return ldb_next_request(module, req);
705         }
706
707         /* is user or computer? */
708         if ((samdb_find_attribute(module->ldb, msg, "objectclass", "user") != NULL) || 
709             (samdb_find_attribute(module->ldb, msg, "objectclass", "computer") != NULL)) {
710                 /*  add all relevant missing objects */
711                 ret = samldb_fill_user_or_computer_object(module, msg, &msg2);
712                 if (ret) {
713                         return ret;
714                 }
715         }
716
717         /* is group? add all relevant missing objects */
718         if ( ! msg2 ) {
719                 if (samdb_find_attribute(module->ldb, msg, "objectclass", "group") != NULL) {
720                         ret = samldb_fill_group_object(module, msg, &msg2);
721                         if (ret) {
722                                 return ret;
723                         }
724                 }
725         }
726
727         /* perhaps a foreignSecurityPrincipal? */
728         if ( ! msg2 ) {
729                 if (samdb_find_attribute(module->ldb, msg, "objectclass", "foreignSecurityPrincipal") != NULL) {
730                         ret = samldb_fill_foreignSecurityPrincipal_object(module, msg, &msg2);
731                         if (ret) {
732                                 return ret;
733                         }
734                 }
735         }
736
737         if (msg2 == NULL) {
738                 return ldb_next_request(module, req);
739         }
740
741         down_req = talloc(req, struct ldb_request);
742         if (down_req == NULL) {
743                 return LDB_ERR_OPERATIONS_ERROR;
744         }
745
746         *down_req = *req;
747         
748         down_req->op.add.message = talloc_steal(down_req, msg2);
749
750         ldb_set_timeout_from_prev_req(module->ldb, req, down_req);
751
752         /* go on with the call chain */
753         ret = ldb_next_request(module, down_req);
754
755         /* do not free down_req as the call results may be linked to it,
756          * it will be freed when the upper level request get freed */
757         if (ret == LDB_SUCCESS) {
758                 req->handle = down_req->handle;
759         }
760
761         return ret;
762 }
763
764 /* modify */
765 static int samldb_modify(struct ldb_module *module, struct ldb_request *req)
766 {
767         struct ldb_message *msg;
768         struct ldb_message_element *el, *el2;
769         int ret;
770         unsigned int group_type, user_account_control, account_type;
771         if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
772                 return ldb_next_request(module, req);
773         }
774
775         if (ldb_msg_find_element(req->op.mod.message, "sAMAccountType") != NULL) {
776                 ldb_asprintf_errstring(module->ldb, "sAMAccountType must not be specified");
777                 return LDB_ERR_UNWILLING_TO_PERFORM;
778         }
779
780         el = ldb_msg_find_element(req->op.mod.message, "groupType");
781         if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
782                 req->op.mod.message = msg = ldb_msg_copy_shallow(req, req->op.mod.message);
783
784                 group_type = strtoul((const char *)el->values[0].data, NULL, 0);
785                 account_type =  samdb_gtype2atype(group_type);
786                 ret = samdb_msg_add_uint(module->ldb, msg, msg,
787                                          "sAMAccountType",
788                                          account_type);
789                 if (ret != LDB_SUCCESS) {
790                         return ret;
791                 }
792                 el2 = ldb_msg_find_element(msg, "sAMAccountType");
793                 el2->flags = LDB_FLAG_MOD_REPLACE;
794         }
795
796         el = ldb_msg_find_element(req->op.mod.message, "userAccountControl");
797         if (el && el->flags & (LDB_FLAG_MOD_ADD|LDB_FLAG_MOD_REPLACE) && el->num_values == 1) {
798                 req->op.mod.message = msg = ldb_msg_copy_shallow(req, req->op.mod.message);
799
800                 user_account_control = strtoul((const char *)el->values[0].data, NULL, 0);
801                 account_type = samdb_uf2atype(user_account_control);
802                 ret = samdb_msg_add_uint(module->ldb, msg, msg,
803                                          "sAMAccountType",
804                                          account_type);
805                 if (ret != LDB_SUCCESS) {
806                         return ret;
807                 }
808                 el2 = ldb_msg_find_element(msg, "sAMAccountType");
809                 el2->flags = LDB_FLAG_MOD_REPLACE;
810         }
811         return ldb_next_request(module, req);
812 }
813
814
815 static int samldb_init(struct ldb_module *module)
816 {
817         return ldb_next_init(module);
818 }
819
820 _PUBLIC_ const struct ldb_module_ops ldb_samldb_module_ops = {
821         .name          = "samldb",
822         .init_context  = samldb_init,
823         .add           = samldb_add,
824         .modify        = samldb_modify
825 };