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