r17468: To minimize the diff later on, pre-commit some changes independently: Change
[metze/samba/wip.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 NTSTATUS enum_group_mapping(const DOM_SID *sid,
42                                    enum SID_NAME_USE sid_name_use,
43                                    GROUP_MAP **pp_rmap,
44                                    size_t *p_num_entries, BOOL unix_only);
45 static BOOL group_map_remove(const DOM_SID *sid);
46                         
47 /****************************************************************************
48  Open the group mapping tdb.
49 ****************************************************************************/
50
51 static NTSTATUS init_group_mapping(void)
52 {
53         const char *vstring = "INFO/version";
54         int32 vers_id;
55         GROUP_MAP *map_table = NULL;
56         size_t num_entries = 0;
57         
58         if (tdb)
59                 return NT_STATUS_OK;
60                 
61         tdb = tdb_open_log(lock_path("group_mapping.tdb"), 0, TDB_DEFAULT,
62                            O_RDWR|O_CREAT, 0600);
63         if (!tdb) {
64                 DEBUG(0,("Failed to open group mapping database\n"));
65                 return map_nt_error_from_unix(errno);
66         }
67
68         /* handle a Samba upgrade */
69         tdb_lock_bystring(tdb, vstring);
70
71         /* Cope with byte-reversed older versions of the db. */
72         vers_id = tdb_fetch_int32(tdb, vstring);
73         if ((vers_id == DATABASE_VERSION_V1) || (IREV(vers_id) == DATABASE_VERSION_V1)) {
74                 /* Written on a bigendian machine with old fetch_int code. Save as le. */
75                 tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
76                 vers_id = DATABASE_VERSION_V2;
77         }
78
79         /* if its an unknown version we remove everthing in the db */
80         
81         if (vers_id != DATABASE_VERSION_V2) {
82                 tdb_traverse(tdb, tdb_traverse_delete_fn, NULL);
83                 tdb_store_int32(tdb, vstring, DATABASE_VERSION_V2);
84         }
85
86         tdb_unlock_bystring(tdb, vstring);
87
88         /* cleanup any map entries with a gid == -1 */
89         
90         if ( NT_STATUS_IS_OK(enum_group_mapping( NULL, SID_NAME_UNKNOWN,
91                                                  &map_table, &num_entries,
92                                                  False ))) {
93                 int i;
94                 
95                 for ( i=0; i<num_entries; i++ ) {
96                         if ( map_table[i].gid == -1 ) {
97                                 group_map_remove( &map_table[i].sid );
98                         }
99                 }
100                 
101                 SAFE_FREE( map_table );
102         }
103
104
105         return NT_STATUS_OK;
106 }
107
108 /****************************************************************************
109 ****************************************************************************/
110 static NTSTATUS add_mapping_entry(GROUP_MAP *map, int flag)
111 {
112         TDB_DATA kbuf, dbuf;
113         pstring key, buf;
114         fstring string_sid="";
115         int len;
116         NTSTATUS status;
117
118         status = init_group_mapping();
119         if(!NT_STATUS_IS_OK(status)) {
120                 DEBUG(0,("failed to initialize group mapping: %s\n",
121                          nt_errstr(status)));
122                 return status;
123         }
124         
125         sid_to_string(string_sid, &map->sid);
126
127         len = tdb_pack(buf, sizeof(buf), "ddff",
128                         map->gid, map->sid_name_use, map->nt_name, map->comment);
129
130         if (len > sizeof(buf))
131                 return NT_STATUS_NO_MEMORY;
132
133         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
134
135         kbuf.dsize = strlen(key)+1;
136         kbuf.dptr = key;
137         dbuf.dsize = len;
138         dbuf.dptr = buf;
139         if (tdb_store(tdb, kbuf, dbuf, flag) != 0) {
140                 return map_ntstatus_from_tdb(tdb);
141         }
142
143         return NT_STATUS_OK;
144 }
145
146 /****************************************************************************
147  Map a unix group to a newly created mapping
148 ****************************************************************************/
149 NTSTATUS map_unix_group(const struct group *grp, GROUP_MAP *pmap)
150 {
151         NTSTATUS status;
152         GROUP_MAP map;
153         const char *grpname, *dom, *name;
154         uint32 rid;
155
156         if (NT_STATUS_IS_OK(pdb_getgrgid(&map, grp->gr_gid))) {
157                 return NT_STATUS_GROUP_EXISTS;
158         }
159
160         map.gid = grp->gr_gid;
161         grpname = grp->gr_name;
162
163         if (lookup_name(tmp_talloc_ctx(), grpname, LOOKUP_NAME_ISOLATED,
164                         &dom, &name, NULL, NULL)) {
165
166                 const char *tmp = talloc_asprintf(
167                         tmp_talloc_ctx(), "Unix Group %s", grp->gr_name);
168
169                 DEBUG(5, ("%s exists as %s\\%s, retrying as \"%s\"\n",
170                           grpname, dom, name, tmp));
171                 grpname = tmp;
172         }
173
174         if (lookup_name(tmp_talloc_ctx(), grpname, LOOKUP_NAME_ISOLATED,
175                         NULL, NULL, NULL, NULL)) {
176                 DEBUG(3, ("\"%s\" exists, can't map it\n", grp->gr_name));
177                 return NT_STATUS_GROUP_EXISTS;
178         }
179
180         fstrcpy(map.nt_name, grpname);
181
182         if (pdb_rid_algorithm()) {
183                 rid = pdb_gid_to_group_rid( grp->gr_gid );
184         } else {
185                 if (!pdb_new_rid(&rid)) {
186                         DEBUG(3, ("Could not get a new RID for %s\n",
187                                   grp->gr_name));
188                         return NT_STATUS_ACCESS_DENIED;
189                 }
190         }
191
192         sid_compose(&map.sid, get_global_sam_sid(), rid);
193         map.sid_name_use = SID_NAME_DOM_GRP;
194         fstrcpy(map.comment, talloc_asprintf(tmp_talloc_ctx(), "Unix Group %s",
195                                              grp->gr_name));
196
197         status = pdb_add_group_mapping_entry(&map);
198         if (NT_STATUS_IS_OK(status)) {
199                 *pmap = map;
200         }
201         return status;
202 }
203
204 /****************************************************************************
205  Return the sid and the type of the unix group.
206 ****************************************************************************/
207
208 static NTSTATUS get_group_map_from_sid(const DOM_SID *sid, GROUP_MAP *map)
209 {
210         TDB_DATA kbuf, dbuf;
211         pstring key;
212         fstring string_sid;
213         int ret = 0;
214         NTSTATUS status;
215         
216         status = init_group_mapping();
217         if (!NT_STATUS_IS_OK(status)) {
218                 DEBUG(0, ("failed to initialize group mapping: %s\n",
219                           nt_errstr(status)));
220                 return status;
221         }
222
223         /* the key is the SID, retrieving is direct */
224
225         sid_to_string(string_sid, sid);
226         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
227
228         kbuf.dptr = key;
229         kbuf.dsize = strlen(key)+1;
230                 
231         dbuf = tdb_fetch(tdb, kbuf);
232         if (!dbuf.dptr) {
233                 return NT_STATUS_NOT_FOUND;
234         }
235
236         ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
237                                 &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
238
239         SAFE_FREE(dbuf.dptr);
240         
241         if ( ret == -1 ) {
242                 DEBUG(3,("get_group_map_from_sid: tdb_unpack failure\n"));
243                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
244         }
245         
246         sid_copy(&map->sid, sid);
247         
248         return NT_STATUS_OK;
249 }
250
251 /****************************************************************************
252  Return the sid and the type of the unix group.
253 ****************************************************************************/
254
255 static NTSTATUS get_group_map_from_gid(gid_t gid, GROUP_MAP *map)
256 {
257         TDB_DATA kbuf, dbuf, newkey;
258         fstring string_sid;
259         int ret;
260         NTSTATUS status;
261
262         status = init_group_mapping();
263         if (!NT_STATUS_IS_OK(status)) {
264                 DEBUG(0, ("failed to initialize group mapping: %s\n",
265                           nt_errstr(status)));
266                 return status;
267         }
268
269         /* we need to enumerate the TDB to find the GID */
270
271         for (kbuf = tdb_firstkey(tdb); 
272              kbuf.dptr; 
273              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
274
275                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
276                 
277                 dbuf = tdb_fetch(tdb, kbuf);
278                 if (!dbuf.dptr)
279                         continue;
280
281                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
282
283                 string_to_sid(&map->sid, string_sid);
284                 
285                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
286                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
287
288                 SAFE_FREE(dbuf.dptr);
289
290                 if ( ret == -1 ) {
291                         DEBUG(3,("get_group_map_from_gid: tdb_unpack failure\n"));
292                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
293                 }
294         
295                 if (gid==map->gid) {
296                         SAFE_FREE(kbuf.dptr);
297                         return NT_STATUS_OK;
298                 }
299         }
300
301         return NT_STATUS_NOT_FOUND;
302 }
303
304 /****************************************************************************
305  Return the sid and the type of the unix group.
306 ****************************************************************************/
307
308 static NTSTATUS get_group_map_from_ntname(const char *name, GROUP_MAP *map)
309 {
310         TDB_DATA kbuf, dbuf, newkey;
311         fstring string_sid;
312         int ret;
313         NTSTATUS status;
314
315         status = init_group_mapping();
316         if (!NT_STATUS_IS_OK(status)) {
317                 DEBUG(0, ("get_group_map_from_ntname: failed to initialize "
318                           "group mapping: %s\n", nt_errstr(status)));
319                 return status;
320         }
321
322         /* we need to enumerate the TDB to find the name */
323
324         for (kbuf = tdb_firstkey(tdb); 
325              kbuf.dptr; 
326              newkey = tdb_nextkey(tdb, kbuf), safe_free(kbuf.dptr), kbuf=newkey) {
327
328                 if (strncmp(kbuf.dptr, GROUP_PREFIX, strlen(GROUP_PREFIX)) != 0) continue;
329                 
330                 dbuf = tdb_fetch(tdb, kbuf);
331                 if (!dbuf.dptr)
332                         continue;
333
334                 fstrcpy(string_sid, kbuf.dptr+strlen(GROUP_PREFIX));
335
336                 string_to_sid(&map->sid, string_sid);
337                 
338                 ret = tdb_unpack(dbuf.dptr, dbuf.dsize, "ddff",
339                                  &map->gid, &map->sid_name_use, &map->nt_name, &map->comment);
340
341                 SAFE_FREE(dbuf.dptr);
342                 
343                 if ( ret == -1 ) {
344                         DEBUG(3,("get_group_map_from_ntname: tdb_unpack failure\n"));
345                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
346                 }
347
348                 if ( strequal(name, map->nt_name) ) {
349                         SAFE_FREE(kbuf.dptr);
350                         return NT_STATUS_OK;
351                 }
352         }
353
354         return NT_STATUS_NOT_FOUND;
355 }
356
357 /****************************************************************************
358  Remove a group mapping entry.
359 ****************************************************************************/
360
361 static BOOL group_map_remove(const DOM_SID *sid)
362 {
363         TDB_DATA kbuf, dbuf;
364         pstring key;
365         fstring string_sid;
366         
367         if(!NT_STATUS_IS_OK(init_group_mapping())) {
368                 DEBUG(0,("failed to initialize group mapping\n"));
369                 return(False);
370         }
371
372         /* the key is the SID, retrieving is direct */
373
374         sid_to_string(string_sid, sid);
375         slprintf(key, sizeof(key), "%s%s", GROUP_PREFIX, string_sid);
376
377         kbuf.dptr = key;
378         kbuf.dsize = strlen(key)+1;
379                 
380         dbuf = tdb_fetch(tdb, kbuf);
381         if (!dbuf.dptr)
382                 return False;
383         
384         SAFE_FREE(dbuf.dptr);
385
386         if(tdb_delete(tdb, kbuf) != TDB_SUCCESS)
387                 return False;
388
389         return True;
390 }
391
392 /****************************************************************************
393  Enumerate the group mapping.
394 ****************************************************************************/
395
396 static NTSTATUS enum_group_mapping(const DOM_SID *domsid,
397                                    enum SID_NAME_USE sid_name_use,
398                                    GROUP_MAP **pp_rmap,
399                                    size_t *p_num_entries, BOOL unix_only)
400 {
401         TDB_DATA kbuf, dbuf, newkey;
402         fstring string_sid;
403         GROUP_MAP map;
404         GROUP_MAP *mapt;
405         int ret;
406         size_t entries=0;
407         DOM_SID grpsid;
408         uint32 rid;
409         NTSTATUS status;
410
411         status = init_group_mapping();
412         if(!NT_STATUS_IS_OK(status)) {
413                 DEBUG(0, ("failed to initialize group mapping: %s\n",
414                           nt_errstr(status)));
415                 return status;
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 NT_STATUS_NO_MEMORY;
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 NT_STATUS_OK;
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 (!NT_STATUS_IS_OK(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(!NT_STATUS_IS_OK(init_group_mapping())) {
587                 DEBUG(0,("failed to initialize group mapping\n"));
588                 return NT_STATUS_ACCESS_DENIED;
589         }
590
591         if (!NT_STATUS_IS_OK(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(!NT_STATUS_IS_OK(init_group_mapping())) {
690                 DEBUG(0,("failed to initialize group mapping\n"));
691                 return NT_STATUS_ACCESS_DENIED;
692         }
693
694         if (!NT_STATUS_IS_OK(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 NTSTATUS get_domain_group_from_sid(const DOM_SID *sid, GROUP_MAP *map)
800 {
801         struct group *grp;
802         NTSTATUS status;
803
804         status = init_group_mapping();
805         if (!NT_STATUS_IS_OK(status)) {
806                 DEBUG(0, ("failed to initialize group mapping: %s\n",
807                           nt_errstr(status)));
808                 return status;
809         }
810
811         DEBUG(10, ("get_domain_group_from_sid\n"));
812
813         /* if the group is NOT in the database, it CAN NOT be a domain group */
814         
815         become_root();
816         status = pdb_getgrsid(map, sid);
817         unbecome_root();
818         
819         /* special case check for rid 513 */
820         
821         if ( !NT_STATUS_IS_OK(status) ) {
822                 uint32 rid;
823                 
824                 sid_peek_rid( sid, &rid );
825                 
826                 if ( rid == DOMAIN_GROUP_RID_USERS ) {
827                         fstrcpy( map->nt_name, "None" );
828                         fstrcpy( map->comment, "Ordinary Users" );
829                         sid_copy( &map->sid, sid );
830                         map->sid_name_use = SID_NAME_DOM_GRP;
831                         
832                         return NT_STATUS_OK;
833                 }
834                 
835                 return status;
836         }
837
838         DEBUG(10, ("get_domain_group_from_sid: SID found in the TDB\n"));
839
840         /* if it's not a domain group, continue */
841         if (map->sid_name_use!=SID_NAME_DOM_GRP) {
842                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
843         }
844
845         DEBUG(10, ("get_domain_group_from_sid: SID is a domain group\n"));
846         
847         if (map->gid==-1) {
848                 return NT_STATUS_NOT_FOUND;
849         }
850
851         DEBUG(10, ("get_domain_group_from_sid: SID is mapped to gid:%lu\n",(unsigned long)map->gid));
852         
853         grp = getgrgid(map->gid);
854         if ( !grp ) {
855                 DEBUG(10, ("get_domain_group_from_sid: gid DOESN'T exist in UNIX security\n"));
856                 return NT_STATUS_NOT_FOUND;
857         }
858
859         DEBUG(10, ("get_domain_group_from_sid: gid exists in UNIX security\n"));
860
861         return NT_STATUS_OK;
862 }
863
864 /****************************************************************************
865  Create a UNIX group on demand.
866 ****************************************************************************/
867
868 int smb_create_group(const char *unix_group, gid_t *new_gid)
869 {
870         pstring add_script;
871         int     ret = -1;
872         int     fd = 0;
873         
874         *new_gid = 0;
875
876         /* defer to scripts */
877         
878         if ( *lp_addgroup_script() ) {
879                 pstrcpy(add_script, lp_addgroup_script());
880                 pstring_sub(add_script, "%g", unix_group);
881                 ret = smbrun(add_script, &fd);
882                 DEBUG(ret ? 0 : 3,("smb_create_group: Running the command `%s' gave %d\n",add_script,ret));
883                 if (ret != 0)
884                         return ret;
885                         
886                 if (fd != 0) {
887                         fstring output;
888
889                         *new_gid = 0;
890                         if (read(fd, output, sizeof(output)) > 0) {
891                                 *new_gid = (gid_t)strtoul(output, NULL, 10);
892                         }
893                         
894                         close(fd);
895                 }
896
897         }
898
899         if (*new_gid == 0) {
900                 struct group *grp = getgrnam(unix_group);
901
902                 if (grp != NULL)
903                         *new_gid = grp->gr_gid;
904         }
905                         
906         return ret;     
907 }
908
909 /****************************************************************************
910  Delete a UNIX group on demand.
911 ****************************************************************************/
912
913 int smb_delete_group(const char *unix_group)
914 {
915         pstring del_script;
916         int ret;
917
918         /* defer to scripts */
919         
920         if ( *lp_delgroup_script() ) {
921                 pstrcpy(del_script, lp_delgroup_script());
922                 pstring_sub(del_script, "%g", unix_group);
923                 ret = smbrun(del_script,NULL);
924                 DEBUG(ret ? 0 : 3,("smb_delete_group: Running the command `%s' gave %d\n",del_script,ret));
925                 return ret;
926         }
927                 
928         return -1;
929 }
930
931 /****************************************************************************
932  Set a user's primary UNIX group.
933 ****************************************************************************/
934 int smb_set_primary_group(const char *unix_group, const char* unix_user)
935 {
936         pstring add_script;
937         int ret;
938
939         /* defer to scripts */
940         
941         if ( *lp_setprimarygroup_script() ) {
942                 pstrcpy(add_script, lp_setprimarygroup_script());
943                 all_string_sub(add_script, "%g", unix_group, sizeof(add_script));
944                 all_string_sub(add_script, "%u", unix_user, sizeof(add_script));
945                 ret = smbrun(add_script,NULL);
946                 flush_pwnam_cache();
947                 DEBUG(ret ? 0 : 3,("smb_set_primary_group: "
948                          "Running the command `%s' gave %d\n",add_script,ret));
949                 return ret;
950         }
951
952         return -1;
953 }
954
955 /****************************************************************************
956  Add a user to a UNIX group.
957 ****************************************************************************/
958
959 int smb_add_user_group(const char *unix_group, const char *unix_user)
960 {
961         pstring add_script;
962         int ret;
963
964         /* defer to scripts */
965         
966         if ( *lp_addusertogroup_script() ) {
967                 pstrcpy(add_script, lp_addusertogroup_script());
968                 pstring_sub(add_script, "%g", unix_group);
969                 pstring_sub(add_script, "%u", unix_user);
970                 ret = smbrun(add_script,NULL);
971                 DEBUG(ret ? 0 : 3,("smb_add_user_group: Running the command `%s' gave %d\n",add_script,ret));
972                 return ret;
973         }
974         
975         return -1;
976 }
977
978 /****************************************************************************
979  Delete a user from a UNIX group
980 ****************************************************************************/
981
982 int smb_delete_user_group(const char *unix_group, const char *unix_user)
983 {
984         pstring del_script;
985         int ret;
986
987         /* defer to scripts */
988         
989         if ( *lp_deluserfromgroup_script() ) {
990                 pstrcpy(del_script, lp_deluserfromgroup_script());
991                 pstring_sub(del_script, "%g", unix_group);
992                 pstring_sub(del_script, "%u", unix_user);
993                 ret = smbrun(del_script,NULL);
994                 DEBUG(ret ? 0 : 3,("smb_delete_user_group: Running the command `%s' gave %d\n",del_script,ret));
995                 return ret;
996         }
997         
998         return -1;
999 }
1000
1001
1002 NTSTATUS pdb_default_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1003                               const DOM_SID *sid)
1004 {
1005         return get_group_map_from_sid(sid, map);
1006 }
1007
1008 NTSTATUS pdb_default_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1009                                  gid_t gid)
1010 {
1011         return get_group_map_from_gid(gid, map);
1012 }
1013
1014 NTSTATUS pdb_default_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1015                                  const char *name)
1016 {
1017         return get_group_map_from_ntname(name, map);
1018 }
1019
1020 NTSTATUS pdb_default_add_group_mapping_entry(struct pdb_methods *methods,
1021                                                 GROUP_MAP *map)
1022 {
1023         return add_mapping_entry(map, TDB_INSERT);
1024 }
1025
1026 NTSTATUS pdb_default_update_group_mapping_entry(struct pdb_methods *methods,
1027                                                    GROUP_MAP *map)
1028 {
1029         return add_mapping_entry(map, TDB_REPLACE);
1030 }
1031
1032 NTSTATUS pdb_default_delete_group_mapping_entry(struct pdb_methods *methods,
1033                                                    DOM_SID sid)
1034 {
1035         return group_map_remove(&sid) ?
1036                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1037 }
1038
1039 NTSTATUS pdb_default_enum_group_mapping(struct pdb_methods *methods,
1040                                         const DOM_SID *sid,
1041                                         enum SID_NAME_USE sid_name_use,
1042                                         GROUP_MAP **pp_rmap,
1043                                         size_t *p_num_entries,
1044                                         BOOL unix_only)
1045 {
1046         return enum_group_mapping(sid, sid_name_use, pp_rmap, p_num_entries,
1047                                   unix_only);
1048 }
1049
1050 NTSTATUS pdb_default_create_alias(struct pdb_methods *methods,
1051                                   const char *name, uint32 *rid)
1052 {
1053         DOM_SID sid;
1054         enum SID_NAME_USE type;
1055         uint32 new_rid;
1056         gid_t gid;
1057         BOOL exists;
1058         GROUP_MAP map;
1059         TALLOC_CTX *mem_ctx;
1060         NTSTATUS status;
1061
1062         DEBUG(10, ("Trying to create alias %s\n", name));
1063
1064         mem_ctx = talloc_new(NULL);
1065         if (mem_ctx == NULL) {
1066                 return NT_STATUS_NO_MEMORY;
1067         }
1068
1069         exists = lookup_name(mem_ctx, name, LOOKUP_NAME_ISOLATED,
1070                              NULL, NULL, &sid, &type);
1071         TALLOC_FREE(mem_ctx);
1072
1073         if (exists) {
1074                 return NT_STATUS_ALIAS_EXISTS;
1075         }
1076
1077         if (!winbind_allocate_gid(&gid)) {
1078                 DEBUG(3, ("Could not get a gid out of winbind\n"));
1079                 return NT_STATUS_ACCESS_DENIED;
1080         }
1081
1082         if (!pdb_new_rid(&new_rid)) {
1083                 DEBUG(0, ("Could not allocate a RID -- wasted a gid :-(\n"));
1084                 return NT_STATUS_ACCESS_DENIED;
1085         }
1086
1087         DEBUG(10, ("Creating alias %s with gid %d and rid %d\n",
1088                    name, gid, new_rid));
1089
1090         sid_copy(&sid, get_global_sam_sid());
1091         sid_append_rid(&sid, new_rid);
1092
1093         map.gid = gid;
1094         sid_copy(&map.sid, &sid);
1095         map.sid_name_use = SID_NAME_ALIAS;
1096         fstrcpy(map.nt_name, name);
1097         fstrcpy(map.comment, "");
1098
1099         status = pdb_add_group_mapping_entry(&map);
1100
1101         if (!NT_STATUS_IS_OK(status)) {
1102                 DEBUG(0, ("Could not add group mapping entry for alias %s "
1103                           "(%s)\n", name, nt_errstr(status)));
1104                 return status;
1105         }
1106
1107         *rid = new_rid;
1108
1109         return NT_STATUS_OK;
1110 }
1111
1112 NTSTATUS pdb_default_delete_alias(struct pdb_methods *methods,
1113                                   const DOM_SID *sid)
1114 {
1115         return pdb_delete_group_mapping_entry(*sid);
1116 }
1117
1118 NTSTATUS pdb_default_get_aliasinfo(struct pdb_methods *methods,
1119                                    const DOM_SID *sid,
1120                                    struct acct_info *info)
1121 {
1122         GROUP_MAP map;
1123
1124         if (!NT_STATUS_IS_OK(pdb_getgrsid(&map, sid)))
1125                 return NT_STATUS_NO_SUCH_ALIAS;
1126
1127         if ((map.sid_name_use != SID_NAME_ALIAS) &&
1128             (map.sid_name_use != SID_NAME_WKN_GRP)) {
1129                 DEBUG(2, ("%s is a %s, expected an alias\n",
1130                           sid_string_static(sid),
1131                           sid_type_lookup(map.sid_name_use)));
1132                 return NT_STATUS_NO_SUCH_ALIAS;
1133         }
1134
1135         fstrcpy(info->acct_name, map.nt_name);
1136         fstrcpy(info->acct_desc, map.comment);
1137         sid_peek_rid(&map.sid, &info->rid);
1138         return NT_STATUS_OK;
1139 }
1140
1141 NTSTATUS pdb_default_set_aliasinfo(struct pdb_methods *methods,
1142                                    const DOM_SID *sid,
1143                                    struct acct_info *info)
1144 {
1145         GROUP_MAP map;
1146
1147         if (!NT_STATUS_IS_OK(pdb_getgrsid(&map, sid)))
1148                 return NT_STATUS_NO_SUCH_ALIAS;
1149
1150         fstrcpy(map.nt_name, info->acct_name);
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  Really just intended to be called by smbd
1216 ********************************************************************/
1217
1218 NTSTATUS pdb_create_builtin_alias(uint32 rid)
1219 {
1220         DOM_SID sid;
1221         enum SID_NAME_USE type;
1222         gid_t gid;
1223         GROUP_MAP map;
1224         TALLOC_CTX *mem_ctx;
1225         NTSTATUS status;
1226         const char *name = NULL;
1227         fstring groupname;
1228
1229         DEBUG(10, ("Trying to create builtin alias %d\n", rid));
1230         
1231         if ( !sid_compose( &sid, &global_sid_Builtin, rid ) ) {
1232                 return NT_STATUS_NO_SUCH_ALIAS;
1233         }
1234         
1235         if ( (mem_ctx = talloc_new(NULL)) == NULL ) {
1236                 return NT_STATUS_NO_MEMORY;
1237         }
1238         
1239         if ( !lookup_sid(mem_ctx, &sid, NULL, &name, &type) ) {
1240                 TALLOC_FREE( mem_ctx );
1241                 return NT_STATUS_NO_SUCH_ALIAS;
1242         }
1243         
1244         /* validate RID so copy the name and move on */
1245                 
1246         fstrcpy( groupname, name );
1247         TALLOC_FREE( mem_ctx );
1248
1249         if (!winbind_allocate_gid(&gid)) {
1250                 DEBUG(3, ("pdb_create_builtin_alias: Could not get a gid out of winbind\n"));
1251                 return NT_STATUS_ACCESS_DENIED;
1252         }
1253
1254         DEBUG(10,("Creating alias %s with gid %d\n", name, gid));
1255
1256         map.gid = gid;
1257         sid_copy(&map.sid, &sid);
1258         map.sid_name_use = SID_NAME_ALIAS;
1259         fstrcpy(map.nt_name, name);
1260         fstrcpy(map.comment, "");
1261
1262         status = pdb_add_group_mapping_entry(&map);
1263
1264         if (!NT_STATUS_IS_OK(status)) {
1265                 DEBUG(0, ("pdb_create_builtin_alias: Could not add group mapping entry for alias %d "
1266                           "(%s)\n", rid, nt_errstr(status)));
1267         }
1268
1269         return status;
1270 }
1271
1272