r22509: Fix some memory corruption caused by calling free()
[samba.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 2 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, write to the Free Software
21  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  */
23
24 #include "includes.h"
25 #include "groupdb/mapping.h"
26
27 static TDB_CONTEXT *tdb; /* used for driver files */
28
29 /****************************************************************************
30  Open the group mapping tdb.
31 ****************************************************************************/
32  BOOL init_group_mapping(void)
33 {
34         const char *vstring = "INFO/version";
35         int32 vers_id;
36         GROUP_MAP *map_table = NULL;
37         size_t num_entries = 0;
38         
39         if (tdb)
40                 return True;
41                 
42         tdb = tdb_open_log(lock_path("group_mapping.tdb"), 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
43         if (!tdb) {
44                 DEBUG(0,("Failed to open group mapping database\n"));
45                 return False;
46         }
47
48         /* handle a Samba upgrade */
49         tdb_lock_bystring(tdb, vstring);
50
51         /* Cope with byte-reversed older versions of the db. */
52         vers_id = tdb_fetch_int32(tdb, vstring);
53         if ((vers_id == DATABASE_VERSION_V1) || (IREV(vers_id) == DATABASE_VERSION_V1)) {
54                 /* Written on a bigendian machine with old fetch_int code. Save as le. */
55                 tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
56                 vers_id = DATABASE_VERSION_V2;
57         }
58
59         /* if its an unknown version we remove everthing in the db */
60         
61         if (vers_id != DATABASE_VERSION_V2) {
62                 tdb_traverse(tdb, tdb_traverse_delete_fn, NULL);
63                 tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
64         }
65
66         tdb_unlock_bystring(tdb, vstring);
67
68         /* cleanup any map entries with a gid == -1 */
69         
70         if ( enum_group_mapping( NULL, SID_NAME_UNKNOWN, &map_table, &num_entries, False ) ) {
71                 int i;
72                 
73                 for ( i=0; i<num_entries; i++ ) {
74                         if ( map_table[i].gid == -1 ) {
75                                 group_map_remove( &map_table[i].sid );
76                         }
77                 }
78                 
79                 SAFE_FREE( map_table );
80         }
81
82
83         return True;
84 }
85
86 /****************************************************************************
87 ****************************************************************************/
88  BOOL add_mapping_entry(GROUP_MAP *map, int flag)
89 {
90         TDB_DATA dbuf;
91         pstring key, buf;
92         fstring string_sid="";
93         int len;
94
95         if(!init_group_mapping()) {
96                 DEBUG(0,("failed to initialize group mapping\n"));
97                 return(False);
98         }
99         
100         sid_to_string(string_sid, &map->sid);
101
102         len = tdb_pack((uint8 *)buf, sizeof(buf), "ddff",
103                         map->gid, map->sid_name_use, map->nt_name, map->comment);
104
105         if (len > sizeof(buf))
106                 return False;
107
108         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
109
110         dbuf.dsize = len;
111         dbuf.dptr = (uint8 *)buf;
112         if (tdb_store_bystring(tdb, key, dbuf, flag) != 0) return False;
113
114         return True;
115 }
116
117
118 /****************************************************************************
119  Return the sid and the type of the unix group.
120 ****************************************************************************/
121
122  BOOL get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
123 {
124         TDB_DATA dbuf;
125         pstring key;
126         fstring string_sid;
127         int ret = 0;
128         
129         if(!init_group_mapping()) {
130                 DEBUG(0,("failed to initialize group mapping\n"));
131                 return(False);
132         }
133
134         /* the key is the SID, retrieving is direct */
135
136         sid_to_string(string_sid, &sid);
137         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
138
139         dbuf = tdb_fetch_bystring(tdb, key);
140         if (!dbuf.dptr)
141                 return False;
142
143         ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
144                                 &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
145
146         SAFE_FREE(dbuf.dptr);
147         
148         if ( ret == -1 ) {
149                 DEBUG(3,("get_group_map_from_sid: tdb_unpack failure\n"));
150                 return False;
151         }
152
153         sid_copy(&map->sid, &sid);
154         
155         return True;
156 }
157
158 /****************************************************************************
159  Return the sid and the type of the unix group.
160 ****************************************************************************/
161
162  BOOL get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
163 {
164         TDB_DATA kbuf, dbuf, newkey;
165         fstring string_sid;
166         int ret;
167
168         if(!init_group_mapping()) {
169                 DEBUG(0,("failed to initialize group mapping\n"));
170                 return(False);
171         }
172
173         /* we need to enumerate the TDB to find the GID */
174
175         for (kbuf = tdb_firstkey(tdb); 
176              kbuf.dptr; 
177              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
178
179                 if (strncmp((const char *)kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
180                 
181                 dbuf = tdb_fetch(tdb, kbuf);
182                 if (!dbuf.dptr)
183                         continue;
184
185                 fstrcpy(string_sid, (const char *)kbuf.dptr+strlen(GROUP_PREFIX));
186
187                 string_to_sid(&map->sid, string_sid);
188                 
189                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
190                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
191
192                 SAFE_FREE(dbuf.dptr);
193
194                 if ( ret == -1 ) {
195                         DEBUG(3,("get_group_map_from_gid: tdb_unpack failure\n"));
196                         return False;
197                 }
198         
199                 if (gid==map->gid) {
200                         SAFE_FREE(kbuf.dptr);
201                         return True;
202                 }
203         }
204
205         return False;
206 }
207
208 /****************************************************************************
209  Return the sid and the type of the unix group.
210 ****************************************************************************/
211
212  BOOL get_group_map_from_ntname(const char *name, GROUP_MAP *map)
213 {
214         TDB_DATA kbuf, dbuf, newkey;
215         fstring string_sid;
216         int ret;
217
218         if(!init_group_mapping()) {
219                 DEBUG(0,("get_group_map_from_ntname:failed to initialize group mapping\n"));
220                 return(False);
221         }
222
223         /* we need to enumerate the TDB to find the name */
224
225         for (kbuf = tdb_firstkey(tdb); 
226              kbuf.dptr; 
227              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
228
229                 if (strncmp((const char *)kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
230                 
231                 dbuf = tdb_fetch(tdb, kbuf);
232                 if (!dbuf.dptr)
233                         continue;
234
235                 fstrcpy(string_sid, (const char *)kbuf.dptr+strlen(GROUP_PREFIX));
236
237                 string_to_sid(&map->sid, string_sid);
238                 
239                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
240                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
241
242                 SAFE_FREE(dbuf.dptr);
243                 
244                 if ( ret == -1 ) {
245                         DEBUG(3,("get_group_map_from_ntname: tdb_unpack failure\n"));
246                         return False;
247                 }
248
249                 if ( strequal(name, map->nt_name) ) {
250                         SAFE_FREE(kbuf.dptr);
251                         return True;
252                 }
253         }
254
255         return False;
256 }
257
258 /****************************************************************************
259  Remove a group mapping entry.
260 ****************************************************************************/
261
262 BOOL group_map_remove(const DOM_SID *sid)
263 {
264         TDB_DATA dbuf;
265         pstring key;
266         fstring string_sid;
267         
268         if(!init_group_mapping()) {
269                 DEBUG(0,("failed to initialize group mapping\n"));
270                 return(False);
271         }
272
273         /* the key is the SID, retrieving is direct */
274
275         sid_to_string(string_sid, sid);
276         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
277
278         dbuf = tdb_fetch_bystring(tdb, key);
279         if (!dbuf.dptr)
280                 return False;
281         
282         SAFE_FREE(dbuf.dptr);
283
284         if(tdb_delete_bystring(tdb, key) != TDB_SUCCESS)
285                 return False;
286
287         return True;
288 }
289
290 /****************************************************************************
291  Enumerate the group mapping.
292 ****************************************************************************/
293
294 BOOL enum_group_mapping(const DOM_SID *domsid, enum lsa_SidType sid_name_use, GROUP_MAP **pp_rmap,
295                         size_t *p_num_entries, BOOL unix_only)
296 {
297         TDB_DATA kbuf, dbuf, newkey;
298         fstring string_sid;
299         GROUP_MAP map;
300         GROUP_MAP *mapt;
301         int ret;
302         size_t entries=0;
303         DOM_SID grpsid;
304         uint32 rid;
305
306         if(!init_group_mapping()) {
307                 DEBUG(0,("failed to initialize group mapping\n"));
308                 return(False);
309         }
310
311         *p_num_entries=0;
312         *pp_rmap=NULL;
313
314         for (kbuf = tdb_firstkey(tdb); 
315              kbuf.dptr; 
316              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
317
318                 if (strncmp((const char *)kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0)
319                         continue;
320
321                 dbuf = tdb_fetch(tdb, kbuf);
322                 if (!dbuf.dptr)
323                         continue;
324
325                 fstrcpy(string_sid, (const char *)kbuf.dptr+strlen(GROUP_PREFIX));
326                                 
327                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
328                                  &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
329
330                 SAFE_FREE(dbuf.dptr);
331
332                 if ( ret == -1 ) {
333                         DEBUG(3,("enum_group_mapping: tdb_unpack failure\n"));
334                         continue;
335                 }
336         
337                 /* list only the type or everything if UNKNOWN */
338                 if (sid_name_use!=SID_NAME_UNKNOWN  && sid_name_use!=map.sid_name_use) {
339                         DEBUG(11,("enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
340                         continue;
341                 }
342
343                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
344                         DEBUG(11,("enum_group_mapping: group %s is non mapped\n", map.nt_name));
345                         continue;
346                 }
347
348                 string_to_sid(&grpsid, string_sid);
349                 sid_copy( &map.sid, &grpsid );
350                 
351                 sid_split_rid( &grpsid, &rid );
352
353                 /* Only check the domain if we were given one */
354
355                 if ( domsid && !sid_equal( domsid, &grpsid ) ) {
356                         DEBUG(11,("enum_group_mapping: group %s is not in domain %s\n", 
357                                 string_sid, sid_string_static(domsid)));
358                         continue;
359                 }
360
361                 DEBUG(11,("enum_group_mapping: returning group %s of "
362                           "type %s\n", map.nt_name,
363                           sid_type_lookup(map.sid_name_use)));
364
365                 (*pp_rmap) = SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
366                 if (!(*pp_rmap)) {
367                         DEBUG(0,("enum_group_mapping: Unable to enlarge group map!\n"));
368                         return False;
369                 }
370
371                 mapt = (*pp_rmap);
372
373                 mapt[entries].gid = map.gid;
374                 sid_copy( &mapt[entries].sid, &map.sid);
375                 mapt[entries].sid_name_use = map.sid_name_use;
376                 fstrcpy(mapt[entries].nt_name, map.nt_name);
377                 fstrcpy(mapt[entries].comment, map.comment);
378
379                 entries++;
380
381         }
382
383         *p_num_entries=entries;
384
385         return True;
386 }
387
388 /* This operation happens on session setup, so it should better be fast. We
389  * store a list of aliases a SID is member of hanging off MEMBEROF/SID. */
390
391  NTSTATUS one_alias_membership(const DOM_SID *member,
392                                DOM_SID **sids, size_t *num)
393 {
394         fstring key, string_sid;
395         TDB_DATA dbuf;
396         const char *p;
397
398         if (!init_group_mapping()) {
399                 DEBUG(0,("failed to initialize group mapping\n"));
400                 return NT_STATUS_ACCESS_DENIED;
401         }
402
403         sid_to_string(string_sid, member);
404         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
405
406         dbuf = tdb_fetch_bystring(tdb, key);
407
408         if (dbuf.dptr == NULL) {
409                 return NT_STATUS_OK;
410         }
411
412         p = (const char *)dbuf.dptr;
413
414         while (next_token(&p, string_sid, " ", sizeof(string_sid))) {
415
416                 DOM_SID alias;
417
418                 if (!string_to_sid(&alias, string_sid))
419                         continue;
420
421                 if (!add_sid_to_array_unique(NULL, &alias, sids, num)) {
422                         return NT_STATUS_NO_MEMORY;
423                 }
424         }
425
426         SAFE_FREE(dbuf.dptr);
427         return NT_STATUS_OK;
428 }
429
430 static NTSTATUS alias_memberships(const DOM_SID *members, size_t num_members,
431                                   DOM_SID **sids, size_t *num)
432 {
433         size_t i;
434
435         *num = 0;
436         *sids = NULL;
437
438         for (i=0; i<num_members; i++) {
439                 NTSTATUS status = one_alias_membership(&members[i], sids, num);
440                 if (!NT_STATUS_IS_OK(status))
441                         return status;
442         }
443         return NT_STATUS_OK;
444 }
445
446 static BOOL is_aliasmem(const DOM_SID *alias, const DOM_SID *member)
447 {
448         DOM_SID *sids;
449         size_t i, num;
450
451         /* This feels the wrong way round, but the on-disk data structure
452          * dictates it this way. */
453         if (!NT_STATUS_IS_OK(alias_memberships(member, 1, &sids, &num)))
454                 return False;
455
456         for (i=0; i<num; i++) {
457                 if (sid_compare(alias, &sids[i]) == 0) {
458                         TALLOC_FREE(sids);
459                         return True;
460                 }
461         }
462         TALLOC_FREE(sids);
463         return False;
464 }
465
466
467  NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
468 {
469         GROUP_MAP map;
470         TDB_DATA dbuf;
471         pstring key;
472         fstring string_sid;
473         char *new_memberstring;
474         int result;
475
476         if(!init_group_mapping()) {
477                 DEBUG(0,("failed to initialize group mapping\n"));
478                 return NT_STATUS_ACCESS_DENIED;
479         }
480
481         if (!get_group_map_from_sid(*alias, &map))
482                 return NT_STATUS_NO_SUCH_ALIAS;
483
484         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
485              (map.sid_name_use != SID_NAME_WKN_GRP) )
486                 return NT_STATUS_NO_SUCH_ALIAS;
487
488         if (is_aliasmem(alias, member))
489                 return NT_STATUS_MEMBER_IN_ALIAS;
490
491         sid_to_string(string_sid, member);
492         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
493
494         dbuf = tdb_fetch_bystring(tdb, key);
495
496         sid_to_string(string_sid, alias);
497
498         if (dbuf.dptr != NULL) {
499                 asprintf(&new_memberstring, "%s %s", (char *)(dbuf.dptr),
500                          string_sid);
501         } else {
502                 new_memberstring = SMB_STRDUP(string_sid);
503         }
504
505         if (new_memberstring == NULL)
506                 return NT_STATUS_NO_MEMORY;
507
508         SAFE_FREE(dbuf.dptr);
509         dbuf = string_term_tdb_data(new_memberstring);
510
511         result = tdb_store_bystring(tdb, key, dbuf, 0);
512
513         SAFE_FREE(new_memberstring);
514
515         return (result == 0 ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
516 }
517
518 struct aliasmem_closure {
519         const DOM_SID *alias;
520         DOM_SID **sids;
521         size_t *num;
522 };
523
524 static int collect_aliasmem(TDB_CONTEXT *tdb_ctx, TDB_DATA key, TDB_DATA data,
525                             void *state)
526 {
527         struct aliasmem_closure *closure = (struct aliasmem_closure *)state;
528         const char *p;
529         fstring alias_string;
530
531         if (strncmp((const char *)key.dptr, MEMBEROF_PREFIX,
532                     strlen(MEMBEROF_PREFIX)) != 0)
533                 return 0;
534
535         p = (const char *)data.dptr;
536
537         while (next_token(&p, alias_string, " ", sizeof(alias_string))) {
538
539                 DOM_SID alias, member;
540                 const char *member_string;
541                 
542
543                 if (!string_to_sid(&alias, alias_string))
544                         continue;
545
546                 if (sid_compare(closure->alias, &alias) != 0)
547                         continue;
548
549                 /* Ok, we found the alias we're looking for in the membership
550                  * list currently scanned. The key represents the alias
551                  * member. Add that. */
552
553                 member_string = strchr((const char *)key.dptr, '/');
554
555                 /* Above we tested for MEMBEROF_PREFIX which includes the
556                  * slash. */
557
558                 SMB_ASSERT(member_string != NULL);
559                 member_string += 1;
560
561                 if (!string_to_sid(&member, member_string))
562                         continue;
563                 
564                 if (!add_sid_to_array(NULL, &member, closure->sids, closure->num)) {
565                         /* talloc fail. */
566                         break;
567                 }
568         }
569
570         return 0;
571 }
572
573  NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
574 {
575         GROUP_MAP map;
576         struct aliasmem_closure closure;
577
578         if(!init_group_mapping()) {
579                 DEBUG(0,("failed to initialize group mapping\n"));
580                 return NT_STATUS_ACCESS_DENIED;
581         }
582
583         if (!get_group_map_from_sid(*alias, &map))
584                 return NT_STATUS_NO_SUCH_ALIAS;
585
586         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
587              (map.sid_name_use != SID_NAME_WKN_GRP) )
588                 return NT_STATUS_NO_SUCH_ALIAS;
589
590         *sids = NULL;
591         *num = 0;
592
593         closure.alias = alias;
594         closure.sids = sids;
595         closure.num = num;
596
597         tdb_traverse(tdb, collect_aliasmem, &closure);
598         return NT_STATUS_OK;
599 }
600
601  NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
602 {
603         NTSTATUS result;
604         DOM_SID *sids;
605         size_t i, num;
606         BOOL found = False;
607         char *member_string;
608         TDB_DATA dbuf;
609         pstring key;
610         fstring sid_string;
611
612         result = alias_memberships(member, 1, &sids, &num);
613
614         if (!NT_STATUS_IS_OK(result))
615                 return result;
616
617         for (i=0; i<num; i++) {
618                 if (sid_compare(&sids[i], alias) == 0) {
619                         found = True;
620                         break;
621                 }
622         }
623
624         if (!found) {
625                 TALLOC_FREE(sids);
626                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
627         }
628
629         if (i < num)
630                 sids[i] = sids[num-1];
631
632         num -= 1;
633
634         sid_to_string(sid_string, member);
635         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, sid_string);
636
637         if (num == 0)
638                 return tdb_delete_bystring(tdb, key) == 0 ?
639                         NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
640
641         member_string = SMB_STRDUP("");
642
643         if (member_string == NULL) {
644                 TALLOC_FREE(sids);
645                 return NT_STATUS_NO_MEMORY;
646         }
647
648         for (i=0; i<num; i++) {
649                 char *s = member_string;
650
651                 sid_to_string(sid_string, &sids[i]);
652                 asprintf(&member_string, "%s %s", s, sid_string);
653
654                 SAFE_FREE(s);
655                 if (member_string == NULL) {
656                         TALLOC_FREE(sids);
657                         return NT_STATUS_NO_MEMORY;
658                 }
659         }
660
661         dbuf = string_term_tdb_data(member_string);
662
663         result = tdb_store_bystring(tdb, key, dbuf, 0) == 0 ?
664                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
665
666         TALLOC_FREE(sids);
667         SAFE_FREE(member_string);
668
669         return result;
670 }
671