util_tdb: add a wrapper tdb_wipe() for traverse with tdb_traverse_delete_fn().
[vlendec/samba-autobuild/.git] / source3 / groupdb / mapping_tdb.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-2006,
5  *  Copyright (C) Jean François Micouleau      1998-2001.
6  *  Copyright (C) Volker Lendecke              2006.
7  *  Copyright (C) Gerald Carter                2006.
8  *  
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *  
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *  
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
21  */
22
23 #include "includes.h"
24 #include "groupdb/mapping.h"
25
26 static struct db_context *db; /* used for driver files */
27
28 static bool enum_group_mapping(const DOM_SID *domsid, enum lsa_SidType sid_name_use, GROUP_MAP **pp_rmap,
29                                size_t *p_num_entries, bool unix_only);
30 static bool group_map_remove(const DOM_SID *sid);
31         
32 /****************************************************************************
33  Open the group mapping tdb.
34 ****************************************************************************/
35 static bool init_group_mapping(void)
36 {
37         if (db != NULL) {
38                 return true;
39         }
40
41         db = db_open(NULL, state_path("group_mapping.tdb"), 0, TDB_DEFAULT,
42                      O_RDWR|O_CREAT, 0600);
43         if (db == NULL) {
44                 DEBUG(0, ("Failed to open group mapping database: %s\n",
45                           strerror(errno)));
46                 return false;
47         }
48
49 #if 0
50         /*
51          * This code was designed to handle a group mapping version
52          * upgrade. mapping_tdb is not active by default anymore, so ignore
53          * this here.
54          */
55         {
56                 const char *vstring = "INFO/version";
57                 int32 vers_id;
58                 GROUP_MAP *map_table = NULL;
59                 size_t num_entries = 0;
60
61                 /* handle a Samba upgrade */
62                 tdb_lock_bystring(tdb, vstring);
63
64                 /* Cope with byte-reversed older versions of the db. */
65                 vers_id = tdb_fetch_int32(tdb, vstring);
66                 if ((vers_id == DATABASE_VERSION_V1)
67                     || (IREV(vers_id) == DATABASE_VERSION_V1)) {
68                         /*
69                          * Written on a bigendian machine with old fetch_int
70                          * code. Save as le.
71                          */
72                         tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
73                         vers_id = DATABASE_VERSION_V2;
74                 }
75
76                 /* if its an unknown version we remove everthing in the db */
77
78                 if (vers_id != DATABASE_VERSION_V2) {
79                         tdb_wipe(tdb);
80                         tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
81                 }
82
83                 tdb_unlock_bystring(tdb, vstring);
84
85                 /* cleanup any map entries with a gid == -1 */
86
87                 if ( enum_group_mapping( NULL, SID_NAME_UNKNOWN, &map_table,
88                                          &num_entries, False ) ) {
89                         int i;
90
91                         for ( i=0; i<num_entries; i++ ) {
92                                 if ( map_table[i].gid == -1 ) {
93                                         group_map_remove( &map_table[i].sid );
94                                 }
95                         }
96
97                         SAFE_FREE( map_table );
98                 }
99         }
100 #endif
101
102         return true;
103 }
104
105 static char *group_mapping_key(TALLOC_CTX *mem_ctx, const DOM_SID *sid)
106 {
107         char *sidstr, *result;
108
109         sidstr = sid_string_talloc(talloc_tos(), sid);
110         if (sidstr == NULL) {
111                 return NULL;
112         }
113
114         result = talloc_asprintf(mem_ctx, "GROUP_PREFIX%s", sidstr);
115
116         TALLOC_FREE(sidstr);
117         return result;
118 }
119
120 /****************************************************************************
121 ****************************************************************************/
122 static bool add_mapping_entry(GROUP_MAP *map, int flag)
123 {
124         char *key, *buf;
125         int len;
126         NTSTATUS status;
127
128         key = group_mapping_key(talloc_tos(), &map->sid);
129         if (key == NULL) {
130                 return NULL;
131         }
132
133         len = tdb_pack(NULL, sizeof(buf), "ddff",
134                 map->gid, map->sid_name_use, map->nt_name, map->comment);
135
136         buf = TALLOC_ARRAY(key, char, len);
137         if (!buf) {
138                 TALLOC_FREE(key);
139                 return false;
140         }
141         len = tdb_pack((uint8 *)buf, len, "ddff", map->gid,
142                        map->sid_name_use, map->nt_name, map->comment);
143
144         status = dbwrap_store_bystring(
145                 db, key, make_tdb_data((uint8_t *)buf, len), flag);
146
147         TALLOC_FREE(key);
148
149         return NT_STATUS_IS_OK(status);
150 }
151
152
153 /****************************************************************************
154  Return the sid and the type of the unix group.
155 ****************************************************************************/
156
157 static bool get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
158 {
159         TDB_DATA dbuf;
160         char *key;
161         int ret = 0;
162
163         /* the key is the SID, retrieving is direct */
164
165         key = group_mapping_key(talloc_tos(), &map->sid);
166         if (key == NULL) {
167                 return false;
168         }
169
170         dbuf = dbwrap_fetch_bystring(db, key, key);
171         if (dbuf.dptr == NULL) {
172                 TALLOC_FREE(key);
173                 return false;
174         }
175
176         ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
177                         &map->gid, &map->sid_name_use,
178                         &map->nt_name, &map->comment);
179
180         TALLOC_FREE(key);
181
182         if ( ret == -1 ) {
183                 DEBUG(3,("get_group_map_from_sid: tdb_unpack failure\n"));
184                 return false;
185         }
186
187         sid_copy(&map->sid, &sid);
188
189         return true;
190 }
191
192 static bool dbrec2map(const struct db_record *rec, GROUP_MAP *map)
193 {
194         if ((rec->key.dsize < strlen(GROUP_PREFIX))
195             || (strncmp((char *)rec->key.dptr, GROUP_PREFIX,
196                         GROUP_PREFIX_LEN) != 0)) {
197                 return False;
198         }
199
200         if (!string_to_sid(&map->sid, (const char *)rec->key.dptr
201                            + GROUP_PREFIX_LEN)) {
202                 return False;
203         }
204
205         return tdb_unpack(rec->value.dptr, rec->value.dsize, "ddff",
206                           &map->gid, &map->sid_name_use, &map->nt_name,
207                           &map->comment) != -1;
208 }
209
210 struct find_map_state {
211         bool found;
212         const char *name;       /* If != NULL, look for name */
213         gid_t gid;              /* valid iff name == NULL */
214         GROUP_MAP *map;
215 };
216
217 static int find_map(struct db_record *rec, void *private_data)
218 {
219         struct find_map_state *state = (struct find_map_state *)private_data;
220
221         if (!dbrec2map(rec, state->map)) {
222                 DEBUG(10, ("failed to unpack map\n"));
223                 return 0;
224         }
225
226         if (state->name != NULL) {
227                 if (strequal(state->name, state->map->nt_name)) {
228                         state->found = true;
229                         return 1;
230                 }
231         }
232         else {
233                 if (state->map->gid == state->gid) {
234                         state->found = true;
235                         return 1;
236                 }
237         }
238
239         return 0;
240 }
241
242 /****************************************************************************
243  Return the sid and the type of the unix group.
244 ****************************************************************************/
245
246 static bool get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
247 {
248         struct find_map_state state;
249
250         state.found = false;
251         state.name = NULL;      /* Indicate we're looking for gid */
252         state.gid = gid;
253         state.map = map;
254
255         db->traverse_read(db, find_map, (void *)&state);
256
257         return state.found;
258 }
259
260 /****************************************************************************
261  Return the sid and the type of the unix group.
262 ****************************************************************************/
263
264 static bool get_group_map_from_ntname(const char *name, GROUP_MAP *map)
265 {
266         struct find_map_state state;
267
268         state.found = false;
269         state.name = name;
270         state.map = map;
271
272         db->traverse_read(db, find_map, (void *)&state);
273
274         return state.found;
275 }
276
277 /****************************************************************************
278  Remove a group mapping entry.
279 ****************************************************************************/
280
281 static bool group_map_remove(const DOM_SID *sid)
282 {
283         char *key;
284         bool result;
285
286         key = group_mapping_key(talloc_tos(), sid);
287         if (key == NULL) {
288                 return false;
289         }
290
291         result = NT_STATUS_IS_OK(dbwrap_delete_bystring(db, key));
292
293         TALLOC_FREE(key);
294         return result;
295 }
296
297 /****************************************************************************
298  Enumerate the group mapping.
299 ****************************************************************************/
300
301 struct enum_map_state {
302         const DOM_SID *domsid;
303         enum lsa_SidType sid_name_use;
304         bool unix_only;
305
306         size_t num_maps;
307         GROUP_MAP *maps;
308 };
309
310 static int collect_map(struct db_record *rec, void *private_data)
311 {
312         struct enum_map_state *state = (struct enum_map_state *)private_data;
313         GROUP_MAP map;
314         GROUP_MAP *tmp;
315
316         if (!dbrec2map(rec, &map)) {
317                 return 0;
318         }
319         /* list only the type or everything if UNKNOWN */
320         if (state->sid_name_use != SID_NAME_UNKNOWN
321             && state->sid_name_use != map.sid_name_use) {
322                 DEBUG(11,("enum_group_mapping: group %s is not of the "
323                           "requested type\n", map.nt_name));
324                 return 0;
325         }
326
327         if ((state->unix_only == ENUM_ONLY_MAPPED) && (map.gid == -1)) {
328                 DEBUG(11,("enum_group_mapping: group %s is non mapped\n",
329                           map.nt_name));
330                 return 0;
331         }
332
333         if ((state->domsid != NULL) &&
334             (sid_compare_domain(state->domsid, &map.sid) != 0)) {
335                 DEBUG(11,("enum_group_mapping: group %s is not in domain\n",
336                           sid_string_dbg(&map.sid)));
337                 return 0;
338         }
339
340         if (!(tmp = SMB_REALLOC_ARRAY(state->maps, GROUP_MAP,
341                                       state->num_maps+1))) {
342                 DEBUG(0,("enum_group_mapping: Unable to enlarge group "
343                          "map!\n"));
344                 return 1;
345         }
346
347         state->maps = tmp;
348         state->maps[state->num_maps] = map;
349         state->num_maps++;
350         return 0;
351 }
352
353 static bool enum_group_mapping(const DOM_SID *domsid,
354                                enum lsa_SidType sid_name_use,
355                                GROUP_MAP **pp_rmap,
356                                size_t *p_num_entries, bool unix_only)
357 {
358         struct enum_map_state state;
359
360         state.domsid = domsid;
361         state.sid_name_use = sid_name_use;
362         state.unix_only = unix_only;
363         state.num_maps = 0;
364         state.maps = NULL;
365
366         if (db->traverse_read(db, collect_map, (void *)&state) != 0) {
367                 return false;
368         }
369
370         *pp_rmap = state.maps;
371         *p_num_entries = state.num_maps;
372
373         return true;
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 static NTSTATUS one_alias_membership(const DOM_SID *member,
380                                DOM_SID **sids, size_t *num)
381 {
382         fstring tmp;
383         fstring key;
384         char *string_sid;
385         TDB_DATA dbuf;
386         const char *p;
387         NTSTATUS status = NT_STATUS_OK;
388         TALLOC_CTX *frame = talloc_stackframe();
389
390         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX,
391                  sid_to_fstring(tmp, member));
392
393         dbuf = dbwrap_fetch_bystring(db, frame, key);
394         if (dbuf.dptr == NULL) {
395                 TALLOC_FREE(frame);
396                 return NT_STATUS_OK;
397         }
398
399         p = (const char *)dbuf.dptr;
400
401         while (next_token_talloc(frame, &p, &string_sid, " ")) {
402                 DOM_SID alias;
403
404                 if (!string_to_sid(&alias, string_sid))
405                         continue;
406
407                 status= add_sid_to_array_unique(NULL, &alias, sids, num);
408                 if (!NT_STATUS_IS_OK(status)) {
409                         goto done;
410                 }
411         }
412
413 done:
414         TALLOC_FREE(frame);
415         return status;
416 }
417
418 static NTSTATUS alias_memberships(const DOM_SID *members, size_t num_members,
419                                   DOM_SID **sids, size_t *num)
420 {
421         size_t i;
422
423         *num = 0;
424         *sids = NULL;
425
426         for (i=0; i<num_members; i++) {
427                 NTSTATUS status = one_alias_membership(&members[i], sids, num);
428                 if (!NT_STATUS_IS_OK(status))
429                         return status;
430         }
431         return NT_STATUS_OK;
432 }
433
434 static bool is_aliasmem(const DOM_SID *alias, const DOM_SID *member)
435 {
436         DOM_SID *sids;
437         size_t i, num;
438
439         /* This feels the wrong way round, but the on-disk data structure
440          * dictates it this way. */
441         if (!NT_STATUS_IS_OK(alias_memberships(member, 1, &sids, &num)))
442                 return False;
443
444         for (i=0; i<num; i++) {
445                 if (sid_compare(alias, &sids[i]) == 0) {
446                         TALLOC_FREE(sids);
447                         return True;
448                 }
449         }
450         TALLOC_FREE(sids);
451         return False;
452 }
453
454
455 static NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
456 {
457         GROUP_MAP map;
458         char *key;
459         fstring string_sid;
460         char *new_memberstring;
461         struct db_record *rec;
462         NTSTATUS status;
463
464         if (!get_group_map_from_sid(*alias, &map))
465                 return NT_STATUS_NO_SUCH_ALIAS;
466
467         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
468              (map.sid_name_use != SID_NAME_WKN_GRP) )
469                 return NT_STATUS_NO_SUCH_ALIAS;
470
471         if (is_aliasmem(alias, member))
472                 return NT_STATUS_MEMBER_IN_ALIAS;
473
474         sid_to_fstring(string_sid, member);
475
476         key = talloc_asprintf(talloc_tos(), "%s%s", MEMBEROF_PREFIX,
477                               string_sid);
478         if (key == NULL) {
479                 return NT_STATUS_NO_MEMORY;
480         }
481
482         rec = db->fetch_locked(db, key, string_term_tdb_data(key));
483
484         if (rec == NULL) {
485                 DEBUG(10, ("fetch_lock failed\n"));
486                 TALLOC_FREE(key);
487                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
488         }
489
490         sid_to_fstring(string_sid, alias);
491
492         if (rec->value.dptr != NULL) {
493                 new_memberstring = talloc_asprintf(
494                         key, "%s %s", (char *)(rec->value.dptr), string_sid);
495         } else {
496                 new_memberstring = talloc_strdup(key, string_sid);
497         }
498
499         if (new_memberstring == NULL) {
500                 TALLOC_FREE(key);
501                 return NT_STATUS_NO_MEMORY;
502         }
503
504         status = rec->store(rec, string_term_tdb_data(new_memberstring), 0);
505
506         TALLOC_FREE(key);
507
508         if (!NT_STATUS_IS_OK(status)) {
509                 DEBUG(10, ("Could not store record: %s\n", nt_errstr(status)));
510         }
511
512         return status;
513 }
514
515 struct aliasmem_state {
516         const DOM_SID *alias;
517         DOM_SID **sids;
518         size_t *num;
519 };
520
521 static int collect_aliasmem(struct db_record *rec, void *priv)
522 {
523         struct aliasmem_state *state = (struct aliasmem_state *)priv;
524         const char *p;
525         char *alias_string;
526         TALLOC_CTX *frame;
527
528         if (strncmp((const char *)rec->key.dptr, MEMBEROF_PREFIX,
529                     MEMBEROF_PREFIX_LEN) != 0)
530                 return 0;
531
532         p = (const char *)rec->value.dptr;
533
534         frame = talloc_stackframe();
535
536         while (next_token_talloc(frame, &p, &alias_string, " ")) {
537                 DOM_SID alias, member;
538                 const char *member_string;
539
540                 if (!string_to_sid(&alias, alias_string))
541                         continue;
542
543                 if (sid_compare(state->alias, &alias) != 0)
544                         continue;
545
546                 /* Ok, we found the alias we're looking for in the membership
547                  * list currently scanned. The key represents the alias
548                  * member. Add that. */
549
550                 member_string = strchr((const char *)rec->key.dptr, '/');
551
552                 /* Above we tested for MEMBEROF_PREFIX which includes the
553                  * slash. */
554
555                 SMB_ASSERT(member_string != NULL);
556                 member_string += 1;
557
558                 if (!string_to_sid(&member, member_string))
559                         continue;
560
561                 if (!NT_STATUS_IS_OK(add_sid_to_array(NULL, &member,
562                                                       state->sids,
563                                                       state->num)))
564                 {
565                         /* talloc fail. */
566                         break;
567                 }
568         }
569
570         TALLOC_FREE(frame);
571         return 0;
572 }
573
574 static NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
575 {
576         GROUP_MAP map;
577         struct aliasmem_state state;
578
579         if (!get_group_map_from_sid(*alias, &map))
580                 return NT_STATUS_NO_SUCH_ALIAS;
581
582         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
583              (map.sid_name_use != SID_NAME_WKN_GRP) )
584                 return NT_STATUS_NO_SUCH_ALIAS;
585
586         *sids = NULL;
587         *num = 0;
588
589         state.alias = alias;
590         state.sids = sids;
591         state.num = num;
592
593         db->traverse_read(db, collect_aliasmem, &state);
594         return NT_STATUS_OK;
595 }
596
597 static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
598 {
599         NTSTATUS status;
600         DOM_SID *sids;
601         size_t i, num;
602         bool found = False;
603         char *member_string;
604         char *key;
605         fstring sid_string;
606
607         status = alias_memberships(member, 1, &sids, &num);
608
609         if (!NT_STATUS_IS_OK(status))
610                 return status;
611
612         for (i=0; i<num; i++) {
613                 if (sid_compare(&sids[i], alias) == 0) {
614                         found = True;
615                         break;
616                 }
617         }
618
619         if (!found) {
620                 TALLOC_FREE(sids);
621                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
622         }
623
624         if (i < num)
625                 sids[i] = sids[num-1];
626
627         num -= 1;
628
629         sid_to_fstring(sid_string, member);
630
631         key = talloc_asprintf(sids, "%s%s", MEMBEROF_PREFIX, sid_string);
632         if (key == NULL) {
633                 TALLOC_FREE(sids);
634                 return NT_STATUS_NO_MEMORY;
635         }
636
637         if (num == 0) {
638                 status = dbwrap_delete_bystring(db, key);
639                 TALLOC_FREE(sids);
640                 return status;
641         }
642
643         member_string = talloc_strdup(sids, "");
644         if (member_string == NULL) {
645                 TALLOC_FREE(sids);
646                 return NT_STATUS_NO_MEMORY;
647         }
648
649         for (i=0; i<num; i++) {
650
651                 sid_to_fstring(sid_string, &sids[i]);
652
653                 member_string = talloc_asprintf_append_buffer(
654                         member_string, " %s", sid_string);
655
656                 if (member_string == NULL) {
657                         TALLOC_FREE(sids);
658                         return NT_STATUS_NO_MEMORY;
659                 }
660         }
661
662         status = dbwrap_store_bystring(
663                 db, key, string_term_tdb_data(member_string), 0);
664
665         TALLOC_FREE(sids);
666
667         return status;
668 }
669
670 static const struct mapping_backend tdb_backend = {
671         .add_mapping_entry         = add_mapping_entry,
672         .get_group_map_from_sid    = get_group_map_from_sid,
673         .get_group_map_from_gid    = get_group_map_from_gid,
674         .get_group_map_from_ntname = get_group_map_from_ntname,
675         .group_map_remove          = group_map_remove,
676         .enum_group_mapping        = enum_group_mapping,
677         .one_alias_membership      = one_alias_membership,
678         .add_aliasmem              = add_aliasmem,
679         .del_aliasmem              = del_aliasmem,
680         .enum_aliasmem             = enum_aliasmem      
681 };
682
683 /*
684   initialise the tdb mapping backend
685  */
686 const struct mapping_backend *groupdb_tdb_init(void)
687 {
688         if (!init_group_mapping()) {
689                 DEBUG(0,("Failed to initialise tdb mapping backend\n"));
690                 return NULL;
691         }
692
693         return &tdb_backend;
694 }