r19927: Fix klokwork ID 4702
[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: 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         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, "rid=%u,domain=%s", 
125                                      rid, string_sid);
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) {
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  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         if (!init_group_mapping()) {
214                 return False;
215         }
216
217         dn = mapping_dn(ldb, &sid);
218         if (dn == NULL) goto failed;
219
220         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, NULL, &res);
221         talloc_steal(dn, res);
222         if (ret != LDB_SUCCESS || res->count != 1) {
223                 goto failed;
224         }
225
226         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
227
228         talloc_free(dn);
229         return True;
230
231 failed:
232         talloc_free(dn);
233         return False;
234 }
235
236 /*
237  return a group map entry for a given gid
238 */
239  BOOL get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
240 {
241         int ret;
242         char *expr;
243         struct ldb_result *res=NULL;
244
245         if (!init_group_mapping()) {
246                 return False;
247         }
248
249         expr = talloc_asprintf(ldb, "(&(gidNumber=%u)(objectClass=groupMap))", 
250                                (unsigned)gid);
251         if (expr == NULL) goto failed;
252
253         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res);
254         talloc_steal(expr, res);
255         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
256         
257         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
258
259         talloc_free(expr);
260         return True;
261
262 failed:
263         talloc_free(expr);
264         return False;
265 }
266
267 /*
268   Return the sid and the type of the unix group.
269 */
270  BOOL get_group_map_from_ntname(const char *name, GROUP_MAP *map)
271 {
272         int ret;
273         char *expr;
274         struct ldb_result *res=NULL;
275
276         if (!init_group_mapping()) {
277                 return False;
278         }
279
280         expr = talloc_asprintf(ldb, "(&(ntName=%s)(objectClass=groupMap))", name);
281         if (expr == NULL) goto failed;
282
283         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, NULL, &res);
284         talloc_steal(expr, res);
285         if (ret != LDB_SUCCESS || res->count != 1) goto failed;
286         
287         if (!msg_to_group_map(res->msgs[0], map)) goto failed;
288
289         talloc_free(expr);
290         return True;
291
292 failed:
293         talloc_free(expr);
294         return False;
295 }
296
297 /*
298  Remove a group mapping entry.
299 */
300  BOOL group_map_remove(const DOM_SID *sid)
301 {
302         struct ldb_dn *dn;
303         int ret;
304         
305         if (!init_group_mapping()) {
306                 return False;
307         }
308
309         dn = mapping_dn(ldb, sid);
310         if (dn == NULL) {
311                 return False;
312         }
313         ret = ldb_delete(ldb, dn);
314         talloc_free(dn);
315
316         return ret == LDB_SUCCESS;
317 }
318
319
320 /*
321   Enumerate the group mappings for a domain
322 */
323  BOOL enum_group_mapping(const DOM_SID *domsid, enum lsa_SidType sid_name_use, 
324                          GROUP_MAP **pp_rmap,
325                          size_t *p_num_entries, BOOL unix_only)
326 {
327         int i, ret;
328         char *expr;
329         fstring name;
330         struct ldb_result *res;
331         struct ldb_dn *basedn=NULL;
332         TALLOC_CTX *tmp_ctx;
333
334         if (!init_group_mapping()) {
335                 return False;
336         }
337
338         tmp_ctx = talloc_new(ldb);
339         if (tmp_ctx == NULL) goto failed;
340
341         if (sid_name_use == SID_NAME_UNKNOWN) {
342                 expr = talloc_asprintf(tmp_ctx, "(&(objectClass=groupMap))");
343         } else {
344                 expr = talloc_asprintf(tmp_ctx, "(&(sidNameUse=%u)(objectClass=groupMap))",
345                                        sid_name_use);
346         }
347         if (expr == NULL) goto failed;
348
349         /* we do a subtree search on the domain */
350         if (domsid != NULL) {
351                 sid_to_string(name, domsid);
352                 basedn = ldb_dn_string_compose(tmp_ctx, NULL, "domain=%s", name);
353                 if (basedn == NULL) goto failed;
354         }
355
356         ret = ldb_search(ldb, basedn, LDB_SCOPE_SUBTREE, expr, NULL, &res);
357         if (ret != LDB_SUCCESS) goto failed;
358
359         (*pp_rmap) = NULL;
360         *p_num_entries = 0;
361
362         for (i=0;i<res->count;i++) {
363                 (*pp_rmap) = SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, 
364                                                (*p_num_entries)+1);
365                 if (!(*pp_rmap)) goto failed;
366
367                 if (!msg_to_group_map(res->msgs[i], &(*pp_rmap)[*p_num_entries])) {
368                         goto failed;
369                 }
370
371                 (*p_num_entries)++;
372         }
373
374         talloc_free(tmp_ctx);
375         return True;
376
377 failed:
378         talloc_free(tmp_ctx);
379         return False;   
380 }
381
382 /* 
383    This operation happens on session setup, so it should better be fast. We
384    store a list of aliases a SID is member of hanging off MEMBEROF/SID. 
385 */
386  NTSTATUS one_alias_membership(const DOM_SID *member,
387                                DOM_SID **sids, size_t *num)
388 {
389         const char *attrs[] = {
390                 "sid",
391                 NULL
392         };
393         DOM_SID alias;
394         char *expr;
395         int ret, i;
396         struct ldb_result *res=NULL;
397         fstring string_sid;
398         NTSTATUS status = NT_STATUS_INTERNAL_DB_CORRUPTION;
399
400         if (!init_group_mapping()) {
401                 return NT_STATUS_ACCESS_DENIED;
402         }
403
404         if (!sid_to_string(string_sid, member)) {
405                 return NT_STATUS_INVALID_PARAMETER;
406         }
407
408         expr = talloc_asprintf(ldb, "(&(member=%s)(objectClass=groupMap))", 
409                                string_sid);
410         if (expr == NULL) goto failed;
411
412         ret = ldb_search(ldb, NULL, LDB_SCOPE_SUBTREE, expr, attrs, &res);
413         talloc_steal(expr, res);
414         if (ret != LDB_SUCCESS) {
415                 goto failed;
416         }
417
418         for (i=0;i<res->count;i++) {
419                 struct ldb_message_element *el;
420                 el = ldb_msg_find_element(res->msgs[i], "sid");
421                 if (el == NULL || el->num_values != 1) {
422                         status = NT_STATUS_INTERNAL_DB_CORRUPTION;
423                         goto failed;
424                 }
425                 string_to_sid(&alias, (char *)el->values[0].data);
426                 add_sid_to_array_unique(NULL, &alias, sids, num);
427                 if (sids == NULL) {
428                         status = NT_STATUS_NO_MEMORY;
429                         goto failed;
430                 }
431         }
432
433         talloc_free(expr);
434         return NT_STATUS_OK;
435
436 failed:
437         talloc_free(expr);
438         return status;
439 }
440
441 /*
442   add/remove a member field
443 */
444 static NTSTATUS modify_aliasmem(const DOM_SID *alias, const DOM_SID *member,
445                                 int operation)
446 {
447         fstring string_sid;
448         int ret;
449         struct ldb_message msg;
450         struct ldb_message_element el;
451         struct ldb_val val;
452         TALLOC_CTX *tmp_ctx;
453         GROUP_MAP map;
454
455         if (!init_group_mapping()) {
456                 return NT_STATUS_ACCESS_DENIED;
457         }
458
459         if (!get_group_map_from_sid(*alias, &map)) {
460                 sid_to_string(string_sid, alias);
461                 return NT_STATUS_NO_SUCH_ALIAS;
462         }
463
464         if ((map.sid_name_use != SID_NAME_ALIAS) &&
465             (map.sid_name_use != SID_NAME_WKN_GRP)) {
466                 DEBUG(0,("sid_name_use=%d\n", map.sid_name_use));
467                 return NT_STATUS_NO_SUCH_ALIAS;
468         }
469
470         tmp_ctx = talloc_new(NULL);
471         if (tmp_ctx == NULL) {
472                 return NT_STATUS_NO_MEMORY;
473         }
474
475         msg.dn = mapping_dn(tmp_ctx, alias);
476         if (msg.dn == NULL) {
477                 return NT_STATUS_NO_MEMORY;
478         }
479         msg.num_elements = 1;
480         msg.elements = &el;
481         el.flags = operation;
482         el.name = talloc_strdup(tmp_ctx, "member");
483         el.num_values = 1;
484         el.values = &val;
485         sid_to_string(string_sid, member);
486         val.data = (uint8_t *)string_sid;
487         val.length = strlen(string_sid);
488
489         ret = ldb_modify(ldb, &msg);
490         talloc_free(tmp_ctx);
491
492         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
493                 return NT_STATUS_NO_SUCH_ALIAS;
494         }
495
496         if (operation == LDB_FLAG_MOD_ADD &&
497             ret == LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
498                 return NT_STATUS_MEMBER_IN_ALIAS;
499         }
500
501         return (ret == LDB_SUCCESS ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
502 }
503
504  NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
505 {
506         return modify_aliasmem(alias, member, LDB_FLAG_MOD_ADD);
507 }
508
509  NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
510 {
511         return modify_aliasmem(alias, member, LDB_FLAG_MOD_DELETE);
512 }
513
514
515 /*
516   enumerate sids that have the given alias set in member
517 */
518  NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
519 {
520         const char *attrs[] = {
521                 "member",
522                 NULL
523         };
524         int ret, i;
525         struct ldb_result *res=NULL;
526         struct ldb_dn *dn;
527         struct ldb_message_element *el;
528         
529         if (!init_group_mapping()) {
530                 return NT_STATUS_ACCESS_DENIED;
531         }
532
533         *sids = NULL;
534         *num = 0;
535
536         dn = mapping_dn(ldb, alias);
537         if (dn == NULL) {
538                 return NT_STATUS_NO_MEMORY;
539         }
540
541         ret = ldb_search(ldb, dn, LDB_SCOPE_BASE, NULL, attrs, &res);
542         talloc_steal(dn, res);
543         if (ret == LDB_SUCCESS && res->count == 0) {
544                 talloc_free(dn);
545                 return NT_STATUS_OK;
546         }
547         if (ret != LDB_SUCCESS) {
548                 talloc_free(dn);
549                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
550         }
551
552         el = ldb_msg_find_element(res->msgs[0], "member");
553         if (el == NULL) {
554                 talloc_free(dn);
555                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
556         }
557         
558         for (i=0;i<el->num_values;i++) {
559                 DOM_SID sid;
560                 string_to_sid(&sid, (const char *)el->values[i].data);
561                 add_sid_to_array_unique(NULL, &sid, sids, num);
562                 if (sids == NULL) {
563                         talloc_free(dn);
564                         return NT_STATUS_NO_MEMORY;
565                 }
566         }
567         talloc_free(dn);
568
569         return NT_STATUS_OK;
570 }
571
572 /*
573   upgrade one group mapping record from the old tdb format
574 */
575 static int upgrade_map_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
576                               TDB_DATA data, void *state)
577 {
578         int ret;
579         GROUP_MAP map;
580
581         if (strncmp(key.dptr, GROUP_PREFIX, 
582                     MIN(key.dsize, strlen(GROUP_PREFIX))) != 0) {
583                 return 0;
584         }
585
586         if (!string_to_sid(&map.sid, strlen(GROUP_PREFIX) + (const char *)key.dptr)) {
587                 DEBUG(0,("Bad sid key '%s' during upgrade\n", (const char *)key.dptr));
588                 *(int *)state = -1;
589                 return -1;
590         }
591
592         ret = tdb_unpack(data.dptr, data.dsize, "ddff",
593                          &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
594         if (ret == -1) {
595                 DEBUG(0,("Failed to unpack group map record during upgrade\n"));
596                 *(int *)state = -1;
597                 return -1;
598         }
599
600         if (!add_mapping_entry(&map, 0)) {
601                 DEBUG(0,("Failed to add mapping entry during upgrade\n"));
602                 *(int *)state = -1;
603                 return -1;
604         }
605
606         return 0;
607 }
608
609 /*
610   upgrade one alias record from the old tdb format
611 */
612 static int upgrade_alias_record(TDB_CONTEXT *tdb_ctx, TDB_DATA key, 
613                                 TDB_DATA data, void *state)
614 {
615         const char *p = data.dptr;
616         fstring string_sid;
617         DOM_SID member;
618
619         if (strncmp(key.dptr, MEMBEROF_PREFIX, 
620                     MIN(key.dsize, strlen(MEMBEROF_PREFIX))) != 0) {
621                 return 0;
622         }
623
624         if (!string_to_sid(&member, strlen(MEMBEROF_PREFIX) + (const char *)key.dptr)) {
625                 DEBUG(0,("Bad alias key %s during upgrade\n",
626                          (const char *)key.dptr));
627                 *(int *)state = -1;
628         }
629
630         while (next_token(&p, string_sid, " ", sizeof(string_sid))) {
631                 DOM_SID alias;
632                 NTSTATUS status;
633                 string_to_sid(&alias, string_sid);
634                 status = add_aliasmem(&alias, &member);
635                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_ALIAS)) {
636                         DEBUG(0,("Ignoring orphaned alias record '%s'\n", 
637                                  string_sid));
638                 } else if (!NT_STATUS_IS_OK(status)) {
639                         DEBUG(0,("Failed to add alias member during upgrade - %s\n",
640                                  nt_errstr(status)));
641                         *(int *)state = -1;
642                         return -1;
643                 }
644         }
645
646         return 0;
647 }
648
649 /*
650   upgrade from a old style tdb
651 */
652 static BOOL mapping_upgrade(const char *tdb_path)
653 {
654         static TDB_CONTEXT *tdb;
655         int ret, status=0;
656         pstring old_path;
657         pstring new_path;
658
659         tdb = tdb_open_log(tdb_path, 0, TDB_DEFAULT, O_RDWR, 0600);
660         if (tdb == NULL) goto failed;
661
662         /* we have to do the map records first, as alias records may
663            reference them */
664         ret = tdb_traverse(tdb, upgrade_map_record, &status);
665         if (ret == -1 || status == -1) goto failed;
666
667         ret = tdb_traverse(tdb, upgrade_alias_record, &status);
668         if (ret == -1 || status == -1) goto failed;
669
670         if (tdb) {
671                 tdb_close(tdb);
672                 tdb = NULL;
673         }
674
675         pstrcpy(old_path, tdb_path);
676         pstrcpy(new_path, lock_path("group_mapping.tdb.upgraded"));
677
678         if (rename(old_path, new_path) != 0) {
679                 DEBUG(0,("Failed to rename old group mapping database\n"));
680                 goto failed;
681         }
682         return True;
683
684 failed:
685         DEBUG(0,("Failed to upgrade group mapping database\n"));
686         if (tdb) tdb_close(tdb);
687         return False;
688 }