21da363a530174f1a37a08352560bb2087fe8a7b
[kai/samba.git] / source / 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, write to the Free Software
22  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  */
24
25 #include "includes.h"
26 #include "groupdb/mapping.h"
27 #include "lib/ldb/include/includes.h"
28 #include "lib/ldb/include/ldb_errors.h"
29
30 static struct ldb_context *ldb;
31
32 static BOOL mapping_upgrade(const char *tdb_path);
33
34 /*
35   connect to the group mapping ldb
36 */
37 static BOOL init_group_mapping(void)
38 {
39         BOOL existed;
40         const char *init_ldif[] = 
41                 { "dn: @ATTRIBUTES\n" \
42                   "ntName: CASE_INSENSITIVE\n" \
43                   "\n",
44                   "dn: @INDEXLIST\n" \
45                   "@IDXATTR: gidNumber\n" \
46                   "@IDXATTR: ntName\n" \
47                   "@IDXATTR: member\n" };
48         const char *db_path, *tdb_path;
49         int ret;
50         int flags = 0;
51
52         if (ldb != NULL) {
53                 return True;
54         }
55
56         /* this is needed as Samba3 doesn't have this globally yet */
57         ldb_global_init();
58
59         db_path = lock_path("group_mapping.ldb");
60
61         ldb = ldb_init(NULL);
62         if (ldb == NULL) goto failed;
63
64         existed = file_exist(db_path, NULL);
65
66         if (lp_parm_bool(-1, "groupmap", "nosync", False)) {
67                 flags |= LDB_FLG_NOSYNC;
68         }
69
70         if (!lp_use_mmap()) {
71                 flags |= LDB_FLG_NOMMAP;
72         }
73
74         ret = ldb_connect(ldb, db_path, flags, NULL);
75         if (ret != LDB_SUCCESS) {
76                 goto failed;
77         }
78         
79         if (!existed) {
80                 /* initialise the ldb with an index */
81                 struct ldb_ldif *ldif;
82                 int i;
83                 for (i=0;i<ARRAY_SIZE(init_ldif);i++) {
84                         ldif = ldb_ldif_read_string(ldb, &init_ldif[i]);
85                         if (ldif == NULL) goto failed;
86                         ret = ldb_add(ldb, ldif->msg);
87                         talloc_free(ldif);
88                         if (ret == -1) goto failed;
89                 }
90         }
91
92         /* possibly upgrade */
93         tdb_path = lock_path("group_mapping.tdb");
94         if (file_exist(tdb_path, NULL) && !mapping_upgrade(tdb_path)) {
95                 unlink(lock_path("group_mapping.ldb"));
96                 goto failed;
97         }
98
99         return True;
100
101 failed:
102         DEBUG(0,("Failed to open group mapping ldb '%s' - '%s'\n",
103                  db_path, ldb?ldb_errstring(ldb):strerror(errno)));
104         talloc_free(ldb);
105         ldb = NULL;
106         return False;
107 }
108
109
110 /*
111   form the DN for a mapping entry from a SID
112  */
113 static struct ldb_dn *mapping_dn(TALLOC_CTX *mem_ctx, const DOM_SID *sid)
114 {
115         fstring string_sid;
116         uint32_t rid;
117         DOM_SID domsid;
118
119         sid_copy(&domsid, sid);
120         if (!sid_split_rid(&domsid, &rid)) {
121                 return NULL;
122         }
123         if (!sid_to_string(string_sid, &domsid)) {
124                 return NULL;
125         }
126         /* we split by domain and rid so we can do a subtree search
127            when we only want one domain */
128         return ldb_dn_string_compose(mem_ctx, NULL, "rid=%u,domain=%s", 
129                                      rid, string_sid);
130 }
131
132 /*
133   add a group mapping entry
134  */
135 static BOOL add_mapping_entry(GROUP_MAP *map, int flag)
136 {
137         struct ldb_message *msg;        
138         int ret, i;
139         fstring string_sid;
140
141         msg = ldb_msg_new(ldb);
142         if (msg == NULL) {
143                 return False;
144         }
145
146         msg->dn = mapping_dn(msg, &map->sid);
147         if (msg->dn == NULL) {
148                 goto failed;
149         }
150
151         if (ldb_msg_add_string(msg, "objectClass", "groupMap") != LDB_SUCCESS ||
152             ldb_msg_add_string(msg, "sid", 
153                                sid_to_string(string_sid, &map->sid)) != LDB_SUCCESS ||
154             ldb_msg_add_fmt(msg, "gidNumber", "%u", (unsigned)map->gid) != LDB_SUCCESS ||
155             ldb_msg_add_fmt(msg, "sidNameUse", "%u", (unsigned)map->sid_name_use) != LDB_SUCCESS ||
156             ldb_msg_add_string(msg, "comment", map->comment) != LDB_SUCCESS ||
157             ldb_msg_add_string(msg, "ntName", map->nt_name) != LDB_SUCCESS) {
158                 goto failed;
159         }
160
161         ret = ldb_add(ldb, msg);
162
163         /* if it exists we update it. This is a hangover from the semantics the
164            tdb backend had */
165         if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {
166                 for (i=0;i<msg->num_elements;i++) {
167                         msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
168                 }
169                 ret = ldb_modify(ldb, msg);
170         }
171
172         talloc_free(msg);
173
174         return ret == LDB_SUCCESS;
175
176 failed:
177         talloc_free(msg);
178         return False;
179 }
180
181 /*
182   unpack a ldb message into a GROUP_MAP structure
183 */
184 static BOOL msg_to_group_map(struct ldb_message *msg, GROUP_MAP *map)
185 {
186         const char *sidstr;
187
188         map->gid          = ldb_msg_find_attr_as_int(msg, "gidNumber", -1);
189         map->sid_name_use = ldb_msg_find_attr_as_int(msg, "sidNameUse", -1);
190         fstrcpy(map->nt_name, ldb_msg_find_attr_as_string(msg, "ntName", NULL));
191         fstrcpy(map->comment, ldb_msg_find_attr_as_string(msg, "comment", NULL));
192         sidstr = ldb_msg_find_attr_as_string(msg, "sid", NULL);
193
194         if (!string_to_sid(&map->sid, sidstr) ||
195             map->gid == (gid_t)-1 ||
196             map->sid_name_use == (enum lsa_SidType)-1) {
197                 DEBUG(0,("Unable to unpack group mapping\n"));
198                 return False;
199         }
200
201         return True;
202 }
203
204 /*
205  return a group map entry for a given sid
206 */
207 static BOOL get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
208 {
209         int ret;
210         struct ldb_dn *dn;
211         struct ldb_result *res=NULL;
212         
213         dn = mapping_dn(ldb, &sid);
214         if (dn == NULL) goto failed;
215
216         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res);
217         talloc_steal(dn, res);
218         if (ret != LDB_SUCCESS || res->count != 1) {
219                 goto failed;
220         }
221
222         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
223
224         talloc_free(dn);
225         return True;
226
227 failed:
228         talloc_free(dn);
229         return False;
230 }
231
232 /*
233  return a group map entry for a given gid
234 */
235 static BOOL get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
236 {
237         int ret;
238         char *expr;
239         struct ldb_result *res=NULL;
240
241         expr = talloc_asprintf(ldb, "(&(gidNumber=%u)(objectClass=groupMap))", 
242                                (unsigned)gid);
243         if (expr == NULL) goto failed;
244
245         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res);
246         talloc_steal(expr, res);
247         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
248         
249         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
250
251         talloc_free(expr);
252         return True;
253
254 failed:
255         talloc_free(expr);
256         return False;
257 }
258
259 /*
260   Return the sid and the type of the unix group.
261 */
262 static BOOL get_group_map_from_ntname(const char *name, GROUP_MAP *map)
263 {
264         int ret;
265         char *expr;
266         struct ldb_result *res=NULL;
267
268         expr = talloc_asprintf(ldb, "(&(ntName=%s)(objectClass=groupMap))", name);
269         if (expr == NULL) goto failed;
270
271         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res);
272         talloc_steal(expr, res);
273         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
274         
275         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
276
277         talloc_free(expr);
278         return True;
279
280 failed:
281         talloc_free(expr);
282         return False;
283 }
284
285 /*
286  Remove a group mapping entry.
287 */
288 static BOOL group_map_remove(const DOM_SID *sid)
289 {
290         struct ldb_dn *dn;
291         int ret;
292         
293         dn = mapping_dn(ldb, sid);
294         if (dn == NULL) {
295                 return False;
296         }
297         ret = ldb_delete(ldb, dn);
298         talloc_free(dn);
299
300         return ret == LDB_SUCCESS;
301 }
302
303
304 /*
305   Enumerate the group mappings for a domain
306 */
307 static BOOL enum_group_mapping(const DOM_SID *domsid, enum lsa_SidType sid_name_use, 
308                                GROUP_MAP **pp_rmap,
309                                size_t *p_num_entries, BOOL unix_only)
310 {
311         int i, ret;
312         char *expr;
313         fstring name;
314         struct ldb_result *res;
315         struct ldb_dn *basedn=NULL;
316         TALLOC_CTX *tmp_ctx;
317
318         tmp_ctx = talloc_new(ldb);
319         if (tmp_ctx == NULL) goto failed;
320
321         if (sid_name_use == SID_NAME_UNKNOWN) {
322                 expr = talloc_asprintf(tmp_ctx, "(&(objectClass=groupMap))");
323         } else {
324                 expr = talloc_asprintf(tmp_ctx, "(&(sidNameUse=%u)(objectClass=groupMap))",
325                                        sid_name_use);
326         }
327         if (expr == NULL) goto failed;
328
329         /* we do a subtree search on the domain */
330         if (domsid != NULL) {
331                 sid_to_string(name, domsid);
332                 basedn = ldb_dn_string_compose(tmp_ctx, NULL, "domain=%s", name);
333                 if (basedn == NULL) goto failed;
334         }
335
336         ret = ldb_search(ldb, basedn, LDB_SCOPE_SUBTREE, expr, NULL, &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_string(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                 if (!add_sid_to_array_unique(NULL, &alias, sids, num)) {
403                         status = NT_STATUS_NO_MEMORY;
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_string(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_string(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         struct ldb_result *res=NULL;
497         struct ldb_dn *dn;
498         struct ldb_message_element *el;
499         
500         *sids = NULL;
501         *num = 0;
502
503         dn = mapping_dn(ldb, alias);
504         if (dn == NULL) {
505                 return NT_STATUS_NO_MEMORY;
506         }
507
508         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, attrs, &res);
509         talloc_steal(dn, res);
510         if (ret == LDB_SUCCESS && res->count == 0) {
511                 talloc_free(dn);
512                 return NT_STATUS_OK;
513         }
514         if (ret != LDB_SUCCESS) {
515                 talloc_free(dn);
516                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
517         }
518
519         el = ldb_msg_find_element(res->msgs[0], "member");
520         if (el == NULL) {
521                 talloc_free(dn);
522                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
523         }
524         
525         for (i=0;i<el->num_values;i++) {
526                 DOM_SID sid;
527                 string_to_sid(&sid, (const char *)el->values[i].data);
528                 if (!add_sid_to_array_unique(NULL, &sid, sids, num)) {
529                         talloc_free(dn);
530                         return NT_STATUS_NO_MEMORY;
531                 }
532         }
533         talloc_free(dn);
534
535         return NT_STATUS_OK;
536 }
537
538 /*
539   upgrade one group mapping record from the old tdb format
540 */
541 static int upgrade_map_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
542                               TDB_DATA data, void *state)
543 {
544         int ret;
545         GROUP_MAP map;
546
547         if (strncmp((char *)key.dptr, GROUP_PREFIX, 
548                     MIN(key.dsize, strlen(GROUP_PREFIX))) != 0) {
549                 return 0;
550         }
551
552         if (!string_to_sid(&map.sid, strlen(GROUP_PREFIX) + (const char *)key.dptr)) {
553                 DEBUG(0,("Bad sid key '%s' during upgrade\n", (const char *)key.dptr));
554                 *(int *)state = -1;
555                 return -1;
556         }
557
558         ret = tdb_unpack(data.dptr, data.dsize, "ddff",
559                          &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
560         if (ret == -1) {
561                 DEBUG(0,("Failed to unpack group map record during upgrade\n"));
562                 *(int *)state = -1;
563                 return -1;
564         }
565
566         if (!add_mapping_entry(&map, 0)) {
567                 DEBUG(0,("Failed to add mapping entry during upgrade\n"));
568                 *(int *)state = -1;
569                 return -1;
570         }
571
572         return 0;
573 }
574
575 /*
576   upgrade one alias record from the old tdb format
577 */
578 static int upgrade_alias_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
579                                 TDB_DATA data, void *state)
580 {
581         const char *p = (const char *)data.dptr;
582         fstring string_sid;
583         DOM_SID member;
584
585         if (strncmp((char *)key.dptr, MEMBEROF_PREFIX, 
586                     MIN(key.dsize, strlen(MEMBEROF_PREFIX))) != 0) {
587                 return 0;
588         }
589
590         if (!string_to_sid(&member, strlen(MEMBEROF_PREFIX) + (const char *)key.dptr)) {
591                 DEBUG(0,("Bad alias key %s during upgrade\n",
592                          (const char *)key.dptr));
593                 *(int *)state = -1;
594         }
595
596         while (next_token(&p, string_sid, " ", sizeof(string_sid))) {
597                 DOM_SID alias;
598                 NTSTATUS status;
599                 string_to_sid(&alias, string_sid);
600                 status = add_aliasmem(&alias, &member);
601                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_ALIAS)) {
602                         DEBUG(0,("Ignoring orphaned alias record '%s'\n", 
603                                  string_sid));
604                 } else if (!NT_STATUS_IS_OK(status)) {
605                         DEBUG(0,("Failed to add alias member during upgrade - %s\n",
606                                  nt_errstr(status)));
607                         *(int *)state = -1;
608                         return -1;
609                 }
610         }
611
612         return 0;
613 }
614
615 /*
616   upgrade from a old style tdb
617 */
618 static BOOL mapping_upgrade(const char *tdb_path)
619 {
620         static TDB_CONTEXT *tdb;
621         int ret, status=0;
622         pstring old_path;
623         pstring new_path;
624
625         tdb = tdb_open_log(tdb_path, 0, TDB_DEFAULT, O_RDWR, 0600);
626         if (tdb == NULL) goto failed;
627
628         /* we have to do the map records first, as alias records may
629            reference them */
630         ret = tdb_traverse(tdb, upgrade_map_record, &status);
631         if (ret == -1 || status == -1) goto failed;
632
633         ret = tdb_traverse(tdb, upgrade_alias_record, &status);
634         if (ret == -1 || status == -1) goto failed;
635
636         if (tdb) {
637                 tdb_close(tdb);
638                 tdb = NULL;
639         }
640
641         pstrcpy(old_path, tdb_path);
642         pstrcpy(new_path, lock_path("group_mapping.tdb.upgraded"));
643
644         if (rename(old_path, new_path) != 0) {
645                 DEBUG(0,("Failed to rename old group mapping database\n"));
646                 goto failed;
647         }
648         return True;
649
650 failed:
651         DEBUG(0,("Failed to upgrade group mapping database\n"));
652         if (tdb) tdb_close(tdb);
653         return False;
654 }
655
656
657
658 static const struct mapping_backend ldb_backend = {
659         .add_mapping_entry         = add_mapping_entry,
660         .get_group_map_from_sid    = get_group_map_from_sid,
661         .get_group_map_from_gid    = get_group_map_from_gid,
662         .get_group_map_from_ntname = get_group_map_from_ntname,
663         .group_map_remove          = group_map_remove,
664         .enum_group_mapping        = enum_group_mapping,
665         .one_alias_membership      = one_alias_membership,
666         .add_aliasmem              = add_aliasmem,
667         .del_aliasmem              = del_aliasmem,
668         .enum_aliasmem             = enum_aliasmem      
669 };
670
671 /*
672   initialise the ldb mapping backend
673  */
674 const struct mapping_backend *groupdb_ldb_init(void)
675 {
676         if (!init_group_mapping()) {
677                 DEBUG(0,("Failed to initialise ldb mapping backend\n"));
678                 return NULL;
679         }
680
681         return &ldb_backend;
682 }