r4088: Get medieval on our ass about malloc.... :-). Take control of all our allocation
[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 one_alias_membership(const DOM_SID *member,
500                                      DOM_SID **sids, int *num)
501 {
502         fstring key, string_sid;
503         TDB_DATA kbuf, dbuf;
504         const char *p;
505
506         if (!init_group_mapping()) {
507                 DEBUG(0,("failed to initialize group mapping\n"));
508                 return NT_STATUS_ACCESS_DENIED;
509         }
510
511         sid_to_string(string_sid, member);
512         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
513
514         kbuf.dsize = strlen(key)+1;
515         kbuf.dptr = key;
516
517         dbuf = tdb_fetch(tdb, kbuf);
518
519         if (dbuf.dptr == NULL) {
520                 return NT_STATUS_OK;
521         }
522
523         p = dbuf.dptr;
524
525         while (next_token(&p, string_sid, " ", sizeof(string_sid))) {
526
527                 DOM_SID alias;
528
529                 if (!string_to_sid(&alias, string_sid))
530                         continue;
531
532                 add_sid_to_array_unique(&alias, sids, num);
533
534                 if (sids == NULL)
535                         return NT_STATUS_NO_MEMORY;
536         }
537
538         SAFE_FREE(dbuf.dptr);
539         return NT_STATUS_OK;
540 }
541
542 static NTSTATUS alias_memberships(const DOM_SID *members, int num_members,
543                                   DOM_SID **sids, int *num)
544 {
545         int i;
546
547         *num = 0;
548         *sids = NULL;
549
550         for (i=0; i<num_members; i++) {
551                 NTSTATUS status = one_alias_membership(&members[i], sids, num);
552                 if (!NT_STATUS_IS_OK(status))
553                         return status;
554         }
555         return NT_STATUS_OK;
556 }
557
558 static BOOL is_aliasmem(const DOM_SID *alias, const DOM_SID *member)
559 {
560         DOM_SID *sids;
561         int i, num;
562
563         /* This feels the wrong way round, but the on-disk data structure
564          * dictates it this way. */
565         if (!NT_STATUS_IS_OK(alias_memberships(member, 1, &sids, &num)))
566                 return False;
567
568         for (i=0; i<num; i++) {
569                 if (sid_compare(alias, &sids[i]) == 0) {
570                         SAFE_FREE(sids);
571                         return True;
572                 }
573         }
574         SAFE_FREE(sids);
575         return False;
576 }
577
578 static NTSTATUS add_aliasmem(const DOM_SID *alias, const DOM_SID *member)
579 {
580         GROUP_MAP map;
581         TDB_DATA kbuf, dbuf;
582         pstring key;
583         fstring string_sid;
584         char *new_memberstring;
585         int result;
586
587         if(!init_group_mapping()) {
588                 DEBUG(0,("failed to initialize group mapping\n"));
589                 return NT_STATUS_ACCESS_DENIED;
590         }
591
592         if (!get_group_map_from_sid(*alias, &map))
593                 return NT_STATUS_NO_SUCH_ALIAS;
594
595         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
596              (map.sid_name_use != SID_NAME_WKN_GRP) )
597                 return NT_STATUS_NO_SUCH_ALIAS;
598
599         if (is_aliasmem(alias, member))
600                 return NT_STATUS_MEMBER_IN_ALIAS;
601
602         sid_to_string(string_sid, member);
603         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, string_sid);
604
605         kbuf.dsize = strlen(key)+1;
606         kbuf.dptr = key;
607
608         dbuf = tdb_fetch(tdb, kbuf);
609
610         sid_to_string(string_sid, alias);
611
612         if (dbuf.dptr != NULL) {
613                 asprintf(&new_memberstring, "%s %s", (char *)(dbuf.dptr),
614                          string_sid);
615         } else {
616                 new_memberstring = SMB_STRDUP(string_sid);
617         }
618
619         if (new_memberstring == NULL)
620                 return NT_STATUS_NO_MEMORY;
621
622         SAFE_FREE(dbuf.dptr);
623         dbuf.dsize = strlen(new_memberstring)+1;
624         dbuf.dptr = new_memberstring;
625
626         result = tdb_store(tdb, kbuf, dbuf, 0);
627
628         SAFE_FREE(new_memberstring);
629
630         return (result == 0 ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED);
631 }
632
633 struct aliasmem_closure {
634         const DOM_SID *alias;
635         DOM_SID **sids;
636         int *num;
637 };
638
639 static int collect_aliasmem(TDB_CONTEXT *tdb_ctx, TDB_DATA key, TDB_DATA data,
640                             void *state)
641 {
642         struct aliasmem_closure *closure = (struct aliasmem_closure *)state;
643         const char *p;
644         fstring alias_string;
645
646         if (strncmp(key.dptr, MEMBEROF_PREFIX,
647                     strlen(MEMBEROF_PREFIX)) != 0)
648                 return 0;
649
650         p = data.dptr;
651
652         while (next_token(&p, alias_string, " ", sizeof(alias_string))) {
653
654                 DOM_SID alias, member;
655                 const char *member_string;
656                 
657
658                 if (!string_to_sid(&alias, alias_string))
659                         continue;
660
661                 if (sid_compare(closure->alias, &alias) != 0)
662                         continue;
663
664                 /* Ok, we found the alias we're looking for in the membership
665                  * list currently scanned. The key represents the alias
666                  * member. Add that. */
667
668                 member_string = strchr(key.dptr, '/');
669
670                 /* Above we tested for MEMBEROF_PREFIX which includes the
671                  * slash. */
672
673                 SMB_ASSERT(member_string != NULL);
674                 member_string += 1;
675
676                 if (!string_to_sid(&member, member_string))
677                         continue;
678                 
679                 add_sid_to_array(&member, closure->sids, closure->num);
680         }
681
682         return 0;
683 }
684
685 static NTSTATUS enum_aliasmem(const DOM_SID *alias, DOM_SID **sids, int *num)
686 {
687         GROUP_MAP map;
688         struct aliasmem_closure closure;
689
690         if(!init_group_mapping()) {
691                 DEBUG(0,("failed to initialize group mapping\n"));
692                 return NT_STATUS_ACCESS_DENIED;
693         }
694
695         if (!get_group_map_from_sid(*alias, &map))
696                 return NT_STATUS_NO_SUCH_ALIAS;
697
698         if ( (map.sid_name_use != SID_NAME_ALIAS) &&
699              (map.sid_name_use != SID_NAME_WKN_GRP) )
700                 return NT_STATUS_NO_SUCH_ALIAS;
701
702         *sids = NULL;
703         *num = 0;
704
705         closure.alias = alias;
706         closure.sids = sids;
707         closure.num = num;
708
709         tdb_traverse(tdb, collect_aliasmem, &closure);
710         return NT_STATUS_OK;
711 }
712
713 static NTSTATUS del_aliasmem(const DOM_SID *alias, const DOM_SID *member)
714 {
715         NTSTATUS result;
716         DOM_SID *sids;
717         int i, num;
718         BOOL found = False;
719         char *member_string;
720         TDB_DATA kbuf, dbuf;
721         pstring key;
722         fstring sid_string;
723
724         result = alias_memberships(member, 1, &sids, &num);
725
726         if (!NT_STATUS_IS_OK(result))
727                 return result;
728
729         for (i=0; i<num; i++) {
730                 if (sid_compare(&sids[i], alias) == 0) {
731                         found = True;
732                         break;
733                 }
734         }
735
736         if (!found) {
737                 SAFE_FREE(sids);
738                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
739         }
740
741         if (i < num)
742                 sids[i] = sids[num-1];
743
744         num -= 1;
745
746         sid_to_string(sid_string, member);
747         slprintf(key, sizeof(key), "%s%s", MEMBEROF_PREFIX, sid_string);
748
749         kbuf.dsize = strlen(key)+1;
750         kbuf.dptr = key;
751
752         if (num == 0)
753                 return tdb_delete(tdb, kbuf) == 0 ?
754                         NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
755
756         member_string = SMB_STRDUP("");
757
758         if (member_string == NULL) {
759                 SAFE_FREE(sids);
760                 return NT_STATUS_NO_MEMORY;
761         }
762
763         for (i=0; i<num; i++) {
764                 char *s = member_string;
765
766                 sid_to_string(sid_string, &sids[i]);
767                 asprintf(&member_string, "%s %s", s, sid_string);
768
769                 SAFE_FREE(s);
770                 if (member_string == NULL) {
771                         SAFE_FREE(sids);
772                         return NT_STATUS_NO_MEMORY;
773                 }
774         }
775
776         dbuf.dsize = strlen(member_string)+1;
777         dbuf.dptr = member_string;
778
779         result = tdb_store(tdb, kbuf, dbuf, 0) == 0 ?
780                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
781
782         SAFE_FREE(sids);
783         SAFE_FREE(member_string);
784
785         return result;
786 }
787
788 /*
789  *
790  * High level functions
791  * better to use them than the lower ones.
792  *
793  * we are checking if the group is in the mapping file
794  * and if the group is an existing unix group
795  *
796  */
797
798 /* get a domain group from it's SID */
799
800 BOOL get_domain_group_from_sid(DOM_SID sid, GROUP_MAP *map)
801 {
802         struct group *grp;
803         BOOL ret;
804         
805         if(!init_group_mapping()) {
806                 DEBUG(0,("failed to initialize group mapping\n"));
807                 return(False);
808         }
809
810         DEBUG(10, ("get_domain_group_from_sid\n"));
811
812         /* if the group is NOT in the database, it CAN NOT be a domain group */
813         
814         become_root();
815         ret = pdb_getgrsid(map, sid);
816         unbecome_root();
817         
818         if ( !ret ) 
819                 return False;
820
821         DEBUG(10, ("get_domain_group_from_sid: SID found in the TDB\n"));
822
823         /* if it's not a domain group, continue */
824         if (map->sid_name_use!=SID_NAME_DOM_GRP) {
825                 return False;
826         }
827
828         DEBUG(10, ("get_domain_group_from_sid: SID is a domain group\n"));
829         
830         if (map->gid==-1) {
831                 return False;
832         }
833
834         DEBUG(10, ("get_domain_group_from_sid: SID is mapped to gid:%lu\n",(unsigned long)map->gid));
835         
836         grp = getgrgid(map->gid);
837         if ( !grp ) {
838                 DEBUG(10, ("get_domain_group_from_sid: gid DOESN'T exist in UNIX security\n"));
839                 return False;
840         }
841
842         DEBUG(10, ("get_domain_group_from_sid: gid exists in UNIX security\n"));
843
844         return True;
845 }
846
847
848 /* get a local (alias) group from it's SID */
849
850 BOOL get_local_group_from_sid(DOM_SID *sid, GROUP_MAP *map)
851 {
852         BOOL ret;
853         
854         if(!init_group_mapping()) {
855                 DEBUG(0,("failed to initialize group mapping\n"));
856                 return(False);
857         }
858
859         /* The group is in the mapping table */
860         become_root();
861         ret = pdb_getgrsid(map, *sid);
862         unbecome_root();
863         
864         if ( !ret )
865                 return False;
866                 
867         if ( ( (map->sid_name_use != SID_NAME_ALIAS) &&
868                (map->sid_name_use != SID_NAME_WKN_GRP) )
869                 || (map->gid == -1)
870                 || (getgrgid(map->gid) == NULL) ) 
871         {
872                 return False;
873         }               
874                         
875 #if 1   /* JERRY */
876         /* local groups only exist in the group mapping DB so this 
877            is not necessary */
878            
879         else {
880                 /* the group isn't in the mapping table.
881                  * make one based on the unix information */
882                 uint32 alias_rid;
883                 struct group *grp;
884
885                 sid_peek_rid(sid, &alias_rid);
886                 map->gid=pdb_group_rid_to_gid(alias_rid);
887                 
888                 grp = getgrgid(map->gid);
889                 if ( !grp ) {
890                         DEBUG(3,("get_local_group_from_sid: No unix group for [%ul]\n", map->gid));
891                         return False;
892                 }
893
894                 map->sid_name_use=SID_NAME_ALIAS;
895
896                 fstrcpy(map->nt_name, grp->gr_name);
897                 fstrcpy(map->comment, "Local Unix Group");
898
899                 sid_copy(&map->sid, sid);
900         }
901 #endif
902
903         return True;
904 }
905
906 /* get a builtin group from it's SID */
907
908 BOOL get_builtin_group_from_sid(DOM_SID *sid, GROUP_MAP *map)
909 {
910         struct group *grp;
911         BOOL ret;
912         
913
914         if(!init_group_mapping()) {
915                 DEBUG(0,("failed to initialize group mapping\n"));
916                 return(False);
917         }
918
919         become_root();
920         ret = pdb_getgrsid(map, *sid);
921         unbecome_root();
922         
923         if ( !ret )
924                 return False;
925
926         if (map->sid_name_use!=SID_NAME_WKN_GRP) {
927                 return False;
928         }
929
930         if (map->gid==-1) {
931                 return False;
932         }
933
934         if ( (grp=getgrgid(map->gid)) == NULL) {
935                 return False;
936         }
937
938         return True;
939 }
940
941
942
943 /****************************************************************************
944 Returns a GROUP_MAP struct based on the gid.
945 ****************************************************************************/
946 BOOL get_group_from_gid(gid_t gid, GROUP_MAP *map)
947 {
948         struct group *grp;
949         BOOL ret;
950
951         if(!init_group_mapping()) {
952                 DEBUG(0,("failed to initialize group mapping\n"));
953                 return(False);
954         }
955
956         if ( (grp=getgrgid(gid)) == NULL)
957                 return False;
958
959         become_root();
960         ret = pdb_getgrgid(map, gid);
961         unbecome_root();
962         
963         if ( !ret ) {
964                 return False;
965         }
966         
967         return True;
968 }
969
970
971 /****************************************************************************
972  Create a UNIX group on demand.
973 ****************************************************************************/
974
975 int smb_create_group(char *unix_group, gid_t *new_gid)
976 {
977         pstring add_script;
978         int     ret = -1;
979         int     fd = 0;
980         
981         *new_gid = 0;
982
983         /* defer to scripts */
984         
985         if ( *lp_addgroup_script() ) {
986                 pstrcpy(add_script, lp_addgroup_script());
987                 pstring_sub(add_script, "%g", unix_group);
988                 ret = smbrun(add_script, (new_gid!=NULL) ? &fd : NULL);
989                 DEBUG(3,("smb_create_group: Running the command `%s' gave %d\n",add_script,ret));
990                 if (ret != 0)
991                         return ret;
992                         
993                 if (fd != 0) {
994                         fstring output;
995
996                         *new_gid = 0;
997                         if (read(fd, output, sizeof(output)) > 0) {
998                                 *new_gid = (gid_t)strtoul(output, NULL, 10);
999                         }
1000                         
1001                         close(fd);
1002                 }
1003
1004         } else if ( winbind_create_group( unix_group, NULL ) ) {
1005
1006                 DEBUG(3,("smb_create_group: winbindd created the group (%s)\n",
1007                         unix_group));
1008                 ret = 0;
1009         }
1010         
1011         if (*new_gid == 0) {
1012                 struct group *grp = getgrnam(unix_group);
1013
1014                 if (grp != NULL)
1015                         *new_gid = grp->gr_gid;
1016         }
1017                         
1018         return ret;     
1019 }
1020
1021 /****************************************************************************
1022  Delete a UNIX group on demand.
1023 ****************************************************************************/
1024
1025 int smb_delete_group(char *unix_group)
1026 {
1027         pstring del_script;
1028         int ret;
1029
1030         /* defer to scripts */
1031         
1032         if ( *lp_delgroup_script() ) {
1033                 pstrcpy(del_script, lp_delgroup_script());
1034                 pstring_sub(del_script, "%g", unix_group);
1035                 ret = smbrun(del_script,NULL);
1036                 DEBUG(3,("smb_delete_group: Running the command `%s' gave %d\n",del_script,ret));
1037                 return ret;
1038         }
1039
1040         if ( winbind_delete_group( unix_group ) ) {
1041                 DEBUG(3,("smb_delete_group: winbindd deleted the group (%s)\n",
1042                         unix_group));
1043                 return 0;
1044         }
1045                 
1046         return -1;
1047 }
1048
1049 /****************************************************************************
1050  Set a user's primary UNIX group.
1051 ****************************************************************************/
1052 int smb_set_primary_group(const char *unix_group, const char* unix_user)
1053 {
1054         pstring add_script;
1055         int ret;
1056
1057         /* defer to scripts */
1058         
1059         if ( *lp_setprimarygroup_script() ) {
1060                 pstrcpy(add_script, lp_setprimarygroup_script());
1061                 all_string_sub(add_script, "%g", unix_group, sizeof(add_script));
1062                 all_string_sub(add_script, "%u", unix_user, sizeof(add_script));
1063                 ret = smbrun(add_script,NULL);
1064                 DEBUG(3,("smb_set_primary_group: "
1065                          "Running the command `%s' gave %d\n",add_script,ret));
1066                 return ret;
1067         }
1068
1069         /* Try winbindd */
1070         
1071         if ( winbind_set_user_primary_group( unix_user, unix_group ) ) {
1072                 DEBUG(3,("smb_delete_group: winbindd set the group (%s) as the primary group for user (%s)\n",
1073                         unix_group, unix_user));
1074                 return 0;
1075         }               
1076         
1077         return -1;
1078 }
1079
1080 /****************************************************************************
1081  Add a user to a UNIX group.
1082 ****************************************************************************/
1083
1084 int smb_add_user_group(char *unix_group, char *unix_user)
1085 {
1086         pstring add_script;
1087         int ret;
1088
1089         /* defer to scripts */
1090         
1091         if ( *lp_addusertogroup_script() ) {
1092                 pstrcpy(add_script, lp_addusertogroup_script());
1093                 pstring_sub(add_script, "%g", unix_group);
1094                 pstring_sub(add_script, "%u", unix_user);
1095                 ret = smbrun(add_script,NULL);
1096                 DEBUG(3,("smb_add_user_group: Running the command `%s' gave %d\n",add_script,ret));
1097                 return ret;
1098         }
1099         
1100         /* Try winbindd */
1101
1102         if ( winbind_add_user_to_group( unix_user, unix_group ) ) {
1103                 DEBUG(3,("smb_delete_group: winbindd added user (%s) to the group (%s)\n",
1104                         unix_user, unix_group));
1105                 return -1;
1106         }       
1107         
1108         return -1;
1109 }
1110
1111 /****************************************************************************
1112  Delete a user from a UNIX group
1113 ****************************************************************************/
1114
1115 int smb_delete_user_group(const char *unix_group, const char *unix_user)
1116 {
1117         pstring del_script;
1118         int ret;
1119
1120         /* defer to scripts */
1121         
1122         if ( *lp_deluserfromgroup_script() ) {
1123                 pstrcpy(del_script, lp_deluserfromgroup_script());
1124                 pstring_sub(del_script, "%g", unix_group);
1125                 pstring_sub(del_script, "%u", unix_user);
1126                 ret = smbrun(del_script,NULL);
1127                 DEBUG(3,("smb_delete_user_group: Running the command `%s' gave %d\n",del_script,ret));
1128                 return ret;
1129         }
1130         
1131         /* Try winbindd */
1132
1133         if ( winbind_remove_user_from_group( unix_user, unix_group ) ) {
1134                 DEBUG(3,("smb_delete_group: winbindd removed user (%s) from the group (%s)\n",
1135                         unix_user, unix_group));
1136                 return 0;
1137         }
1138         
1139         return -1;
1140 }
1141
1142
1143 NTSTATUS pdb_default_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1144                                  DOM_SID sid)
1145 {
1146         return get_group_map_from_sid(sid, map) ?
1147                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1148 }
1149
1150 NTSTATUS pdb_default_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1151                                  gid_t gid)
1152 {
1153         return get_group_map_from_gid(gid, map) ?
1154                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1155 }
1156
1157 NTSTATUS pdb_default_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1158                                  const char *name)
1159 {
1160         return get_group_map_from_ntname(name, map) ?
1161                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1162 }
1163
1164 NTSTATUS pdb_default_add_group_mapping_entry(struct pdb_methods *methods,
1165                                                 GROUP_MAP *map)
1166 {
1167         return add_mapping_entry(map, TDB_INSERT) ?
1168                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1169 }
1170
1171 NTSTATUS pdb_default_update_group_mapping_entry(struct pdb_methods *methods,
1172                                                    GROUP_MAP *map)
1173 {
1174         return add_mapping_entry(map, TDB_REPLACE) ?
1175                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1176 }
1177
1178 NTSTATUS pdb_default_delete_group_mapping_entry(struct pdb_methods *methods,
1179                                                    DOM_SID sid)
1180 {
1181         return group_map_remove(sid) ?
1182                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1183 }
1184
1185 NTSTATUS pdb_default_enum_group_mapping(struct pdb_methods *methods,
1186                                            enum SID_NAME_USE sid_name_use,
1187                                            GROUP_MAP **rmap, int *num_entries,
1188                                            BOOL unix_only)
1189 {
1190         return enum_group_mapping(sid_name_use, rmap, num_entries, unix_only) ?
1191                 NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
1192 }
1193
1194 NTSTATUS pdb_default_find_alias(struct pdb_methods *methods,
1195                                 const char *name, DOM_SID *sid)
1196 {
1197         GROUP_MAP map;
1198
1199         if (!pdb_getgrnam(&map, name))
1200                 return NT_STATUS_NO_SUCH_ALIAS;
1201
1202         if ((map.sid_name_use != SID_NAME_WKN_GRP) &&
1203             (map.sid_name_use != SID_NAME_ALIAS))
1204                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
1205
1206         sid_copy(sid, &map.sid);
1207         return NT_STATUS_OK;
1208 }
1209
1210 NTSTATUS pdb_default_create_alias(struct pdb_methods *methods,
1211                                   const char *name, uint32 *rid)
1212 {
1213         DOM_SID sid;
1214         enum SID_NAME_USE type;
1215         uint32 new_rid;
1216         gid_t gid;
1217
1218         GROUP_MAP map;
1219
1220         if (lookup_name(get_global_sam_name(), name, &sid, &type))
1221                 return NT_STATUS_ALIAS_EXISTS;
1222
1223         if (!winbind_allocate_rid(&new_rid))
1224                 return NT_STATUS_ACCESS_DENIED;
1225
1226         sid_copy(&sid, get_global_sam_sid());
1227         sid_append_rid(&sid, new_rid);
1228
1229         /* Here we allocate the gid */
1230         if (!winbind_sid_to_gid(&gid, &sid)) {
1231                 DEBUG(0, ("Could not get gid for new RID\n"));
1232                 return NT_STATUS_ACCESS_DENIED;
1233         }
1234
1235         map.gid = gid;
1236         sid_copy(&map.sid, &sid);
1237         map.sid_name_use = SID_NAME_ALIAS;
1238         fstrcpy(map.nt_name, name);
1239         fstrcpy(map.comment, "");
1240
1241         if (!pdb_add_group_mapping_entry(&map)) {
1242                 DEBUG(0, ("Could not add group mapping entry for alias %s\n",
1243                           name));
1244                 return NT_STATUS_ACCESS_DENIED;
1245         }
1246
1247         *rid = new_rid;
1248
1249         return NT_STATUS_OK;
1250 }
1251
1252 NTSTATUS pdb_default_delete_alias(struct pdb_methods *methods,
1253                                   const DOM_SID *sid)
1254 {
1255         return pdb_delete_group_mapping_entry(*sid) ?
1256                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1257 }
1258
1259 NTSTATUS pdb_default_enum_aliases(struct pdb_methods *methods,
1260                                   const DOM_SID *sid,
1261                                   uint32 start_idx, uint32 max_entries,
1262                                   uint32 *num_aliases,
1263                                   struct acct_info **info)
1264 {
1265         extern DOM_SID global_sid_Builtin;
1266
1267         GROUP_MAP *map;
1268         int i, num_maps;
1269         enum SID_NAME_USE type = SID_NAME_UNKNOWN;
1270
1271         if (sid_compare(sid, get_global_sam_sid()) == 0)
1272                 type = SID_NAME_ALIAS;
1273
1274         if (sid_compare(sid, &global_sid_Builtin) == 0)
1275                 type = SID_NAME_WKN_GRP;
1276
1277         if (!pdb_enum_group_mapping(type, &map, &num_maps, False) ||
1278             (num_maps == 0)) {
1279                 *num_aliases = 0;
1280                 *info = NULL;
1281                 goto done;
1282         }
1283
1284         if (start_idx > num_maps) {
1285                 *num_aliases = 0;
1286                 *info = NULL;
1287                 goto done;
1288         }
1289
1290         *num_aliases = num_maps - start_idx;
1291
1292         if (*num_aliases > max_entries)
1293                 *num_aliases = max_entries;
1294
1295         *info = SMB_MALLOC_ARRAY(struct acct_info, *num_aliases);
1296
1297         for (i=0; i<*num_aliases; i++) {
1298                 fstrcpy((*info)[i].acct_name, map[i+start_idx].nt_name);
1299                 fstrcpy((*info)[i].acct_desc, map[i+start_idx].comment);
1300                 sid_peek_rid(&map[i].sid, &(*info)[i+start_idx].rid);
1301         }
1302
1303  done:
1304         SAFE_FREE(map);
1305         return NT_STATUS_OK;
1306 }
1307
1308 NTSTATUS pdb_default_get_aliasinfo(struct pdb_methods *methods,
1309                                    const DOM_SID *sid,
1310                                    struct acct_info *info)
1311 {
1312         GROUP_MAP map;
1313
1314         if (!pdb_getgrsid(&map, *sid))
1315                 return NT_STATUS_NO_SUCH_ALIAS;
1316
1317         fstrcpy(info->acct_name, map.nt_name);
1318         fstrcpy(info->acct_desc, map.comment);
1319         sid_peek_rid(&map.sid, &info->rid);
1320         return NT_STATUS_OK;
1321 }
1322
1323 NTSTATUS pdb_default_set_aliasinfo(struct pdb_methods *methods,
1324                                    const DOM_SID *sid,
1325                                    struct acct_info *info)
1326 {
1327         GROUP_MAP map;
1328
1329         if (!pdb_getgrsid(&map, *sid))
1330                 return NT_STATUS_NO_SUCH_ALIAS;
1331
1332         fstrcpy(map.comment, info->acct_desc);
1333
1334         if (!pdb_update_group_mapping_entry(&map))
1335                 return NT_STATUS_ACCESS_DENIED;
1336
1337         return NT_STATUS_OK;
1338 }
1339
1340 NTSTATUS pdb_default_add_aliasmem(struct pdb_methods *methods,
1341                                   const DOM_SID *alias, const DOM_SID *member)
1342 {
1343         return add_aliasmem(alias, member);
1344 }
1345
1346 NTSTATUS pdb_default_del_aliasmem(struct pdb_methods *methods,
1347                                   const DOM_SID *alias, const DOM_SID *member)
1348 {
1349         return del_aliasmem(alias, member);
1350 }
1351
1352 NTSTATUS pdb_default_enum_aliasmem(struct pdb_methods *methods,
1353                                    const DOM_SID *alias, DOM_SID **members,
1354                                    int *num_members)
1355 {
1356         return enum_aliasmem(alias, members, num_members);
1357 }
1358
1359 NTSTATUS pdb_default_alias_memberships(struct pdb_methods *methods,
1360                                        const DOM_SID *members,
1361                                        int num_members,
1362                                        DOM_SID **aliases, int *num)
1363 {
1364         return alias_memberships(members, num_members, aliases, num);
1365 }
1366
1367 /**********************************************************************
1368  no ops for passdb backends that don't implement group mapping
1369  *********************************************************************/
1370
1371 NTSTATUS pdb_nop_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1372                                  DOM_SID sid)
1373 {
1374         return NT_STATUS_UNSUCCESSFUL;
1375 }
1376
1377 NTSTATUS pdb_nop_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1378                                  gid_t gid)
1379 {
1380         return NT_STATUS_UNSUCCESSFUL;
1381 }
1382
1383 NTSTATUS pdb_nop_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1384                                  const char *name)
1385 {
1386         return NT_STATUS_UNSUCCESSFUL;
1387 }
1388
1389 NTSTATUS pdb_nop_add_group_mapping_entry(struct pdb_methods *methods,
1390                                                 GROUP_MAP *map)
1391 {
1392         return NT_STATUS_UNSUCCESSFUL;
1393 }
1394
1395 NTSTATUS pdb_nop_update_group_mapping_entry(struct pdb_methods *methods,
1396                                                    GROUP_MAP *map)
1397 {
1398         return NT_STATUS_UNSUCCESSFUL;
1399 }
1400
1401 NTSTATUS pdb_nop_delete_group_mapping_entry(struct pdb_methods *methods,
1402                                                    DOM_SID sid)
1403 {
1404         return NT_STATUS_UNSUCCESSFUL;
1405 }
1406
1407 NTSTATUS pdb_nop_enum_group_mapping(struct pdb_methods *methods,
1408                                            enum SID_NAME_USE sid_name_use,
1409                                            GROUP_MAP **rmap, int *num_entries,
1410                                            BOOL unix_only)
1411 {
1412         return NT_STATUS_UNSUCCESSFUL;
1413 }
1414