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