Merge branch 'master' of ssh://git.samba.org/data/git/samba
[jra/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         /* Ensure this db is created read/write for root only. */
64         ldb_set_create_perms(ldb, 0600);
65
66         existed = file_exist(db_path);
67
68         if (lp_parm_bool(-1, "groupmap", "nosync", False)) {
69                 flags |= LDB_FLG_NOSYNC;
70         }
71
72         if (!lp_use_mmap()) {
73                 flags |= LDB_FLG_NOMMAP;
74         }
75
76         ret = ldb_connect(ldb, db_path, flags, NULL);
77         if (ret != LDB_SUCCESS) {
78                 goto failed;
79         }
80
81         /* force the permissions on the ldb to 0600 - this will fix
82            existing databases as well as new ones */
83         if (chmod(db_path, 0600) != 0) {
84                 goto failed;
85         }
86
87         if (!existed) {
88                 /* initialise the ldb with an index */
89                 struct ldb_ldif *ldif;
90                 int i;
91                 for (i=0;i<ARRAY_SIZE(init_ldif);i++) {
92                         ldif = ldb_ldif_read_string(ldb, &init_ldif[i]);
93                         if (ldif == NULL) goto failed;
94                         ret = ldb_add(ldb, ldif->msg);
95                         talloc_free(ldif);
96                         if (ret == -1) goto failed;
97                 }
98         }
99
100         /* possibly upgrade */
101         tdb_path = state_path("group_mapping.tdb");
102         if (file_exist(tdb_path) && !mapping_upgrade(tdb_path)) {
103                 unlink(state_path("group_mapping.ldb"));
104                 goto failed;
105         }
106
107         return True;
108
109 failed:
110         DEBUG(0,("Failed to open group mapping ldb '%s' - '%s'\n",
111                  db_path, ldb?ldb_errstring(ldb):strerror(errno)));
112         talloc_free(ldb);
113         ldb = NULL;
114         return False;
115 }
116
117
118 /*
119   form the DN for a mapping entry from a SID
120  */
121 static struct ldb_dn *mapping_dn(TALLOC_CTX *mem_ctx, const DOM_SID *sid)
122 {
123         fstring string_sid;
124         uint32_t rid;
125         DOM_SID domsid;
126
127         sid_copy(&domsid, sid);
128         if (!sid_split_rid(&domsid, &rid)) {
129                 return NULL;
130         }
131         if (!sid_to_fstring(string_sid, &domsid)) {
132                 return NULL;
133         }
134         /* we split by domain and rid so we can do a subtree search
135            when we only want one domain */
136         return ldb_dn_string_compose(mem_ctx, NULL, "rid=%u,domain=%s", 
137                                      rid, string_sid);
138 }
139
140 /*
141   add a group mapping entry
142  */
143 static bool add_mapping_entry(GROUP_MAP *map, int flag)
144 {
145         struct ldb_message *msg;        
146         int ret, i;
147         fstring string_sid;
148
149         msg = ldb_msg_new(ldb);
150         if (msg == NULL) {
151                 return False;
152         }
153
154         msg->dn = mapping_dn(msg, &map->sid);
155         if (msg->dn == NULL) {
156                 goto failed;
157         }
158
159         if (ldb_msg_add_string(msg, "objectClass", "groupMap") != LDB_SUCCESS ||
160             ldb_msg_add_string(msg, "sid", 
161                                sid_to_fstring(string_sid, &map->sid)) != LDB_SUCCESS ||
162             ldb_msg_add_fmt(msg, "gidNumber", "%u", (unsigned)map->gid) != LDB_SUCCESS ||
163             ldb_msg_add_fmt(msg, "sidNameUse", "%u", (unsigned)map->sid_name_use) != LDB_SUCCESS ||
164             ldb_msg_add_string(msg, "comment", map->comment) != LDB_SUCCESS ||
165             ldb_msg_add_string(msg, "ntName", map->nt_name) != LDB_SUCCESS) {
166                 goto failed;
167         }
168
169         ret = ldb_add(ldb, msg);
170
171         /* if it exists we update it. This is a hangover from the semantics the
172            tdb backend had */
173         if (ret == LDB_ERR_ENTRY_ALREADY_EXISTS) {
174                 for (i=0;i<msg->num_elements;i++) {
175                         msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
176                 }
177                 ret = ldb_modify(ldb, msg);
178         }
179
180         talloc_free(msg);
181
182         return ret == LDB_SUCCESS;
183
184 failed:
185         talloc_free(msg);
186         return False;
187 }
188
189 /*
190   unpack a ldb message into a GROUP_MAP structure
191 */
192 static bool msg_to_group_map(struct ldb_message *msg, GROUP_MAP *map)
193 {
194         const char *sidstr;
195
196         map->gid          = ldb_msg_find_attr_as_int(msg, "gidNumber", -1);
197         map->sid_name_use = ldb_msg_find_attr_as_int(msg, "sidNameUse", -1);
198         fstrcpy(map->nt_name, ldb_msg_find_attr_as_string(msg, "ntName", NULL));
199         fstrcpy(map->comment, ldb_msg_find_attr_as_string(msg, "comment", NULL));
200         sidstr = ldb_msg_find_attr_as_string(msg, "sid", NULL);
201
202         if (!string_to_sid(&map->sid, sidstr) ||
203             map->gid == (gid_t)-1 ||
204             map->sid_name_use == (enum lsa_SidType)-1) {
205                 DEBUG(0,("Unable to unpack group mapping\n"));
206                 return False;
207         }
208
209         return True;
210 }
211
212 /*
213  return a group map entry for a given sid
214 */
215 static bool get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
216 {
217         int ret;
218         struct ldb_dn *dn;
219         struct ldb_result *res=NULL;
220         
221         dn = mapping_dn(ldb, &sid);
222         if (dn == NULL) goto failed;
223
224         ret = ldb_search(ldb, ldb, &res, dn, LDB_SCOPE_BASE, NULL, NULL);
225         talloc_steal(dn, res);
226         if (ret != LDB_SUCCESS || res->count != 1) {
227                 goto failed;
228         }
229
230         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
231
232         talloc_free(dn);
233         return True;
234
235 failed:
236         talloc_free(dn);
237         return False;
238 }
239
240 /*
241  return a group map entry for a given gid
242 */
243 static bool get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
244 {
245         int ret;
246         struct ldb_result *res=NULL;
247
248         ret = ldb_search(ldb, ldb, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(gidNumber=%u)(objectClass=groupMap))", (unsigned)gid);
249         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
250         
251         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
252
253         return True;
254
255 failed:
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         struct ldb_result *res=NULL;
266
267         ret = ldb_search(ldb, ldb, &res, NULL, LDB_SCOPE_SUBTREE, NULL, "(&(ntName=%s)(objectClass=groupMap))", name);
268         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
269         
270         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
271
272         return True;
273
274 failed:
275         return False;
276 }
277
278 /*
279  Remove a group mapping entry.
280 */
281 static bool group_map_remove(const DOM_SID *sid)
282 {
283         struct ldb_dn *dn;
284         int ret;
285         
286         dn = mapping_dn(ldb, sid);
287         if (dn == NULL) {
288                 return False;
289         }
290         ret = ldb_delete(ldb, dn);
291         talloc_free(dn);
292
293         return ret == LDB_SUCCESS;
294 }
295
296
297 /*
298   Enumerate the group mappings for a domain
299 */
300 static bool enum_group_mapping(const DOM_SID *domsid, enum lsa_SidType sid_name_use, 
301                                GROUP_MAP **pp_rmap,
302                                size_t *p_num_entries, bool unix_only)
303 {
304         int i, ret;
305         fstring name;
306         struct ldb_result *res = NULL;
307         struct ldb_dn *basedn=NULL;
308         TALLOC_CTX *tmp_ctx;
309
310         tmp_ctx = talloc_new(ldb);
311         if (tmp_ctx == NULL) goto failed;
312
313         /* we do a subtree search on the domain */
314         if (domsid != NULL) {
315                 sid_to_fstring(name, domsid);
316                 basedn = ldb_dn_string_compose(tmp_ctx, NULL, "domain=%s", name);
317                 if (basedn == NULL) goto failed;
318         }
319
320         if (sid_name_use == SID_NAME_UNKNOWN) {
321                 ret = ldb_search(ldb, ldb, &res, basedn, LDB_SCOPE_SUBTREE, NULL, 
322                                                  "(&(objectClass=groupMap))");
323         } else {
324                 ret = ldb_search(ldb, ldb, &res, basedn, LDB_SCOPE_SUBTREE, NULL, 
325                                                  "(&(sidNameUse=%u)(objectClass=groupMap))",
326                                                  sid_name_use);
327         }
328
329         talloc_steal(tmp_ctx, res);
330         if (ret != LDB_SUCCESS) goto failed;
331
332         (*pp_rmap) = NULL;
333         *p_num_entries = 0;
334
335         for (i=0;i<res->count;i++) {
336                 (*pp_rmap) = SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, 
337                                                (*p_num_entries)+1);
338                 if (!(*pp_rmap)) goto failed;
339
340                 if (!msg_to_group_map(res->msgs[i], &(*pp_rmap)[*p_num_entries])) {
341                         goto failed;
342                 }
343
344                 (*p_num_entries)++;
345         }
346
347         talloc_free(tmp_ctx);
348         return True;
349
350 failed:
351         talloc_free(tmp_ctx);
352         return False;   
353 }
354
355 /* 
356    This operation happens on session setup, so it should better be fast. We
357    store a list of aliases a SID is member of hanging off MEMBEROF/SID. 
358 */
359 static NTSTATUS one_alias_membership(const DOM_SID *member,
360                                      DOM_SID **sids, size_t *num)
361 {
362         const char *attrs[] = {
363                 "sid",
364                 NULL
365         };
366         DOM_SID alias;
367         int ret, i;
368         struct ldb_result *res=NULL;
369         fstring string_sid;
370         NTSTATUS status = NT_STATUS_INTERNAL_DB_CORRUPTION;
371
372         if (!sid_to_fstring(string_sid, member)) {
373                 return NT_STATUS_INVALID_PARAMETER;
374         }
375
376         ret = ldb_search(ldb, ldb, &res, NULL, LDB_SCOPE_SUBTREE, attrs, "(&(member=%s)(objectClass=groupMap))", string_sid);
377         if (ret != LDB_SUCCESS) {
378                 goto failed;
379         }
380
381         for (i=0;i<res->count;i++) {
382                 struct ldb_message_element *el;
383                 el = ldb_msg_find_element(res->msgs[i], "sid");
384                 if (el == NULL || el->num_values != 1) {
385                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
386                         goto failed;
387                 }
388                 string_to_sid(&alias, (char *)el->values[0].data);
389                 status = add_sid_to_array_unique(NULL, &alias, sids, num);
390                 if (!NT_STATUS_IS_OK(status)) {
391                         goto failed;
392                 }
393         }
394
395         return NT_STATUS_OK;
396
397 failed:
398         return status;
399 }
400
401 /*
402   add/remove a member field
403 */
404 static NTSTATUS modify_aliasmem(const DOM_SID *alias, const DOM_SID *member,
405                                 int operation)
406 {
407         fstring string_sid;
408         int ret;
409         struct ldb_message msg;
410         struct ldb_message_element el;
411         struct ldb_val val;
412         TALLOC_CTX *tmp_ctx;
413         GROUP_MAP map;
414
415         if (!get_group_map_from_sid(*alias, &map)) {
416                 sid_to_fstring(string_sid, alias);
417                 return NT_STATUS_NO_SUCH_ALIAS;
418         }
419
420         if ((map.sid_name_use != SID_NAME_ALIAS) &&
421             (map.sid_name_use != SID_NAME_WKN_GRP)) {
422                 DEBUG(0,("sid_name_use=%d\n", map.sid_name_use));
423                 return NT_STATUS_NO_SUCH_ALIAS;
424         }
425
426         tmp_ctx = talloc_new(NULL);
427         if (tmp_ctx == NULL) {
428                 return NT_STATUS_NO_MEMORY;
429         }
430
431         msg.dn = mapping_dn(tmp_ctx, alias);
432         if (msg.dn == NULL) {
433                 return NT_STATUS_NO_MEMORY;
434         }
435         msg.num_elements = 1;
436         msg.elements = &el;
437         el.flags = operation;
438         el.name = talloc_strdup(tmp_ctx, "member");
439         el.num_values = 1;
440         el.values = &val;
441         sid_to_fstring(string_sid, member);
442         val.data = (uint8_t *)string_sid;
443         val.length = strlen(string_sid);
444
445         ret = ldb_modify(ldb, &msg);
446         talloc_free(tmp_ctx);
447
448         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
449                 return NT_STATUS_NO_SUCH_ALIAS;
450         }
451
452         if (operation == LDB_FLAG_MOD_ADD &&
453             ret == LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
454                 return NT_STATUS_MEMBER_IN_ALIAS;
455         }
456
457         return (ret == LDB_SUCCESS ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
458 }
459
460 static NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
461 {
462         return modify_aliasmem(alias, member, LDB_FLAG_MOD_ADD);
463 }
464
465 static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
466 {
467         return modify_aliasmem(alias, member, LDB_FLAG_MOD_DELETE);
468 }
469
470
471 /*
472   enumerate sids that have the given alias set in member
473 */
474 static NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
475 {
476         const char *attrs[] = {
477                 "member",
478                 NULL
479         };
480         int ret, i;
481         NTSTATUS status = NT_STATUS_OK;
482         struct ldb_result *res=NULL;
483         struct ldb_dn *dn;
484         struct ldb_message_element *el;
485         
486         *sids = NULL;
487         *num = 0;
488
489         dn = mapping_dn(ldb, alias);
490         if (dn == NULL) {
491                 return NT_STATUS_NO_MEMORY;
492         }
493
494         ret = ldb_search(ldb, ldb, &res, dn, LDB_SCOPE_BASE, attrs, NULL);
495         talloc_steal(dn, res);
496         if (ret == LDB_SUCCESS && res->count == 0) {
497                 talloc_free(dn);
498                 return NT_STATUS_OK;
499         }
500         if (ret != LDB_SUCCESS) {
501                 talloc_free(dn);
502                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
503         }
504
505         el = ldb_msg_find_element(res->msgs[0], "member");
506         if (el == NULL) {
507                 talloc_free(dn);
508                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
509         }
510         
511         for (i=0;i<el->num_values;i++) {
512                 DOM_SID sid;
513                 string_to_sid(&sid, (const char *)el->values[i].data);
514                 status = add_sid_to_array_unique(NULL, &sid, sids, num);
515                 if (!NT_STATUS_IS_OK(status)) {
516                         goto done;
517                 }
518         }
519
520 done:
521         talloc_free(dn);
522         return status;
523 }
524
525 /*
526   upgrade one group mapping record from the old tdb format
527 */
528 static int upgrade_map_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
529                               TDB_DATA data, void *state)
530 {
531         int ret;
532         GROUP_MAP map;
533
534         if (strncmp((char *)key.dptr, GROUP_PREFIX, 
535                     MIN(key.dsize, strlen(GROUP_PREFIX))) != 0) {
536                 return 0;
537         }
538
539         if (!string_to_sid(&map.sid, strlen(GROUP_PREFIX) + (const char *)key.dptr)) {
540                 DEBUG(0,("Bad sid key '%s' during upgrade\n", (const char *)key.dptr));
541                 *(int *)state = -1;
542                 return -1;
543         }
544
545         ret = tdb_unpack(data.dptr, data.dsize, "ddff",
546                          &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
547         if (ret == -1) {
548                 DEBUG(0,("Failed to unpack group map record during upgrade\n"));
549                 *(int *)state = -1;
550                 return -1;
551         }
552
553         if ((int)map.gid == -1) {
554                 /*
555                  * Ignore old invalid mappings
556                  */
557                 return 0;
558         }
559
560         if (!add_mapping_entry(&map, 0)) {
561                 DEBUG(0,("Failed to add mapping entry during upgrade\n"));
562                 *(int *)state = -1;
563                 return -1;
564         }
565
566         return 0;
567 }
568
569 /*
570   upgrade one alias record from the old tdb format
571 */
572 static int upgrade_alias_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
573                                 TDB_DATA data, void *state)
574 {
575         const char *p = (const char *)data.dptr;
576         char *string_sid;
577         DOM_SID member;
578         TALLOC_CTX *frame;
579
580         if (strncmp((char *)key.dptr, MEMBEROF_PREFIX, 
581                     MIN(key.dsize, strlen(MEMBEROF_PREFIX))) != 0) {
582                 return 0;
583         }
584
585         if (!string_to_sid(&member, strlen(MEMBEROF_PREFIX) + (const char *)key.dptr)) {
586                 DEBUG(0,("Bad alias key %s during upgrade\n",
587                          (const char *)key.dptr));
588                 *(int *)state = -1;
589         }
590
591         frame = talloc_stackframe();
592         while (next_token_talloc(frame,&p, &string_sid, " ")) {
593                 DOM_SID alias;
594                 NTSTATUS status;
595                 string_to_sid(&alias, string_sid);
596                 status = add_aliasmem(&alias, &member);
597                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_ALIAS)) {
598                         DEBUG(0,("Ignoring orphaned alias record '%s'\n", 
599                                  string_sid));
600                 } else if (!NT_STATUS_IS_OK(status)) {
601                         DEBUG(0,("Failed to add alias member during upgrade - %s\n",
602                                  nt_errstr(status)));
603                         *(int *)state = -1;
604                         TALLOC_FREE(frame);
605                         return -1;
606                 }
607         }
608         TALLOC_FREE(frame);
609         return 0;
610 }
611
612 /*
613   upgrade from a old style tdb
614 */
615 static bool mapping_upgrade(const char *tdb_path)
616 {
617         static TDB_CONTEXT *tdb;
618         int ret, status=0;
619
620         tdb = tdb_open_log(tdb_path, 0, TDB_DEFAULT, O_RDWR, 0600);
621         if (tdb == NULL) goto failed;
622
623         /* we have to do the map records first, as alias records may
624            reference them */
625         ret = tdb_traverse(tdb, upgrade_map_record, &status);
626         if (ret == -1 || status == -1) goto failed;
627
628         ret = tdb_traverse(tdb, upgrade_alias_record, &status);
629         if (ret == -1 || status == -1) goto failed;
630
631         if (tdb) {
632                 tdb_close(tdb);
633                 tdb = NULL;
634         }
635
636         {
637                 const char *old_path = tdb_path;
638                 char *new_path = state_path("group_mapping.tdb.upgraded");
639
640                 if (!new_path) {
641                         goto failed;
642                 }
643                 if (rename(old_path, new_path) != 0) {
644                         DEBUG(0,("Failed to rename old group mapping database\n"));
645                         goto failed;
646                 }
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 }