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