libsmbconf: fix comment headers in smbconf.h
[kai/samba.git] / source3 / groupdb / mapping_ldb.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *
4  *  group mapping code on top of ldb
5  *
6  *  Copyright (C) Andrew Tridgell              2006
7  *
8  * based on tdb group mapping code from groupdb/mapping.c
9  *  
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 3 of the License, or
13  *  (at your option) any later version.
14  *  
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *  
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #include "includes.h"
25 #include "groupdb/mapping.h"
26 #include "lib/ldb/include/includes.h"
27 #include "lib/ldb/include/ldb_errors.h"
28
29 static struct ldb_context *ldb;
30
31 static bool mapping_upgrade(const char *tdb_path);
32
33 /*
34   connect to the group mapping ldb
35 */
36 static bool init_group_mapping(void)
37 {
38         bool existed;
39         const char *init_ldif[] = 
40                 { "dn: @ATTRIBUTES\n" \
41                   "ntName: CASE_INSENSITIVE\n" \
42                   "\n",
43                   "dn: @INDEXLIST\n" \
44                   "@IDXATTR: gidNumber\n" \
45                   "@IDXATTR: ntName\n" \
46                   "@IDXATTR: member\n" };
47         const char *db_path, *tdb_path;
48         int ret;
49         int flags = 0;
50
51         if (ldb != NULL) {
52                 return True;
53         }
54
55         /* this is needed as Samba3 doesn't have this globally yet */
56         ldb_global_init();
57
58         db_path = state_path("group_mapping.ldb");
59
60         ldb = ldb_init(NULL);
61         if (ldb == NULL) goto failed;
62
63         existed = file_exist(db_path, NULL);
64
65         if (lp_parm_bool(-1, "groupmap", "nosync", False)) {
66                 flags |= LDB_FLG_NOSYNC;
67         }
68
69         if (!lp_use_mmap()) {
70                 flags |= LDB_FLG_NOMMAP;
71         }
72
73         ret = ldb_connect(ldb, db_path, flags, NULL);
74         if (ret != LDB_SUCCESS) {
75                 goto failed;
76         }
77         
78         if (!existed) {
79                 /* initialise the ldb with an index */
80                 struct ldb_ldif *ldif;
81                 int i;
82                 for (i=0;i<ARRAY_SIZE(init_ldif);i++) {
83                         ldif = ldb_ldif_read_string(ldb, &init_ldif[i]);
84                         if (ldif == NULL) goto failed;
85                         ret = ldb_add(ldb, ldif->msg);
86                         talloc_free(ldif);
87                         if (ret == -1) goto failed;
88                 }
89         }
90
91         /* possibly upgrade */
92         tdb_path = state_path("group_mapping.tdb");
93         if (file_exist(tdb_path, NULL) && !mapping_upgrade(tdb_path)) {
94                 unlink(state_path("group_mapping.ldb"));
95                 goto failed;
96         }
97
98         return True;
99
100 failed:
101         DEBUG(0,("Failed to open group mapping ldb '%s' - '%s'\n",
102                  db_path, ldb?ldb_errstring(ldb):strerror(errno)));
103         talloc_free(ldb);
104         ldb = NULL;
105         return False;
106 }
107
108
109 /*
110   form the DN for a mapping entry from a SID
111  */
112 static struct ldb_dn *mapping_dn(TALLOC_CTX *mem_ctx, const DOM_SID *sid)
113 {
114         fstring string_sid;
115         uint32_t rid;
116         DOM_SID domsid;
117
118         sid_copy(&domsid, sid);
119         if (!sid_split_rid(&domsid, &rid)) {
120                 return NULL;
121         }
122         if (!sid_to_fstring(string_sid, &domsid)) {
123                 return NULL;
124         }
125         /* we split by domain and rid so we can do a subtree search
126            when we only want one domain */
127         return ldb_dn_string_compose(mem_ctx, NULL, "rid=%u,domain=%s", 
128                                      rid, string_sid);
129 }
130
131 /*
132   add a group mapping entry
133  */
134 static bool add_mapping_entry(GROUP_MAP *map, int flag)
135 {
136         struct ldb_message *msg;        
137         int ret, i;
138         fstring string_sid;
139
140         msg = ldb_msg_new(ldb);
141         if (msg == NULL) {
142                 return False;
143         }
144
145         msg->dn = mapping_dn(msg, &map->sid);
146         if (msg->dn == NULL) {
147                 goto failed;
148         }
149
150         if (ldb_msg_add_string(msg, "objectClass", "groupMap") != LDB_SUCCESS ||
151             ldb_msg_add_string(msg, "sid", 
152                                sid_to_fstring(string_sid, &map->sid)) != LDB_SUCCESS ||
153             ldb_msg_add_fmt(msg, "gidNumber", "%u", (unsigned)map->gid) != LDB_SUCCESS ||
154             ldb_msg_add_fmt(msg, "sidNameUse", "%u", (unsigned)map->sid_name_use) != LDB_SUCCESS ||
155             ldb_msg_add_string(msg, "comment", map->comment) != LDB_SUCCESS ||
156             ldb_msg_add_string(msg, "ntName", map->nt_name) != LDB_SUCCESS) {
157                 goto failed;
158         }
159
160         ret = ldb_add(ldb, msg);
161
162         /* if it exists we update it. This is a hangover from the semantics the
163            tdb backend had */
164         if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {
165                 for (i=0;i<msg->num_elements;i++) {
166                         msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
167                 }
168                 ret = ldb_modify(ldb, msg);
169         }
170
171         talloc_free(msg);
172
173         return ret == LDB_SUCCESS;
174
175 failed:
176         talloc_free(msg);
177         return False;
178 }
179
180 /*
181   unpack a ldb message into a GROUP_MAP structure
182 */
183 static bool msg_to_group_map(struct ldb_message *msg, GROUP_MAP *map)
184 {
185         const char *sidstr;
186
187         map->gid          = ldb_msg_find_attr_as_int(msg, "gidNumber", -1);
188         map->sid_name_use = ldb_msg_find_attr_as_int(msg, "sidNameUse", -1);
189         fstrcpy(map->nt_name, ldb_msg_find_attr_as_string(msg, "ntName", NULL));
190         fstrcpy(map->comment, ldb_msg_find_attr_as_string(msg, "comment", NULL));
191         sidstr = ldb_msg_find_attr_as_string(msg, "sid", NULL);
192
193         if (!string_to_sid(&map->sid, sidstr) ||
194             map->gid == (gid_t)-1 ||
195             map->sid_name_use == (enum lsa_SidType)-1) {
196                 DEBUG(0,("Unable to unpack group mapping\n"));
197                 return False;
198         }
199
200         return True;
201 }
202
203 /*
204  return a group map entry for a given sid
205 */
206 static bool get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
207 {
208         int ret;
209         struct ldb_dn *dn;
210         struct ldb_result *res=NULL;
211         
212         dn = mapping_dn(ldb, &sid);
213         if (dn == NULL) goto failed;
214
215         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res);
216         talloc_steal(dn, res);
217         if (ret != LDB_SUCCESS || res->count != 1) {
218                 goto failed;
219         }
220
221         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
222
223         talloc_free(dn);
224         return True;
225
226 failed:
227         talloc_free(dn);
228         return False;
229 }
230
231 /*
232  return a group map entry for a given gid
233 */
234 static bool get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
235 {
236         int ret;
237         char *expr;
238         struct ldb_result *res=NULL;
239
240         expr = talloc_asprintf(ldb, "(&(gidNumber=%u)(objectClass=groupMap))", 
241                                (unsigned)gid);
242         if (expr == NULL) goto failed;
243
244         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res);
245         talloc_steal(expr, res);
246         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
247         
248         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
249
250         talloc_free(expr);
251         return True;
252
253 failed:
254         talloc_free(expr);
255         return False;
256 }
257
258 /*
259   Return the sid and the type of the unix group.
260 */
261 static bool get_group_map_from_ntname(const char *name, GROUP_MAP *map)
262 {
263         int ret;
264         char *expr;
265         struct ldb_result *res=NULL;
266
267         expr = talloc_asprintf(ldb, "(&(ntName=%s)(objectClass=groupMap))", name);
268         if (expr == NULL) goto failed;
269
270         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res);
271         talloc_steal(expr, res);
272         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
273         
274         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
275
276         talloc_free(expr);
277         return True;
278
279 failed:
280         talloc_free(expr);
281         return False;
282 }
283
284 /*
285  Remove a group mapping entry.
286 */
287 static bool group_map_remove(const DOM_SID *sid)
288 {
289         struct ldb_dn *dn;
290         int ret;
291         
292         dn = mapping_dn(ldb, sid);
293         if (dn == NULL) {
294                 return False;
295         }
296         ret = ldb_delete(ldb, dn);
297         talloc_free(dn);
298
299         return ret == LDB_SUCCESS;
300 }
301
302
303 /*
304   Enumerate the group mappings for a domain
305 */
306 static bool enum_group_mapping(const DOM_SID *domsid, enum lsa_SidType sid_name_use, 
307                                GROUP_MAP **pp_rmap,
308                                size_t *p_num_entries, bool unix_only)
309 {
310         int i, ret;
311         char *expr;
312         fstring name;
313         struct ldb_result *res = NULL;
314         struct ldb_dn *basedn=NULL;
315         TALLOC_CTX *tmp_ctx;
316
317         tmp_ctx = talloc_new(ldb);
318         if (tmp_ctx == NULL) goto failed;
319
320         if (sid_name_use == SID_NAME_UNKNOWN) {
321                 expr = talloc_asprintf(tmp_ctx, "(&(objectClass=groupMap))");
322         } else {
323                 expr = talloc_asprintf(tmp_ctx, "(&(sidNameUse=%u)(objectClass=groupMap))",
324                                        sid_name_use);
325         }
326         if (expr == NULL) goto failed;
327
328         /* we do a subtree search on the domain */
329         if (domsid != NULL) {
330                 sid_to_fstring(name, domsid);
331                 basedn = ldb_dn_string_compose(tmp_ctx, NULL, "domain=%s", name);
332                 if (basedn == NULL) goto failed;
333         }
334
335         ret = ldb_search(ldb, basedn, LDB_SCOPE_SUBTREE, expr, NULL, &res);
336         talloc_steal(tmp_ctx, res);
337         if (ret != LDB_SUCCESS) goto failed;
338
339         (*pp_rmap) = NULL;
340         *p_num_entries = 0;
341
342         for (i=0;i<res->count;i++) {
343                 (*pp_rmap) = SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, 
344                                                (*p_num_entries)+1);
345                 if (!(*pp_rmap)) goto failed;
346
347                 if (!msg_to_group_map(res->msgs[i], &(*pp_rmap)[*p_num_entries])) {
348                         goto failed;
349                 }
350
351                 (*p_num_entries)++;
352         }
353
354         talloc_free(tmp_ctx);
355         return True;
356
357 failed:
358         talloc_free(tmp_ctx);
359         return False;   
360 }
361
362 /* 
363    This operation happens on session setup, so it should better be fast. We
364    store a list of aliases a SID is member of hanging off MEMBEROF/SID. 
365 */
366 static NTSTATUS one_alias_membership(const DOM_SID *member,
367                                      DOM_SID **sids, size_t *num)
368 {
369         const char *attrs[] = {
370                 "sid",
371                 NULL
372         };
373         DOM_SID alias;
374         char *expr;
375         int ret, i;
376         struct ldb_result *res=NULL;
377         fstring string_sid;
378         NTSTATUS status = NT_STATUS_INTERNAL_DB_CORRUPTION;
379
380         if (!sid_to_fstring(string_sid, member)) {
381                 return NT_STATUS_INVALID_PARAMETER;
382         }
383
384         expr = talloc_asprintf(ldb, "(&(member=%s)(objectClass=groupMap))", 
385                                string_sid);
386         if (expr == NULL) goto failed;
387
388         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, attrs, &res);
389         talloc_steal(expr, res);
390         if (ret != LDB_SUCCESS) {
391                 goto failed;
392         }
393
394         for (i=0;i<res->count;i++) {
395                 struct ldb_message_element *el;
396                 el = ldb_msg_find_element(res->msgs[i], "sid");
397                 if (el == NULL || el->num_values != 1) {
398                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
399                         goto failed;
400                 }
401                 string_to_sid(&alias, (char *)el->values[0].data);
402                 status = add_sid_to_array_unique(NULL, &alias, sids, num);
403                 if (!NT_STATUS_IS_OK(status)) {
404                         goto failed;
405                 }
406         }
407
408         talloc_free(expr);
409         return NT_STATUS_OK;
410
411 failed:
412         talloc_free(expr);
413         return status;
414 }
415
416 /*
417   add/remove a member field
418 */
419 static NTSTATUS modify_aliasmem(const DOM_SID *alias, const DOM_SID *member,
420                                 int operation)
421 {
422         fstring string_sid;
423         int ret;
424         struct ldb_message msg;
425         struct ldb_message_element el;
426         struct ldb_val val;
427         TALLOC_CTX *tmp_ctx;
428         GROUP_MAP map;
429
430         if (!get_group_map_from_sid(*alias, &map)) {
431                 sid_to_fstring(string_sid, alias);
432                 return NT_STATUS_NO_SUCH_ALIAS;
433         }
434
435         if ((map.sid_name_use != SID_NAME_ALIAS) &&
436             (map.sid_name_use != SID_NAME_WKN_GRP)) {
437                 DEBUG(0,("sid_name_use=%d\n", map.sid_name_use));
438                 return NT_STATUS_NO_SUCH_ALIAS;
439         }
440
441         tmp_ctx = talloc_new(NULL);
442         if (tmp_ctx == NULL) {
443                 return NT_STATUS_NO_MEMORY;
444         }
445
446         msg.dn = mapping_dn(tmp_ctx, alias);
447         if (msg.dn == NULL) {
448                 return NT_STATUS_NO_MEMORY;
449         }
450         msg.num_elements = 1;
451         msg.elements = &el;
452         el.flags = operation;
453         el.name = talloc_strdup(tmp_ctx, "member");
454         el.num_values = 1;
455         el.values = &val;
456         sid_to_fstring(string_sid, member);
457         val.data = (uint8_t *)string_sid;
458         val.length = strlen(string_sid);
459
460         ret = ldb_modify(ldb, &msg);
461         talloc_free(tmp_ctx);
462
463         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
464                 return NT_STATUS_NO_SUCH_ALIAS;
465         }
466
467         if (operation == LDB_FLAG_MOD_ADD &&
468             ret == LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
469                 return NT_STATUS_MEMBER_IN_ALIAS;
470         }
471
472         return (ret == LDB_SUCCESS ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
473 }
474
475 static NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
476 {
477         return modify_aliasmem(alias, member, LDB_FLAG_MOD_ADD);
478 }
479
480 static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
481 {
482         return modify_aliasmem(alias, member, LDB_FLAG_MOD_DELETE);
483 }
484
485
486 /*
487   enumerate sids that have the given alias set in member
488 */
489 static NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
490 {
491         const char *attrs[] = {
492                 "member",
493                 NULL
494         };
495         int ret, i;
496         NTSTATUS status = NT_STATUS_OK;
497         struct ldb_result *res=NULL;
498         struct ldb_dn *dn;
499         struct ldb_message_element *el;
500         
501         *sids = NULL;
502         *num = 0;
503
504         dn = mapping_dn(ldb, alias);
505         if (dn == NULL) {
506                 return NT_STATUS_NO_MEMORY;
507         }
508
509         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, attrs, &res);
510         talloc_steal(dn, res);
511         if (ret == LDB_SUCCESS && res->count == 0) {
512                 talloc_free(dn);
513                 return NT_STATUS_OK;
514         }
515         if (ret != LDB_SUCCESS) {
516                 talloc_free(dn);
517                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
518         }
519
520         el = ldb_msg_find_element(res->msgs[0], "member");
521         if (el == NULL) {
522                 talloc_free(dn);
523                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
524         }
525         
526         for (i=0;i<el->num_values;i++) {
527                 DOM_SID sid;
528                 string_to_sid(&sid, (const char *)el->values[i].data);
529                 status = add_sid_to_array_unique(NULL, &sid, sids, num);
530                 if (!NT_STATUS_IS_OK(status)) {
531                         goto done;
532                 }
533         }
534
535 done:
536         talloc_free(dn);
537         return status;
538 }
539
540 /*
541   upgrade one group mapping record from the old tdb format
542 */
543 static int upgrade_map_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
544                               TDB_DATA data, void *state)
545 {
546         int ret;
547         GROUP_MAP map;
548
549         if (strncmp((char *)key.dptr, GROUP_PREFIX, 
550                     MIN(key.dsize, strlen(GROUP_PREFIX))) != 0) {
551                 return 0;
552         }
553
554         if (!string_to_sid(&map.sid, strlen(GROUP_PREFIX) + (const char *)key.dptr)) {
555                 DEBUG(0,("Bad sid key '%s' during upgrade\n", (const char *)key.dptr));
556                 *(int *)state = -1;
557                 return -1;
558         }
559
560         ret = tdb_unpack(data.dptr, data.dsize, "ddff",
561                          &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
562         if (ret == -1) {
563                 DEBUG(0,("Failed to unpack group map record during upgrade\n"));
564                 *(int *)state = -1;
565                 return -1;
566         }
567
568         if (!add_mapping_entry(&map, 0)) {
569                 DEBUG(0,("Failed to add mapping entry during upgrade\n"));
570                 *(int *)state = -1;
571                 return -1;
572         }
573
574         return 0;
575 }
576
577 /*
578   upgrade one alias record from the old tdb format
579 */
580 static int upgrade_alias_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
581                                 TDB_DATA data, void *state)
582 {
583         const char *p = (const char *)data.dptr;
584         char *string_sid;
585         DOM_SID member;
586         TALLOC_CTX *frame;
587
588         if (strncmp((char *)key.dptr, MEMBEROF_PREFIX, 
589                     MIN(key.dsize, strlen(MEMBEROF_PREFIX))) != 0) {
590                 return 0;
591         }
592
593         if (!string_to_sid(&member, strlen(MEMBEROF_PREFIX) + (const char *)key.dptr)) {
594                 DEBUG(0,("Bad alias key %s during upgrade\n",
595                          (const char *)key.dptr));
596                 *(int *)state = -1;
597         }
598
599         frame = talloc_stackframe();
600         while (next_token_talloc(frame,&p, &string_sid, " ")) {
601                 DOM_SID alias;
602                 NTSTATUS status;
603                 string_to_sid(&alias, string_sid);
604                 status = add_aliasmem(&alias, &member);
605                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_ALIAS)) {
606                         DEBUG(0,("Ignoring orphaned alias record '%s'\n", 
607                                  string_sid));
608                 } else if (!NT_STATUS_IS_OK(status)) {
609                         DEBUG(0,("Failed to add alias member during upgrade - %s\n",
610                                  nt_errstr(status)));
611                         *(int *)state = -1;
612                         TALLOC_FREE(frame);
613                         return -1;
614                 }
615         }
616         TALLOC_FREE(frame);
617         return 0;
618 }
619
620 /*
621   upgrade from a old style tdb
622 */
623 static bool mapping_upgrade(const char *tdb_path)
624 {
625         static TDB_CONTEXT *tdb;
626         int ret, status=0;
627
628         tdb = tdb_open_log(tdb_path, 0, TDB_DEFAULT, O_RDWR, 0600);
629         if (tdb == NULL) goto failed;
630
631         /* we have to do the map records first, as alias records may
632            reference them */
633         ret = tdb_traverse(tdb, upgrade_map_record, &status);
634         if (ret == -1 || status == -1) goto failed;
635
636         ret = tdb_traverse(tdb, upgrade_alias_record, &status);
637         if (ret == -1 || status == -1) goto failed;
638
639         if (tdb) {
640                 tdb_close(tdb);
641                 tdb = NULL;
642         }
643
644         {
645                 const char *old_path = tdb_path;
646                 char *new_path = state_path("group_mapping.tdb.upgraded");
647
648                 if (!new_path) {
649                         goto failed;
650                 }
651                 if (rename(old_path, new_path) != 0) {
652                         DEBUG(0,("Failed to rename old group mapping database\n"));
653                         goto failed;
654                 }
655         }
656         return True;
657
658 failed:
659         DEBUG(0,("Failed to upgrade group mapping database\n"));
660         if (tdb) tdb_close(tdb);
661         return False;
662 }
663
664
665
666 static const struct mapping_backend ldb_backend = {
667         .add_mapping_entry         = add_mapping_entry,
668         .get_group_map_from_sid    = get_group_map_from_sid,
669         .get_group_map_from_gid    = get_group_map_from_gid,
670         .get_group_map_from_ntname = get_group_map_from_ntname,
671         .group_map_remove          = group_map_remove,
672         .enum_group_mapping        = enum_group_mapping,
673         .one_alias_membership      = one_alias_membership,
674         .add_aliasmem              = add_aliasmem,
675         .del_aliasmem              = del_aliasmem,
676         .enum_aliasmem             = enum_aliasmem      
677 };
678
679 /*
680   initialise the ldb mapping backend
681  */
682 const struct mapping_backend *groupdb_ldb_init(void)
683 {
684         if (!init_group_mapping()) {
685                 DEBUG(0,("Failed to initialise ldb mapping backend\n"));
686                 return NULL;
687         }
688
689         return &ldb_backend;
690 }