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