r14403: * modifies create_local_nt_token() to create a BUILTIN\Administrators
[samba.git] / source3 / groupdb / mapping.c
1 /* 
2  *  Unix SMB/CIFS implementation.
3  *  RPC Pipe client / server routines
4  *  Copyright (C) Andrew Tridgell              1992-2000,
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
26 static TDB_CONTEXT *tdb; /* used for driver files */
27
28 #define DATABASE_VERSION_V1 1 /* native byte format. */
29 #define DATABASE_VERSION_V2 2 /* le format. */
30
31 #define GROUP_PREFIX "UNIXGROUP/"
32
33 /* Alias memberships are stored reverse, as memberships. The performance
34  * critical operation is to determine the aliases a SID is member of, not
35  * listing alias members. So we store a list of alias SIDs a SID is member of
36  * hanging of the member as key.
37  */
38 #define MEMBEROF_PREFIX "MEMBEROF/"
39
40
41 static BOOL enum_group_mapping(const DOM_SID *sid, enum SID_NAME_USE sid_name_use, GROUP_MAP **pp_rmap,
42                                size_t *p_num_entries, BOOL unix_only);
43 static BOOL group_map_remove(const DOM_SID *sid);
44                         
45 /****************************************************************************
46  Open the group mapping tdb.
47 ****************************************************************************/
48
49 static BOOL init_group_mapping(void)
50 {
51         const char *vstring = "INFO/version";
52         int32 vers_id;
53         GROUP_MAP *map_table = NULL;
54         size_t num_entries = 0;
55         
56         if (tdb)
57                 return True;
58                 
59         tdb = tdb_open_log(lock_path("group_mapping.tdb"), 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0600);
60         if (!tdb) {
61                 DEBUG(0,("Failed to open group mapping database\n"));
62                 return False;
63         }
64
65         /* handle a Samba upgrade */
66         tdb_lock_bystring(tdb, vstring, 0);
67
68         /* Cope with byte-reversed older versions of the db. */
69         vers_id = tdb_fetch_int32(tdb, vstring);
70         if ((vers_id == DATABASE_VERSION_V1) || (IREV(vers_id) == DATABASE_VERSION_V1)) {
71                 /* Written on a bigendian machine with old fetch_int code. Save as le. */
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_traverse(tdb, tdb_traverse_delete_fn, NULL);
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, &num_entries, False ) ) {
88                 int i;
89                 
90                 for ( i=0; i<num_entries; i++ ) {
91                         if ( map_table[i].gid == -1 ) {
92                                 group_map_remove( &map_table[i].sid );
93                         }
94                 }
95                 
96                 SAFE_FREE( map_table );
97         }
98
99
100         return True;
101 }
102
103 /****************************************************************************
104 ****************************************************************************/
105 static BOOL add_mapping_entry(GROUP_MAP *map, int flag)
106 {
107         TDB_DATA kbuf, dbuf;
108         pstring key, buf;
109         fstring string_sid="";
110         int len;
111
112         if(!init_group_mapping()) {
113                 DEBUG(0,("failed to initialize group mapping\n"));
114                 return(False);
115         }
116         
117         sid_to_string(string_sid, &map->sid);
118
119         len = tdb_pack(buf, sizeof(buf), "ddff",
120                         map->gid, map->sid_name_use, map->nt_name, map->comment);
121
122         if (len > sizeof(buf))
123                 return False;
124
125         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
126
127         kbuf.dsize = strlen(key)+1;
128         kbuf.dptr = key;
129         dbuf.dsize = len;
130         dbuf.dptr = buf;
131         if (tdb_store(tdb, kbuf, dbuf, flag) != 0) return False;
132
133         return True;
134 }
135
136 /****************************************************************************
137 initialise first time the mapping list
138 ****************************************************************************/
139 NTSTATUS add_initial_entry(gid_t gid, const char *sid, enum SID_NAME_USE sid_name_use, const char *nt_name, const char *comment)
140 {
141         GROUP_MAP map;
142
143         if(!init_group_mapping()) {
144                 DEBUG(0,("failed to initialize group mapping\n"));
145                 return NT_STATUS_UNSUCCESSFUL;
146         }
147         
148         map.gid=gid;
149         if (!string_to_sid(&map.sid, sid)) {
150                 DEBUG(0, ("string_to_sid failed: %s", sid));
151                 return NT_STATUS_UNSUCCESSFUL;
152         }
153         
154         map.sid_name_use=sid_name_use;
155         fstrcpy(map.nt_name, nt_name);
156         fstrcpy(map.comment, comment);
157
158         return pdb_add_group_mapping_entry(&map);
159 }
160
161 /****************************************************************************
162  Map a unix group to a newly created mapping
163 ****************************************************************************/
164 NTSTATUS map_unix_group(const struct group *grp, GROUP_MAP *pmap)
165 {
166         NTSTATUS status;
167         GROUP_MAP map;
168         const char *grpname, *dom, *name;
169         uint32 rid;
170
171         if (pdb_getgrgid(&map, grp->gr_gid)) {
172                 return NT_STATUS_GROUP_EXISTS;
173         }
174
175         map.gid = grp->gr_gid;
176         grpname = grp->gr_name;
177
178         if (lookup_name(tmp_talloc_ctx(), grpname, LOOKUP_NAME_ISOLATED,
179                         &dom, &name, NULL, NULL)) {
180
181                 const char *tmp = talloc_asprintf(
182                         tmp_talloc_ctx(), "Unix Group %s", grp->gr_name);
183
184                 DEBUG(5, ("%s exists as %s\\%s, retrying as \"%s\"\n",
185                           grpname, dom, name, tmp));
186                 grpname = tmp;
187         }
188
189         if (lookup_name(tmp_talloc_ctx(), grpname, LOOKUP_NAME_ISOLATED,
190                         NULL, NULL, NULL, NULL)) {
191                 DEBUG(3, ("\"%s\" exists, can't map it\n", grp->gr_name));
192                 return NT_STATUS_GROUP_EXISTS;
193         }
194
195         fstrcpy(map.nt_name, grpname);
196
197         if (pdb_rid_algorithm()) {
198                 rid = pdb_gid_to_group_rid( grp->gr_gid );
199         } else {
200                 if (!pdb_new_rid(&rid)) {
201                         DEBUG(3, ("Could not get a new RID for %s\n",
202                                   grp->gr_name));
203                         return NT_STATUS_ACCESS_DENIED;
204                 }
205         }
206
207         sid_compose(&map.sid, get_global_sam_sid(), rid);
208         map.sid_name_use = SID_NAME_DOM_GRP;
209         fstrcpy(map.comment, talloc_asprintf(tmp_talloc_ctx(), "Unix Group %s",
210                                              grp->gr_name));
211
212         status = pdb_add_group_mapping_entry(&map);
213         if (NT_STATUS_IS_OK(status)) {
214                 *pmap = map;
215         }
216         return status;
217 }
218
219 /****************************************************************************
220  Return the sid and the type of the unix group.
221 ****************************************************************************/
222
223 static BOOL get_group_map_from_sid(DOM_SID sid, GROUP_MAP *map)
224 {
225         TDB_DATA kbuf, dbuf;
226         pstring key;
227         fstring string_sid;
228         int ret = 0;
229         
230         if(!init_group_mapping()) {
231                 DEBUG(0,("failed to initialize group mapping\n"));
232                 return(False);
233         }
234
235         /* the key is the SID, retrieving is direct */
236
237         sid_to_string(string_sid, &sid);
238         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
239
240         kbuf.dptr = key;
241         kbuf.dsize = strlen(key)+1;
242                 
243         dbuf = tdb_fetch(tdb, kbuf);
244         if (!dbuf.dptr)
245                 return False;
246
247         ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
248                                 &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
249
250         SAFE_FREE(dbuf.dptr);
251         
252         if ( ret == -1 ) {
253                 DEBUG(3,("get_group_map_from_sid: tdb_unpack failure\n"));
254                 return False;
255         }
256         
257         sid_copy(&map->sid, &sid);
258         
259         return True;
260 }
261
262 /****************************************************************************
263  Return the sid and the type of the unix group.
264 ****************************************************************************/
265
266 static BOOL get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
267 {
268         TDB_DATA kbuf, dbuf, newkey;
269         fstring string_sid;
270         int ret;
271
272         if(!init_group_mapping()) {
273                 DEBUG(0,("failed to initialize group mapping\n"));
274                 return(False);
275         }
276
277         /* we need to enumerate the TDB to find the GID */
278
279         for (kbuf = tdb_firstkey(tdb); 
280              kbuf.dptr; 
281              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
282
283                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
284                 
285                 dbuf = tdb_fetch(tdb, kbuf);
286                 if (!dbuf.dptr)
287                         continue;
288
289                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
290
291                 string_to_sid(&map->sid, string_sid);
292                 
293                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
294                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
295
296                 SAFE_FREE(dbuf.dptr);
297
298                 if ( ret == -1 ) {
299                         DEBUG(3,("get_group_map_from_gid: tdb_unpack failure\n"));
300                         return False;
301                 }
302         
303                 if (gid==map->gid) {
304                         SAFE_FREE(kbuf.dptr);
305                         return True;
306                 }
307         }
308
309         return False;
310 }
311
312 /****************************************************************************
313  Return the sid and the type of the unix group.
314 ****************************************************************************/
315
316 static BOOL get_group_map_from_ntname(const char *name, GROUP_MAP *map)
317 {
318         TDB_DATA kbuf, dbuf, newkey;
319         fstring string_sid;
320         int ret;
321
322         if(!init_group_mapping()) {
323                 DEBUG(0,("get_group_map_from_ntname:failed to initialize group mapping\n"));
324                 return(False);
325         }
326
327         /* we need to enumerate the TDB to find the name */
328
329         for (kbuf = tdb_firstkey(tdb); 
330              kbuf.dptr; 
331              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
332
333                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
334                 
335                 dbuf = tdb_fetch(tdb, kbuf);
336                 if (!dbuf.dptr)
337                         continue;
338
339                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
340
341                 string_to_sid(&map->sid, string_sid);
342                 
343                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
344                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
345
346                 SAFE_FREE(dbuf.dptr);
347                 
348                 if ( ret == -1 ) {
349                         DEBUG(3,("get_group_map_from_ntname: tdb_unpack failure\n"));
350                         return False;
351                 }
352
353                 if ( strequal(name, map->nt_name) ) {
354                         SAFE_FREE(kbuf.dptr);
355                         return True;
356                 }
357         }
358
359         return False;
360 }
361
362 /****************************************************************************
363  Remove a group mapping entry.
364 ****************************************************************************/
365
366 static BOOL group_map_remove(const DOM_SID *sid)
367 {
368         TDB_DATA kbuf, dbuf;
369         pstring key;
370         fstring string_sid;
371         
372         if(!init_group_mapping()) {
373                 DEBUG(0,("failed to initialize group mapping\n"));
374                 return(False);
375         }
376
377         /* the key is the SID, retrieving is direct */
378
379         sid_to_string(string_sid, sid);
380         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
381
382         kbuf.dptr = key;
383         kbuf.dsize = strlen(key)+1;
384                 
385         dbuf = tdb_fetch(tdb, kbuf);
386         if (!dbuf.dptr)
387                 return False;
388         
389         SAFE_FREE(dbuf.dptr);
390
391         if(tdb_delete(tdb, kbuf) != TDB_SUCCESS)
392                 return False;
393
394         return True;
395 }
396
397 /****************************************************************************
398  Enumerate the group mapping.
399 ****************************************************************************/
400
401 static BOOL enum_group_mapping(const DOM_SID *domsid, enum SID_NAME_USE sid_name_use, GROUP_MAP **pp_rmap,
402                         size_t *p_num_entries, BOOL unix_only)
403 {
404         TDB_DATA kbuf, dbuf, newkey;
405         fstring string_sid;
406         GROUP_MAP map;
407         GROUP_MAP *mapt;
408         int ret;
409         size_t entries=0;
410         DOM_SID grpsid;
411         uint32 rid;
412
413         if(!init_group_mapping()) {
414                 DEBUG(0,("failed to initialize group mapping\n"));
415                 return(False);
416         }
417
418         *p_num_entries=0;
419         *pp_rmap=NULL;
420
421         for (kbuf = tdb_firstkey(tdb); 
422              kbuf.dptr; 
423              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
424
425                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0)
426                         continue;
427
428                 dbuf = tdb_fetch(tdb, kbuf);
429                 if (!dbuf.dptr)
430                         continue;
431
432                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
433                                 
434                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
435                                  &map.gid, &map.sid_name_use, &map.nt_name, &map.comment);
436
437                 SAFE_FREE(dbuf.dptr);
438
439                 if ( ret == -1 ) {
440                         DEBUG(3,("enum_group_mapping: tdb_unpack failure\n"));
441                         continue;
442                 }
443         
444                 /* list only the type or everything if UNKNOWN */
445                 if (sid_name_use!=SID_NAME_UNKNOWN  && sid_name_use!=map.sid_name_use) {
446                         DEBUG(11,("enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
447                         continue;
448                 }
449
450                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
451                         DEBUG(11,("enum_group_mapping: group %s is non mapped\n", map.nt_name));
452                         continue;
453                 }
454
455                 string_to_sid(&grpsid, string_sid);
456                 sid_copy( &map.sid, &grpsid );
457                 
458                 sid_split_rid( &grpsid, &rid );
459
460                 /* Only check the domain if we were given one */
461
462                 if ( domsid && !sid_equal( domsid, &grpsid ) ) {
463                         DEBUG(11,("enum_group_mapping: group %s is not in domain %s\n", 
464                                 string_sid, sid_string_static(domsid)));
465                         continue;
466                 }
467
468                 DEBUG(11,("enum_group_mapping: returning group %s of "
469                           "type %s\n", map.nt_name,
470                           sid_type_lookup(map.sid_name_use)));
471
472                 (*pp_rmap) = SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
473                 if (!(*pp_rmap)) {
474                         DEBUG(0,("enum_group_mapping: Unable to enlarge group map!\n"));
475                         return False;
476                 }
477
478                 mapt = (*pp_rmap);
479
480                 mapt[entries].gid = map.gid;
481                 sid_copy( &mapt[entries].sid, &map.sid);
482                 mapt[entries].sid_name_use = map.sid_name_use;
483                 fstrcpy(mapt[entries].nt_name, map.nt_name);
484                 fstrcpy(mapt[entries].comment, map.comment);
485
486                 entries++;
487
488         }
489
490         *p_num_entries=entries;
491
492         return True;
493 }
494
495 /* This operation happens on session setup, so it should better be fast. We
496  * store a list of aliases a SID is member of hanging off MEMBEROF/SID. */
497
498 static NTSTATUS one_alias_membership(const DOM_SID *member,
499                                      DOM_SID **sids, size_t *num)
500 {
501         fstring key, string_sid;
502         TDB_DATA kbuf, dbuf;
503         const char *p;
504
505         if (!init_group_mapping()) {
506                 DEBUG(0,("failed to initialize group mapping\n"));
507                 return NT_STATUS_ACCESS_DENIED;
508         }
509
510         sid_to_string(string_sid, member);
511         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
512
513         kbuf.dsize = strlen(key)+1;
514         kbuf.dptr = key;
515
516         dbuf = tdb_fetch(tdb, kbuf);
517
518         if (dbuf.dptr == NULL) {
519                 return NT_STATUS_OK;
520         }
521
522         p = dbuf.dptr;
523
524         while (next_token(&p, string_sid, " ", sizeof(string_sid))) {
525
526                 DOM_SID alias;
527
528                 if (!string_to_sid(&alias, string_sid))
529                         continue;
530
531                 add_sid_to_array_unique(NULL, &alias, sids, num);
532
533                 if (sids == NULL)
534                         return NT_STATUS_NO_MEMORY;
535         }
536
537         SAFE_FREE(dbuf.dptr);
538         return NT_STATUS_OK;
539 }
540
541 static NTSTATUS alias_memberships(const DOM_SID *members, size_t num_members,
542                                   DOM_SID **sids, size_t *num)
543 {
544         size_t i;
545
546         *num = 0;
547         *sids = NULL;
548
549         for (i=0; i<num_members; i++) {
550                 NTSTATUS status = one_alias_membership(&members[i], sids, num);
551                 if (!NT_STATUS_IS_OK(status))
552                         return status;
553         }
554         return NT_STATUS_OK;
555 }
556
557 static BOOL is_aliasmem(const DOM_SID *alias, const DOM_SID *member)
558 {
559         DOM_SID *sids;
560         size_t i, num;
561
562         /* This feels the wrong way round, but the on-disk data structure
563          * dictates it this way. */
564         if (!NT_STATUS_IS_OK(alias_memberships(member, 1, &sids, &num)))
565                 return False;
566
567         for (i=0; i<num; i++) {
568                 if (sid_compare(alias, &sids[i]) == 0) {
569                         SAFE_FREE(sids);
570                         return True;
571                 }
572         }
573         SAFE_FREE(sids);
574         return False;
575 }
576
577 static NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
578 {
579         GROUP_MAP map;
580         TDB_DATA kbuf, dbuf;
581         pstring key;
582         fstring string_sid;
583         char *new_memberstring;
584         int result;
585
586         if(!init_group_mapping()) {
587                 DEBUG(0,("failed to initialize group mapping\n"));
588                 return NT_STATUS_ACCESS_DENIED;
589         }
590
591         if (!get_group_map_from_sid(*alias, &map))
592                 return NT_STATUS_NO_SUCH_ALIAS;
593
594         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
595              (map.sid_name_use != SID_NAME_WKN_GRP) )
596                 return NT_STATUS_NO_SUCH_ALIAS;
597
598         if (is_aliasmem(alias, member))
599                 return NT_STATUS_MEMBER_IN_ALIAS;
600
601         sid_to_string(string_sid, member);
602         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
603
604         kbuf.dsize = strlen(key)+1;
605         kbuf.dptr = key;
606
607         dbuf = tdb_fetch(tdb, kbuf);
608
609         sid_to_string(string_sid, alias);
610
611         if (dbuf.dptr != NULL) {
612                 asprintf(&new_memberstring, "%s %s", (char *)(dbuf.dptr),
613                          string_sid);
614         } else {
615                 new_memberstring = SMB_STRDUP(string_sid);
616         }
617
618         if (new_memberstring == NULL)
619                 return NT_STATUS_NO_MEMORY;
620
621         SAFE_FREE(dbuf.dptr);
622         dbuf.dsize = strlen(new_memberstring)+1;
623         dbuf.dptr = new_memberstring;
624
625         result = tdb_store(tdb, kbuf, dbuf, 0);
626
627         SAFE_FREE(new_memberstring);
628
629         return (result == 0 ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
630 }
631
632 struct aliasmem_closure {
633         const DOM_SID *alias;
634         DOM_SID **sids;
635         size_t *num;
636 };
637
638 static int collect_aliasmem(TDB_CONTEXT *tdb_ctx, TDB_DATA key, TDB_DATA data,
639                             void *state)
640 {
641         struct aliasmem_closure *closure = (struct aliasmem_closure *)state;
642         const char *p;
643         fstring alias_string;
644
645         if (strncmp(key.dptr, MEMBEROF_PREFIX,
646                     strlen(MEMBEROF_PREFIX)) != 0)
647                 return 0;
648
649         p = data.dptr;
650
651         while (next_token(&p, alias_string, " ", sizeof(alias_string))) {
652
653                 DOM_SID alias, member;
654                 const char *member_string;
655                 
656
657                 if (!string_to_sid(&alias, alias_string))
658                         continue;
659
660                 if (sid_compare(closure->alias, &alias) != 0)
661                         continue;
662
663                 /* Ok, we found the alias we're looking for in the membership
664                  * list currently scanned. The key represents the alias
665                  * member. Add that. */
666
667                 member_string = strchr(key.dptr, '/');
668
669                 /* Above we tested for MEMBEROF_PREFIX which includes the
670                  * slash. */
671
672                 SMB_ASSERT(member_string != NULL);
673                 member_string += 1;
674
675                 if (!string_to_sid(&member, member_string))
676                         continue;
677                 
678                 add_sid_to_array(NULL, &member, closure->sids, closure->num);
679         }
680
681         return 0;
682 }
683
684 static NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, size_t *num)
685 {
686         GROUP_MAP map;
687         struct aliasmem_closure closure;
688
689         if(!init_group_mapping()) {
690                 DEBUG(0,("failed to initialize group mapping\n"));
691                 return NT_STATUS_ACCESS_DENIED;
692         }
693
694         if (!get_group_map_from_sid(*alias, &map))
695                 return NT_STATUS_NO_SUCH_ALIAS;
696
697         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
698              (map.sid_name_use != SID_NAME_WKN_GRP) )
699                 return NT_STATUS_NO_SUCH_ALIAS;
700
701         *sids = NULL;
702         *num = 0;
703
704         closure.alias = alias;
705         closure.sids = sids;
706         closure.num = num;
707
708         tdb_traverse(tdb, collect_aliasmem, &closure);
709         return NT_STATUS_OK;
710 }
711
712 static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
713 {
714         NTSTATUS result;
715         DOM_SID *sids;
716         size_t i, num;
717         BOOL found = False;
718         char *member_string;
719         TDB_DATA kbuf, dbuf;
720         pstring key;
721         fstring sid_string;
722
723         result = alias_memberships(member, 1, &sids, &num);
724
725         if (!NT_STATUS_IS_OK(result))
726                 return result;
727
728         for (i=0; i<num; i++) {
729                 if (sid_compare(&sids[i], alias) == 0) {
730                         found = True;
731                         break;
732                 }
733         }
734
735         if (!found) {
736                 SAFE_FREE(sids);
737                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
738         }
739
740         if (i < num)
741                 sids[i] = sids[num-1];
742
743         num -= 1;
744
745         sid_to_string(sid_string, member);
746         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, sid_string);
747
748         kbuf.dsize = strlen(key)+1;
749         kbuf.dptr = key;
750
751         if (num == 0)
752                 return tdb_delete(tdb, kbuf) == 0 ?
753                         NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
754
755         member_string = SMB_STRDUP("");
756
757         if (member_string == NULL) {
758                 SAFE_FREE(sids);
759                 return NT_STATUS_NO_MEMORY;
760         }
761
762         for (i=0; i<num; i++) {
763                 char *s = member_string;
764
765                 sid_to_string(sid_string, &sids[i]);
766                 asprintf(&member_string, "%s %s", s, sid_string);
767
768                 SAFE_FREE(s);
769                 if (member_string == NULL) {
770                         SAFE_FREE(sids);
771                         return NT_STATUS_NO_MEMORY;
772                 }
773         }
774
775         dbuf.dsize = strlen(member_string)+1;
776         dbuf.dptr = member_string;
777
778         result = tdb_store(tdb, kbuf, dbuf, 0) == 0 ?
779                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
780
781         SAFE_FREE(sids);
782         SAFE_FREE(member_string);
783
784         return result;
785 }
786
787 /*
788  *
789  * High level functions
790  * better to use them than the lower ones.
791  *
792  * we are checking if the group is in the mapping file
793  * and if the group is an existing unix group
794  *
795  */
796
797 /* get a domain group from it's SID */
798
799 BOOL get_domain_group_from_sid(DOM_SID sid, GROUP_MAP *map)
800 {
801         struct group *grp;
802         BOOL ret;
803         
804         if(!init_group_mapping()) {
805                 DEBUG(0,("failed to initialize group mapping\n"));
806                 return(False);
807         }
808
809         DEBUG(10, ("get_domain_group_from_sid\n"));
810
811         /* if the group is NOT in the database, it CAN NOT be a domain group */
812         
813         become_root();
814         ret = pdb_getgrsid(map, sid);
815         unbecome_root();
816         
817         if ( !ret ) 
818                 return False;
819
820         DEBUG(10, ("get_domain_group_from_sid: SID found in the TDB\n"));
821
822         /* if it's not a domain group, continue */
823         if (map->sid_name_use!=SID_NAME_DOM_GRP) {
824                 return False;
825         }
826
827         DEBUG(10, ("get_domain_group_from_sid: SID is a domain group\n"));
828         
829         if (map->gid==-1) {
830                 return False;
831         }
832
833         DEBUG(10, ("get_domain_group_from_sid: SID is mapped to gid:%lu\n",(unsigned long)map->gid));
834         
835         grp = getgrgid(map->gid);
836         if ( !grp ) {
837                 DEBUG(10, ("get_domain_group_from_sid: gid DOESN'T exist in UNIX security\n"));
838                 return False;
839         }
840
841         DEBUG(10, ("get_domain_group_from_sid: gid exists in UNIX security\n"));
842
843         return True;
844 }
845
846 /****************************************************************************
847  Create a UNIX group on demand.
848 ****************************************************************************/
849
850 int smb_create_group(const char *unix_group, gid_t *new_gid)
851 {
852         pstring add_script;
853         int     ret = -1;
854         int     fd = 0;
855         
856         *new_gid = 0;
857
858         /* defer to scripts */
859         
860         if ( *lp_addgroup_script() ) {
861                 pstrcpy(add_script, lp_addgroup_script());
862                 pstring_sub(add_script, "%g", unix_group);
863                 ret = smbrun(add_script, &fd);
864                 DEBUG(ret ? 0 : 3,("smb_create_group: Running the command `%s' gave %d\n",add_script,ret));
865                 if (ret != 0)
866                         return ret;
867                         
868                 if (fd != 0) {
869                         fstring output;
870
871                         *new_gid = 0;
872                         if (read(fd, output, sizeof(output)) > 0) {
873                                 *new_gid = (gid_t)strtoul(output, NULL, 10);
874                         }
875                         
876                         close(fd);
877                 }
878
879         }
880
881         if (*new_gid == 0) {
882                 struct group *grp = getgrnam(unix_group);
883
884                 if (grp != NULL)
885                         *new_gid = grp->gr_gid;
886         }
887                         
888         return ret;     
889 }
890
891 /****************************************************************************
892  Delete a UNIX group on demand.
893 ****************************************************************************/
894
895 int smb_delete_group(const char *unix_group)
896 {
897         pstring del_script;
898         int ret;
899
900         /* defer to scripts */
901         
902         if ( *lp_delgroup_script() ) {
903                 pstrcpy(del_script, lp_delgroup_script());
904                 pstring_sub(del_script, "%g", unix_group);
905                 ret = smbrun(del_script,NULL);
906                 DEBUG(ret ? 0 : 3,("smb_delete_group: Running the command `%s' gave %d\n",del_script,ret));
907                 return ret;
908         }
909                 
910         return -1;
911 }
912
913 /****************************************************************************
914  Set a user's primary UNIX group.
915 ****************************************************************************/
916 int smb_set_primary_group(const char *unix_group, const char* unix_user)
917 {
918         pstring add_script;
919         int ret;
920
921         /* defer to scripts */
922         
923         if ( *lp_setprimarygroup_script() ) {
924                 pstrcpy(add_script, lp_setprimarygroup_script());
925                 all_string_sub(add_script, "%g", unix_group, sizeof(add_script));
926                 all_string_sub(add_script, "%u", unix_user, sizeof(add_script));
927                 ret = smbrun(add_script,NULL);
928                 flush_pwnam_cache();
929                 DEBUG(ret ? 0 : 3,("smb_set_primary_group: "
930                          "Running the command `%s' gave %d\n",add_script,ret));
931                 return ret;
932         }
933
934         return -1;
935 }
936
937 /****************************************************************************
938  Add a user to a UNIX group.
939 ****************************************************************************/
940
941 int smb_add_user_group(const char *unix_group, const char *unix_user)
942 {
943         pstring add_script;
944         int ret;
945
946         /* defer to scripts */
947         
948         if ( *lp_addusertogroup_script() ) {
949                 pstrcpy(add_script, lp_addusertogroup_script());
950                 pstring_sub(add_script, "%g", unix_group);
951                 pstring_sub(add_script, "%u", unix_user);
952                 ret = smbrun(add_script,NULL);
953                 DEBUG(ret ? 0 : 3,("smb_add_user_group: Running the command `%s' gave %d\n",add_script,ret));
954                 return ret;
955         }
956         
957         return -1;
958 }
959
960 /****************************************************************************
961  Delete a user from a UNIX group
962 ****************************************************************************/
963
964 int smb_delete_user_group(const char *unix_group, const char *unix_user)
965 {
966         pstring del_script;
967         int ret;
968
969         /* defer to scripts */
970         
971         if ( *lp_deluserfromgroup_script() ) {
972                 pstrcpy(del_script, lp_deluserfromgroup_script());
973                 pstring_sub(del_script, "%g", unix_group);
974                 pstring_sub(del_script, "%u", unix_user);
975                 ret = smbrun(del_script,NULL);
976                 DEBUG(ret ? 0 : 3,("smb_delete_user_group: Running the command `%s' gave %d\n",del_script,ret));
977                 return ret;
978         }
979         
980         return -1;
981 }
982
983
984 NTSTATUS pdb_default_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
985                                  DOM_SID sid)
986 {
987         return get_group_map_from_sid(sid, map) ?
988                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
989 }
990
991 NTSTATUS pdb_default_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
992                                  gid_t gid)
993 {
994         return get_group_map_from_gid(gid, map) ?
995                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
996 }
997
998 NTSTATUS pdb_default_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
999                                  const char *name)
1000 {
1001         return get_group_map_from_ntname(name, map) ?
1002                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1003 }
1004
1005 NTSTATUS pdb_default_add_group_mapping_entry(struct pdb_methods *methods,
1006                                                 GROUP_MAP *map)
1007 {
1008         return add_mapping_entry(map, TDB_INSERT) ?
1009                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1010 }
1011
1012 NTSTATUS pdb_default_update_group_mapping_entry(struct pdb_methods *methods,
1013                                                    GROUP_MAP *map)
1014 {
1015         return add_mapping_entry(map, TDB_REPLACE) ?
1016                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1017 }
1018
1019 NTSTATUS pdb_default_delete_group_mapping_entry(struct pdb_methods *methods,
1020                                                    DOM_SID sid)
1021 {
1022         return group_map_remove(&sid) ?
1023                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1024 }
1025
1026 NTSTATUS pdb_default_enum_group_mapping(struct pdb_methods *methods,
1027                                            const DOM_SID *sid, enum SID_NAME_USE sid_name_use,
1028                                            GROUP_MAP **pp_rmap, size_t *p_num_entries,
1029                                            BOOL unix_only)
1030 {
1031         return enum_group_mapping(sid, sid_name_use, pp_rmap, p_num_entries, unix_only) ?
1032                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1033 }
1034
1035 NTSTATUS pdb_default_find_alias(struct pdb_methods *methods,
1036                                 const char *name, DOM_SID *sid)
1037 {
1038         GROUP_MAP map;
1039
1040         if (!pdb_getgrnam(&map, name))
1041                 return NT_STATUS_NO_SUCH_ALIAS;
1042
1043         if ((map.sid_name_use != SID_NAME_WKN_GRP) &&
1044             (map.sid_name_use != SID_NAME_ALIAS))
1045                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
1046
1047         sid_copy(sid, &map.sid);
1048         return NT_STATUS_OK;
1049 }
1050
1051 NTSTATUS pdb_default_create_alias(struct pdb_methods *methods,
1052                                   const char *name, uint32 *rid)
1053 {
1054         DOM_SID sid;
1055         enum SID_NAME_USE type;
1056         uint32 new_rid;
1057         gid_t gid;
1058         BOOL exists;
1059         GROUP_MAP map;
1060         TALLOC_CTX *mem_ctx;
1061         NTSTATUS status;
1062
1063         DEBUG(10, ("Trying to create alias %s\n", name));
1064
1065         mem_ctx = talloc_new(NULL);
1066         if (mem_ctx == NULL) {
1067                 return NT_STATUS_NO_MEMORY;
1068         }
1069
1070         exists = lookup_name(mem_ctx, name, LOOKUP_NAME_ISOLATED,
1071                              NULL, NULL, &sid, &type);
1072         TALLOC_FREE(mem_ctx);
1073
1074         if (exists) {
1075                 return NT_STATUS_ALIAS_EXISTS;
1076         }
1077
1078         if (!winbind_allocate_gid(&gid)) {
1079                 DEBUG(3, ("Could not get a gid out of winbind\n"));
1080                 return NT_STATUS_ACCESS_DENIED;
1081         }
1082
1083         if (!pdb_new_rid(&new_rid)) {
1084                 DEBUG(0, ("Could not allocate a RID -- wasted a gid :-(\n"));
1085                 return NT_STATUS_ACCESS_DENIED;
1086         }
1087
1088         DEBUG(10, ("Creating alias %s with gid %d and rid %d\n",
1089                    name, gid, new_rid));
1090
1091         sid_copy(&sid, get_global_sam_sid());
1092         sid_append_rid(&sid, new_rid);
1093
1094         map.gid = gid;
1095         sid_copy(&map.sid, &sid);
1096         map.sid_name_use = SID_NAME_ALIAS;
1097         fstrcpy(map.nt_name, name);
1098         fstrcpy(map.comment, "");
1099
1100         status = pdb_add_group_mapping_entry(&map);
1101
1102         if (!NT_STATUS_IS_OK(status)) {
1103                 DEBUG(0, ("Could not add group mapping entry for alias %s "
1104                           "(%s)\n", name, nt_errstr(status)));
1105                 return status;
1106         }
1107
1108         *rid = new_rid;
1109
1110         return NT_STATUS_OK;
1111 }
1112
1113 NTSTATUS pdb_default_delete_alias(struct pdb_methods *methods,
1114                                   const DOM_SID *sid)
1115 {
1116         return pdb_delete_group_mapping_entry(*sid);
1117 }
1118
1119 NTSTATUS pdb_default_get_aliasinfo(struct pdb_methods *methods,
1120                                    const DOM_SID *sid,
1121                                    struct acct_info *info)
1122 {
1123         GROUP_MAP map;
1124
1125         if (!pdb_getgrsid(&map, *sid))
1126                 return NT_STATUS_NO_SUCH_ALIAS;
1127
1128         if ((map.sid_name_use != SID_NAME_ALIAS) &&
1129             (map.sid_name_use != SID_NAME_WKN_GRP)) {
1130                 DEBUG(2, ("%s is a %s, expected an alias\n",
1131                           sid_string_static(sid),
1132                           sid_type_lookup(map.sid_name_use)));
1133                 return NT_STATUS_NO_SUCH_ALIAS;
1134         }
1135
1136         fstrcpy(info->acct_name, map.nt_name);
1137         fstrcpy(info->acct_desc, map.comment);
1138         sid_peek_rid(&map.sid, &info->rid);
1139         return NT_STATUS_OK;
1140 }
1141
1142 NTSTATUS pdb_default_set_aliasinfo(struct pdb_methods *methods,
1143                                    const DOM_SID *sid,
1144                                    struct acct_info *info)
1145 {
1146         GROUP_MAP map;
1147
1148         if (!pdb_getgrsid(&map, *sid))
1149                 return NT_STATUS_NO_SUCH_ALIAS;
1150
1151         fstrcpy(map.comment, info->acct_desc);
1152
1153         return pdb_update_group_mapping_entry(&map);
1154 }
1155
1156 NTSTATUS pdb_default_add_aliasmem(struct pdb_methods *methods,
1157                                   const DOM_SID *alias, const DOM_SID *member)
1158 {
1159         return add_aliasmem(alias, member);
1160 }
1161
1162 NTSTATUS pdb_default_del_aliasmem(struct pdb_methods *methods,
1163                                   const DOM_SID *alias, const DOM_SID *member)
1164 {
1165         return del_aliasmem(alias, member);
1166 }
1167
1168 NTSTATUS pdb_default_enum_aliasmem(struct pdb_methods *methods,
1169                                    const DOM_SID *alias, DOM_SID **pp_members,
1170                                    size_t *p_num_members)
1171 {
1172         return enum_aliasmem(alias, pp_members, p_num_members);
1173 }
1174
1175 NTSTATUS pdb_default_alias_memberships(struct pdb_methods *methods,
1176                                        TALLOC_CTX *mem_ctx,
1177                                        const DOM_SID *domain_sid,
1178                                        const DOM_SID *members,
1179                                        size_t num_members,
1180                                        uint32 **pp_alias_rids,
1181                                        size_t *p_num_alias_rids)
1182 {
1183         DOM_SID *alias_sids;
1184         size_t i, num_alias_sids;
1185         NTSTATUS result;
1186
1187         alias_sids = NULL;
1188         num_alias_sids = 0;
1189
1190         result = alias_memberships(members, num_members,
1191                                    &alias_sids, &num_alias_sids);
1192
1193         if (!NT_STATUS_IS_OK(result))
1194                 return result;
1195
1196         *pp_alias_rids = TALLOC_ARRAY(mem_ctx, uint32, num_alias_sids);
1197         if (*pp_alias_rids == NULL)
1198                 return NT_STATUS_NO_MEMORY;
1199
1200         *p_num_alias_rids = 0;
1201
1202         for (i=0; i<num_alias_sids; i++) {
1203                 if (!sid_peek_check_rid(domain_sid, &alias_sids[i],
1204                                         &(*pp_alias_rids)[*p_num_alias_rids]))
1205                         continue;
1206                 *p_num_alias_rids += 1;
1207         }
1208
1209         SAFE_FREE(alias_sids);
1210
1211         return NT_STATUS_OK;
1212 }
1213
1214 /**********************************************************************
1215  no ops for passdb backends that don't implement group mapping
1216  *********************************************************************/
1217
1218 NTSTATUS pdb_nop_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1219                                  DOM_SID sid)
1220 {
1221         return NT_STATUS_UNSUCCESSFUL;
1222 }
1223
1224 NTSTATUS pdb_nop_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1225                                  gid_t gid)
1226 {
1227         return NT_STATUS_UNSUCCESSFUL;
1228 }
1229
1230 NTSTATUS pdb_nop_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1231                                  const char *name)
1232 {
1233         return NT_STATUS_UNSUCCESSFUL;
1234 }
1235
1236 NTSTATUS pdb_nop_add_group_mapping_entry(struct pdb_methods *methods,
1237                                                 GROUP_MAP *map)
1238 {
1239         return NT_STATUS_UNSUCCESSFUL;
1240 }
1241
1242 NTSTATUS pdb_nop_update_group_mapping_entry(struct pdb_methods *methods,
1243                                                    GROUP_MAP *map)
1244 {
1245         return NT_STATUS_UNSUCCESSFUL;
1246 }
1247
1248 NTSTATUS pdb_nop_delete_group_mapping_entry(struct pdb_methods *methods,
1249                                                    DOM_SID sid)
1250 {
1251         return NT_STATUS_UNSUCCESSFUL;
1252 }
1253
1254 NTSTATUS pdb_nop_enum_group_mapping(struct pdb_methods *methods,
1255                                            enum SID_NAME_USE sid_name_use,
1256                                            GROUP_MAP **rmap, size_t *num_entries,
1257                                            BOOL unix_only)
1258 {
1259         return NT_STATUS_UNSUCCESSFUL;
1260 }
1261
1262 /****************************************************************************
1263  These need to be redirected through pdb_interface.c
1264 ****************************************************************************/
1265 BOOL pdb_get_dom_grp_info(const DOM_SID *sid, struct acct_info *info)
1266 {
1267         GROUP_MAP map;
1268         BOOL res;
1269
1270         become_root();
1271         res = get_domain_group_from_sid(*sid, &map);
1272         unbecome_root();
1273
1274         if (!res)
1275                 return False;
1276
1277         fstrcpy(info->acct_name, map.nt_name);
1278         fstrcpy(info->acct_desc, map.comment);
1279         sid_peek_rid(sid, &info->rid);
1280         return True;
1281 }
1282
1283 BOOL pdb_set_dom_grp_info(const DOM_SID *sid, const struct acct_info *info)
1284 {
1285         GROUP_MAP map;
1286
1287         if (!get_domain_group_from_sid(*sid, &map))
1288                 return False;
1289
1290         fstrcpy(map.nt_name, info->acct_name);
1291         fstrcpy(map.comment, info->acct_desc);
1292
1293         return NT_STATUS_IS_OK(pdb_update_group_mapping_entry(&map));
1294 }
1295
1296 /********************************************************************
1297  Really just intended to be called by smbd
1298 ********************************************************************/
1299
1300 NTSTATUS pdb_create_builtin_alias(uint32 rid)
1301 {
1302         DOM_SID sid;
1303         enum SID_NAME_USE type;
1304         gid_t gid;
1305         GROUP_MAP map;
1306         TALLOC_CTX *mem_ctx;
1307         NTSTATUS status;
1308         const char *name = NULL;
1309         fstring groupname;
1310
1311         DEBUG(10, ("Trying to create builtin alias %d\n", rid));
1312         
1313         if ( !sid_compose( &sid, &global_sid_Builtin, rid ) ) {
1314                 return NT_STATUS_NO_SUCH_ALIAS;
1315         }
1316         
1317         if ( (mem_ctx = talloc_new(NULL)) == NULL ) {
1318                 return NT_STATUS_NO_MEMORY;
1319         }
1320         
1321         if ( !lookup_sid(mem_ctx, &sid, NULL, &name, &type) ) {
1322                 TALLOC_FREE( mem_ctx );
1323                 return NT_STATUS_NO_SUCH_ALIAS;
1324         }
1325         
1326         /* validate RID so copy the name and move on */
1327                 
1328         fstrcpy( groupname, name );
1329         TALLOC_FREE( mem_ctx );
1330
1331         if (!winbind_allocate_gid(&gid)) {
1332                 DEBUG(3, ("pdb_create_builtin_alias: Could not get a gid out of winbind\n"));
1333                 return NT_STATUS_ACCESS_DENIED;
1334         }
1335
1336         DEBUG(10,("Creating alias %s with gid %d\n", name, gid));
1337
1338         map.gid = gid;
1339         sid_copy(&map.sid, &sid);
1340         map.sid_name_use = SID_NAME_ALIAS;
1341         fstrcpy(map.nt_name, name);
1342         fstrcpy(map.comment, "");
1343
1344         status = pdb_add_group_mapping_entry(&map);
1345
1346         if (!NT_STATUS_IS_OK(status)) {
1347                 DEBUG(0, ("pdb_create_builtin_alias: Could not add group mapping entry for alias %d "
1348                           "(%s)\n", rid, nt_errstr(status)));
1349         }
1350
1351         return status;
1352 }
1353
1354