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