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