45a921f747c70e844c323346960bbc77b7201287
[kai/samba.git] / source3 / smbd / posix_acls.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB NT Security Descriptor / Unix permission conversion.
4    Copyright (C) Jeremy Allison 1994-2009.
5    Copyright (C) Andreas Gruenbacher 2002.
6    Copyright (C) Simo Sorce <idra@samba.org> 2009.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "smbd/smbd.h"
24 #include "system/filesys.h"
25 #include "../libcli/security/security.h"
26 #include "trans2.h"
27 #include "passdb/lookup_sid.h"
28 #include "auth.h"
29 #include "../librpc/gen_ndr/idmap.h"
30 #include "lib/param/loadparm.h"
31
32 extern const struct generic_mapping file_generic_mapping;
33
34 #undef  DBGC_CLASS
35 #define DBGC_CLASS DBGC_ACLS
36
37 /****************************************************************************
38  Data structures representing the internal ACE format.
39 ****************************************************************************/
40
41 enum ace_owner {UID_ACE, GID_ACE, WORLD_ACE};
42 enum ace_attribute {ALLOW_ACE, DENY_ACE}; /* Used for incoming NT ACLS. */
43
44 typedef struct canon_ace {
45         struct canon_ace *next, *prev;
46         SMB_ACL_TAG_T type;
47         mode_t perms; /* Only use S_I(R|W|X)USR mode bits here. */
48         struct dom_sid trustee;
49         enum ace_owner owner_type;
50         enum ace_attribute attr;
51         struct unixid unix_ug;
52         uint8_t ace_flags; /* From windows ACE entry. */
53 } canon_ace;
54
55 #define ALL_ACE_PERMS (S_IRUSR|S_IWUSR|S_IXUSR)
56
57 /*
58  * EA format of user.SAMBA_PAI (Samba_Posix_Acl_Interitance)
59  * attribute on disk - version 1.
60  * All values are little endian.
61  *
62  * |  1   |  1   |   2         |         2           |  ....
63  * +------+------+-------------+---------------------+-------------+--------------------+
64  * | vers | flag | num_entries | num_default_entries | ..entries.. | default_entries... |
65  * +------+------+-------------+---------------------+-------------+--------------------+
66  *
67  * Entry format is :
68  *
69  * |  1   |       4           |
70  * +------+-------------------+
71  * | value|  uid/gid or world |
72  * | type |  value            |
73  * +------+-------------------+
74  *
75  * Version 2 format. Stores extra Windows metadata about an ACL.
76  *
77  * |  1   |  2       |   2         |         2           |  ....
78  * +------+----------+-------------+---------------------+-------------+--------------------+
79  * | vers | ace      | num_entries | num_default_entries | ..entries.. | default_entries... |
80  * |   2  |  type    |             |                     |             |                    |
81  * +------+----------+-------------+---------------------+-------------+--------------------+
82  *
83  * Entry format is :
84  *
85  * |  1   |  1   |       4           |
86  * +------+------+-------------------+
87  * | ace  | value|  uid/gid or world |
88  * | flag | type |  value            |
89  * +------+-------------------+------+
90  *
91  */
92
93 #define PAI_VERSION_OFFSET                      0
94
95 #define PAI_V1_FLAG_OFFSET                      1
96 #define PAI_V1_NUM_ENTRIES_OFFSET               2
97 #define PAI_V1_NUM_DEFAULT_ENTRIES_OFFSET       4
98 #define PAI_V1_ENTRIES_BASE                     6
99 #define PAI_V1_ACL_FLAG_PROTECTED               0x1
100 #define PAI_V1_ENTRY_LENGTH                     5
101
102 #define PAI_V1_VERSION                          1
103
104 #define PAI_V2_TYPE_OFFSET                      1
105 #define PAI_V2_NUM_ENTRIES_OFFSET               3
106 #define PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET       5
107 #define PAI_V2_ENTRIES_BASE                     7
108 #define PAI_V2_ENTRY_LENGTH                     6
109
110 #define PAI_V2_VERSION                          2
111
112 /*
113  * In memory format of user.SAMBA_PAI attribute.
114  */
115
116 struct pai_entry {
117         struct pai_entry *next, *prev;
118         uint8_t ace_flags;
119         enum ace_owner owner_type;
120         struct unixid unix_ug;
121 };
122
123 struct pai_val {
124         uint16_t sd_type;
125         unsigned int num_entries;
126         struct pai_entry *entry_list;
127         unsigned int num_def_entries;
128         struct pai_entry *def_entry_list;
129 };
130
131 /************************************************************************
132  Return a uint32 of the pai_entry principal.
133 ************************************************************************/
134
135 static uint32_t get_pai_entry_val(struct pai_entry *paie)
136 {
137         switch (paie->owner_type) {
138                 case UID_ACE:
139                         DEBUG(10,("get_pai_entry_val: uid = %u\n", (unsigned int)paie->unix_ug.id ));
140                         return (uint32_t)paie->unix_ug.id;
141                 case GID_ACE:
142                         DEBUG(10,("get_pai_entry_val: gid = %u\n", (unsigned int)paie->unix_ug.id ));
143                         return (uint32_t)paie->unix_ug.id;
144                 case WORLD_ACE:
145                 default:
146                         DEBUG(10,("get_pai_entry_val: world ace\n"));
147                         return (uint32_t)-1;
148         }
149 }
150
151 /************************************************************************
152  Return a uint32 of the entry principal.
153 ************************************************************************/
154
155 static uint32_t get_entry_val(canon_ace *ace_entry)
156 {
157         switch (ace_entry->owner_type) {
158                 case UID_ACE:
159                         DEBUG(10,("get_entry_val: uid = %u\n", (unsigned int)ace_entry->unix_ug.id ));
160                         return (uint32_t)ace_entry->unix_ug.id;
161                 case GID_ACE:
162                         DEBUG(10,("get_entry_val: gid = %u\n", (unsigned int)ace_entry->unix_ug.id ));
163                         return (uint32_t)ace_entry->unix_ug.id;
164                 case WORLD_ACE:
165                 default:
166                         DEBUG(10,("get_entry_val: world ace\n"));
167                         return (uint32_t)-1;
168         }
169 }
170
171 /************************************************************************
172  Create the on-disk format (always v2 now). Caller must free.
173 ************************************************************************/
174
175 static char *create_pai_buf_v2(canon_ace *file_ace_list,
176                                 canon_ace *dir_ace_list,
177                                 uint16_t sd_type,
178                                 size_t *store_size)
179 {
180         char *pai_buf = NULL;
181         canon_ace *ace_list = NULL;
182         char *entry_offset = NULL;
183         unsigned int num_entries = 0;
184         unsigned int num_def_entries = 0;
185         unsigned int i;
186
187         for (ace_list = file_ace_list; ace_list; ace_list = ace_list->next) {
188                 num_entries++;
189         }
190
191         for (ace_list = dir_ace_list; ace_list; ace_list = ace_list->next) {
192                 num_def_entries++;
193         }
194
195         DEBUG(10,("create_pai_buf_v2: num_entries = %u, num_def_entries = %u\n", num_entries, num_def_entries ));
196
197         *store_size = PAI_V2_ENTRIES_BASE +
198                 ((num_entries + num_def_entries)*PAI_V2_ENTRY_LENGTH);
199
200         pai_buf = talloc_array(talloc_tos(), char, *store_size);
201         if (!pai_buf) {
202                 return NULL;
203         }
204
205         /* Set up the header. */
206         memset(pai_buf, '\0', PAI_V2_ENTRIES_BASE);
207         SCVAL(pai_buf,PAI_VERSION_OFFSET,PAI_V2_VERSION);
208         SSVAL(pai_buf,PAI_V2_TYPE_OFFSET, sd_type);
209         SSVAL(pai_buf,PAI_V2_NUM_ENTRIES_OFFSET,num_entries);
210         SSVAL(pai_buf,PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET,num_def_entries);
211
212         DEBUG(10,("create_pai_buf_v2: sd_type = 0x%x\n",
213                         (unsigned int)sd_type ));
214
215         entry_offset = pai_buf + PAI_V2_ENTRIES_BASE;
216
217         i = 0;
218         for (ace_list = file_ace_list; ace_list; ace_list = ace_list->next) {
219                 uint8_t type_val = (uint8_t)ace_list->owner_type;
220                 uint32_t entry_val = get_entry_val(ace_list);
221
222                 SCVAL(entry_offset,0,ace_list->ace_flags);
223                 SCVAL(entry_offset,1,type_val);
224                 SIVAL(entry_offset,2,entry_val);
225                 DEBUG(10,("create_pai_buf_v2: entry %u [0x%x] [0x%x] [0x%x]\n",
226                         i,
227                         (unsigned int)ace_list->ace_flags,
228                         (unsigned int)type_val,
229                         (unsigned int)entry_val ));
230                 i++;
231                 entry_offset += PAI_V2_ENTRY_LENGTH;
232         }
233
234         for (ace_list = dir_ace_list; ace_list; ace_list = ace_list->next) {
235                 uint8_t type_val = (uint8_t)ace_list->owner_type;
236                 uint32_t entry_val = get_entry_val(ace_list);
237
238                 SCVAL(entry_offset,0,ace_list->ace_flags);
239                 SCVAL(entry_offset,1,type_val);
240                 SIVAL(entry_offset,2,entry_val);
241                 DEBUG(10,("create_pai_buf_v2: entry %u [0x%x] [0x%x] [0x%x]\n",
242                         i,
243                         (unsigned int)ace_list->ace_flags,
244                         (unsigned int)type_val,
245                         (unsigned int)entry_val ));
246                 i++;
247                 entry_offset += PAI_V2_ENTRY_LENGTH;
248         }
249
250         return pai_buf;
251 }
252
253 /************************************************************************
254  Store the user.SAMBA_PAI attribute on disk.
255 ************************************************************************/
256
257 static void store_inheritance_attributes(files_struct *fsp,
258                                         canon_ace *file_ace_list,
259                                         canon_ace *dir_ace_list,
260                                         uint16_t sd_type)
261 {
262         int ret;
263         size_t store_size;
264         char *pai_buf;
265
266         if (!lp_map_acl_inherit(SNUM(fsp->conn))) {
267                 return;
268         }
269
270         pai_buf = create_pai_buf_v2(file_ace_list, dir_ace_list,
271                                 sd_type, &store_size);
272
273         if (fsp->fh->fd != -1) {
274                 ret = SMB_VFS_FSETXATTR(fsp, SAMBA_POSIX_INHERITANCE_EA_NAME,
275                                 pai_buf, store_size, 0);
276         } else {
277                 ret = SMB_VFS_SETXATTR(fsp->conn, fsp->fsp_name->base_name,
278                                        SAMBA_POSIX_INHERITANCE_EA_NAME,
279                                        pai_buf, store_size, 0);
280         }
281
282         TALLOC_FREE(pai_buf);
283
284         DEBUG(10,("store_inheritance_attribute: type 0x%x for file %s\n",
285                 (unsigned int)sd_type,
286                 fsp_str_dbg(fsp)));
287
288         if (ret == -1 && !no_acl_syscall_error(errno)) {
289                 DEBUG(1,("store_inheritance_attribute: Error %s\n", strerror(errno) ));
290         }
291 }
292
293 /************************************************************************
294  Delete the in memory inheritance info.
295 ************************************************************************/
296
297 static void free_inherited_info(struct pai_val *pal)
298 {
299         if (pal) {
300                 struct pai_entry *paie, *paie_next;
301                 for (paie = pal->entry_list; paie; paie = paie_next) {
302                         paie_next = paie->next;
303                         TALLOC_FREE(paie);
304                 }
305                 for (paie = pal->def_entry_list; paie; paie = paie_next) {
306                         paie_next = paie->next;
307                         TALLOC_FREE(paie);
308                 }
309                 TALLOC_FREE(pal);
310         }
311 }
312
313 /************************************************************************
314  Get any stored ACE flags.
315 ************************************************************************/
316
317 static uint16_t get_pai_flags(struct pai_val *pal, canon_ace *ace_entry, bool default_ace)
318 {
319         struct pai_entry *paie;
320
321         if (!pal) {
322                 return 0;
323         }
324
325         /* If the entry exists it is inherited. */
326         for (paie = (default_ace ? pal->def_entry_list : pal->entry_list); paie; paie = paie->next) {
327                 if (ace_entry->owner_type == paie->owner_type &&
328                                 get_entry_val(ace_entry) == get_pai_entry_val(paie))
329                         return paie->ace_flags;
330         }
331         return 0;
332 }
333
334 /************************************************************************
335  Ensure an attribute just read is valid - v1.
336 ************************************************************************/
337
338 static bool check_pai_ok_v1(const char *pai_buf, size_t pai_buf_data_size)
339 {
340         uint16 num_entries;
341         uint16 num_def_entries;
342
343         if (pai_buf_data_size < PAI_V1_ENTRIES_BASE) {
344                 /* Corrupted - too small. */
345                 return false;
346         }
347
348         if (CVAL(pai_buf,PAI_VERSION_OFFSET) != PAI_V1_VERSION) {
349                 return false;
350         }
351
352         num_entries = SVAL(pai_buf,PAI_V1_NUM_ENTRIES_OFFSET);
353         num_def_entries = SVAL(pai_buf,PAI_V1_NUM_DEFAULT_ENTRIES_OFFSET);
354
355         /* Check the entry lists match. */
356         /* Each entry is 5 bytes (type plus 4 bytes of uid or gid). */
357
358         if (((num_entries + num_def_entries)*PAI_V1_ENTRY_LENGTH) +
359                         PAI_V1_ENTRIES_BASE != pai_buf_data_size) {
360                 return false;
361         }
362
363         return true;
364 }
365
366 /************************************************************************
367  Ensure an attribute just read is valid - v2.
368 ************************************************************************/
369
370 static bool check_pai_ok_v2(const char *pai_buf, size_t pai_buf_data_size)
371 {
372         uint16 num_entries;
373         uint16 num_def_entries;
374
375         if (pai_buf_data_size < PAI_V2_ENTRIES_BASE) {
376                 /* Corrupted - too small. */
377                 return false;
378         }
379
380         if (CVAL(pai_buf,PAI_VERSION_OFFSET) != PAI_V2_VERSION) {
381                 return false;
382         }
383
384         num_entries = SVAL(pai_buf,PAI_V2_NUM_ENTRIES_OFFSET);
385         num_def_entries = SVAL(pai_buf,PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET);
386
387         /* Check the entry lists match. */
388         /* Each entry is 6 bytes (flags + type + 4 bytes of uid or gid). */
389
390         if (((num_entries + num_def_entries)*PAI_V2_ENTRY_LENGTH) +
391                         PAI_V2_ENTRIES_BASE != pai_buf_data_size) {
392                 return false;
393         }
394
395         return true;
396 }
397
398 /************************************************************************
399  Decode the owner.
400 ************************************************************************/
401
402 static bool get_pai_owner_type(struct pai_entry *paie, const char *entry_offset)
403 {
404         paie->owner_type = (enum ace_owner)CVAL(entry_offset,0);
405         switch( paie->owner_type) {
406                 case UID_ACE:
407                         paie->unix_ug.type = ID_TYPE_UID;
408                         paie->unix_ug.id = (uid_t)IVAL(entry_offset,1);
409                         DEBUG(10,("get_pai_owner_type: uid = %u\n",
410                                 (unsigned int)paie->unix_ug.id ));
411                         break;
412                 case GID_ACE:
413                         paie->unix_ug.type = ID_TYPE_GID;
414                         paie->unix_ug.id = (gid_t)IVAL(entry_offset,1);
415                         DEBUG(10,("get_pai_owner_type: gid = %u\n",
416                                 (unsigned int)paie->unix_ug.id ));
417                         break;
418                 case WORLD_ACE:
419                         paie->unix_ug.type = ID_TYPE_NOT_SPECIFIED;
420                         paie->unix_ug.id = -1;
421                         DEBUG(10,("get_pai_owner_type: world ace\n"));
422                         break;
423                 default:
424                         DEBUG(10,("get_pai_owner_type: unknown type %u\n",
425                                 (unsigned int)paie->owner_type ));
426                         return false;
427         }
428         return true;
429 }
430
431 /************************************************************************
432  Process v2 entries.
433 ************************************************************************/
434
435 static const char *create_pai_v1_entries(struct pai_val *paiv,
436                                 const char *entry_offset,
437                                 bool def_entry)
438 {
439         int i;
440
441         for (i = 0; i < paiv->num_entries; i++) {
442                 struct pai_entry *paie = talloc(talloc_tos(), struct pai_entry);
443                 if (!paie) {
444                         return NULL;
445                 }
446
447                 paie->ace_flags = SEC_ACE_FLAG_INHERITED_ACE;
448                 if (!get_pai_owner_type(paie, entry_offset)) {
449                         TALLOC_FREE(paie);
450                         return NULL;
451                 }
452
453                 if (!def_entry) {
454                         DLIST_ADD(paiv->entry_list, paie);
455                 } else {
456                         DLIST_ADD(paiv->def_entry_list, paie);
457                 }
458                 entry_offset += PAI_V1_ENTRY_LENGTH;
459         }
460         return entry_offset;
461 }
462
463 /************************************************************************
464  Convert to in-memory format from version 1.
465 ************************************************************************/
466
467 static struct pai_val *create_pai_val_v1(const char *buf, size_t size)
468 {
469         const char *entry_offset;
470         struct pai_val *paiv = NULL;
471
472         if (!check_pai_ok_v1(buf, size)) {
473                 return NULL;
474         }
475
476         paiv = talloc(talloc_tos(), struct pai_val);
477         if (!paiv) {
478                 return NULL;
479         }
480
481         memset(paiv, '\0', sizeof(struct pai_val));
482
483         paiv->sd_type = (CVAL(buf,PAI_V1_FLAG_OFFSET) == PAI_V1_ACL_FLAG_PROTECTED) ?
484                         SEC_DESC_DACL_PROTECTED : 0;
485
486         paiv->num_entries = SVAL(buf,PAI_V1_NUM_ENTRIES_OFFSET);
487         paiv->num_def_entries = SVAL(buf,PAI_V1_NUM_DEFAULT_ENTRIES_OFFSET);
488
489         entry_offset = buf + PAI_V1_ENTRIES_BASE;
490
491         DEBUG(10,("create_pai_val: num_entries = %u, num_def_entries = %u\n",
492                         paiv->num_entries, paiv->num_def_entries ));
493
494         entry_offset = create_pai_v1_entries(paiv, entry_offset, false);
495         if (entry_offset == NULL) {
496                 free_inherited_info(paiv);
497                 return NULL;
498         }
499         entry_offset = create_pai_v1_entries(paiv, entry_offset, true);
500         if (entry_offset == NULL) {
501                 free_inherited_info(paiv);
502                 return NULL;
503         }
504
505         return paiv;
506 }
507
508 /************************************************************************
509  Process v2 entries.
510 ************************************************************************/
511
512 static const char *create_pai_v2_entries(struct pai_val *paiv,
513                                 unsigned int num_entries,
514                                 const char *entry_offset,
515                                 bool def_entry)
516 {
517         unsigned int i;
518
519         for (i = 0; i < num_entries; i++) {
520                 struct pai_entry *paie = talloc(talloc_tos(), struct pai_entry);
521                 if (!paie) {
522                         return NULL;
523                 }
524
525                 paie->ace_flags = CVAL(entry_offset,0);
526
527                 if (!get_pai_owner_type(paie, entry_offset+1)) {
528                         TALLOC_FREE(paie);
529                         return NULL;
530                 }
531                 if (!def_entry) {
532                         DLIST_ADD(paiv->entry_list, paie);
533                 } else {
534                         DLIST_ADD(paiv->def_entry_list, paie);
535                 }
536                 entry_offset += PAI_V2_ENTRY_LENGTH;
537         }
538         return entry_offset;
539 }
540
541 /************************************************************************
542  Convert to in-memory format from version 2.
543 ************************************************************************/
544
545 static struct pai_val *create_pai_val_v2(const char *buf, size_t size)
546 {
547         const char *entry_offset;
548         struct pai_val *paiv = NULL;
549
550         if (!check_pai_ok_v2(buf, size)) {
551                 return NULL;
552         }
553
554         paiv = talloc(talloc_tos(), struct pai_val);
555         if (!paiv) {
556                 return NULL;
557         }
558
559         memset(paiv, '\0', sizeof(struct pai_val));
560
561         paiv->sd_type = SVAL(buf,PAI_V2_TYPE_OFFSET);
562
563         paiv->num_entries = SVAL(buf,PAI_V2_NUM_ENTRIES_OFFSET);
564         paiv->num_def_entries = SVAL(buf,PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET);
565
566         entry_offset = buf + PAI_V2_ENTRIES_BASE;
567
568         DEBUG(10,("create_pai_val_v2: sd_type = 0x%x num_entries = %u, num_def_entries = %u\n",
569                         (unsigned int)paiv->sd_type,
570                         paiv->num_entries, paiv->num_def_entries ));
571
572         entry_offset = create_pai_v2_entries(paiv, paiv->num_entries,
573                                 entry_offset, false);
574         if (entry_offset == NULL) {
575                 free_inherited_info(paiv);
576                 return NULL;
577         }
578         entry_offset = create_pai_v2_entries(paiv, paiv->num_def_entries,
579                                 entry_offset, true);
580         if (entry_offset == NULL) {
581                 free_inherited_info(paiv);
582                 return NULL;
583         }
584
585         return paiv;
586 }
587
588 /************************************************************************
589  Convert to in-memory format - from either version 1 or 2.
590 ************************************************************************/
591
592 static struct pai_val *create_pai_val(const char *buf, size_t size)
593 {
594         if (size < 1) {
595                 return NULL;
596         }
597         if (CVAL(buf,PAI_VERSION_OFFSET) == PAI_V1_VERSION) {
598                 return create_pai_val_v1(buf, size);
599         } else if (CVAL(buf,PAI_VERSION_OFFSET) == PAI_V2_VERSION) {
600                 return create_pai_val_v2(buf, size);
601         } else {
602                 return NULL;
603         }
604 }
605
606 /************************************************************************
607  Load the user.SAMBA_PAI attribute.
608 ************************************************************************/
609
610 static struct pai_val *fload_inherited_info(files_struct *fsp)
611 {
612         char *pai_buf;
613         size_t pai_buf_size = 1024;
614         struct pai_val *paiv = NULL;
615         ssize_t ret;
616
617         if (!lp_map_acl_inherit(SNUM(fsp->conn))) {
618                 return NULL;
619         }
620
621         if ((pai_buf = talloc_array(talloc_tos(), char, pai_buf_size)) == NULL) {
622                 return NULL;
623         }
624
625         do {
626                 if (fsp->fh->fd != -1) {
627                         ret = SMB_VFS_FGETXATTR(fsp, SAMBA_POSIX_INHERITANCE_EA_NAME,
628                                         pai_buf, pai_buf_size);
629                 } else {
630                         ret = SMB_VFS_GETXATTR(fsp->conn,
631                                                fsp->fsp_name->base_name,
632                                                SAMBA_POSIX_INHERITANCE_EA_NAME,
633                                                pai_buf, pai_buf_size);
634                 }
635
636                 if (ret == -1) {
637                         if (errno != ERANGE) {
638                                 break;
639                         }
640                         /* Buffer too small - enlarge it. */
641                         pai_buf_size *= 2;
642                         TALLOC_FREE(pai_buf);
643                         if (pai_buf_size > 1024*1024) {
644                                 return NULL; /* Limit malloc to 1mb. */
645                         }
646                         if ((pai_buf = talloc_array(talloc_tos(), char, pai_buf_size)) == NULL)
647                                 return NULL;
648                 }
649         } while (ret == -1);
650
651         DEBUG(10,("load_inherited_info: ret = %lu for file %s\n",
652                   (unsigned long)ret, fsp_str_dbg(fsp)));
653
654         if (ret == -1) {
655                 /* No attribute or not supported. */
656 #if defined(ENOATTR)
657                 if (errno != ENOATTR)
658                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
659 #else
660                 if (errno != ENOSYS)
661                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
662 #endif
663                 TALLOC_FREE(pai_buf);
664                 return NULL;
665         }
666
667         paiv = create_pai_val(pai_buf, ret);
668
669         if (paiv) {
670                 DEBUG(10,("load_inherited_info: ACL type is 0x%x for file %s\n",
671                           (unsigned int)paiv->sd_type, fsp_str_dbg(fsp)));
672         }
673
674         TALLOC_FREE(pai_buf);
675         return paiv;
676 }
677
678 /************************************************************************
679  Load the user.SAMBA_PAI attribute.
680 ************************************************************************/
681
682 static struct pai_val *load_inherited_info(const struct connection_struct *conn,
683                                            const char *fname)
684 {
685         char *pai_buf;
686         size_t pai_buf_size = 1024;
687         struct pai_val *paiv = NULL;
688         ssize_t ret;
689
690         if (!lp_map_acl_inherit(SNUM(conn))) {
691                 return NULL;
692         }
693
694         if ((pai_buf = talloc_array(talloc_tos(), char, pai_buf_size)) == NULL) {
695                 return NULL;
696         }
697
698         do {
699                 ret = SMB_VFS_GETXATTR(conn, fname,
700                                        SAMBA_POSIX_INHERITANCE_EA_NAME,
701                                        pai_buf, pai_buf_size);
702
703                 if (ret == -1) {
704                         if (errno != ERANGE) {
705                                 break;
706                         }
707                         /* Buffer too small - enlarge it. */
708                         pai_buf_size *= 2;
709                         TALLOC_FREE(pai_buf);
710                         if (pai_buf_size > 1024*1024) {
711                                 return NULL; /* Limit malloc to 1mb. */
712                         }
713                         if ((pai_buf = talloc_array(talloc_tos(), char, pai_buf_size)) == NULL)
714                                 return NULL;
715                 }
716         } while (ret == -1);
717
718         DEBUG(10,("load_inherited_info: ret = %lu for file %s\n", (unsigned long)ret, fname));
719
720         if (ret == -1) {
721                 /* No attribute or not supported. */
722 #if defined(ENOATTR)
723                 if (errno != ENOATTR)
724                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
725 #else
726                 if (errno != ENOSYS)
727                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
728 #endif
729                 TALLOC_FREE(pai_buf);
730                 return NULL;
731         }
732
733         paiv = create_pai_val(pai_buf, ret);
734
735         if (paiv) {
736                 DEBUG(10,("load_inherited_info: ACL type 0x%x for file %s\n",
737                         (unsigned int)paiv->sd_type,
738                         fname));
739         }
740
741         TALLOC_FREE(pai_buf);
742         return paiv;
743 }
744
745 /****************************************************************************
746  Functions to manipulate the internal ACE format.
747 ****************************************************************************/
748
749 /****************************************************************************
750  Count a linked list of canonical ACE entries.
751 ****************************************************************************/
752
753 static size_t count_canon_ace_list( canon_ace *l_head )
754 {
755         size_t count = 0;
756         canon_ace *ace;
757
758         for (ace = l_head; ace; ace = ace->next)
759                 count++;
760
761         return count;
762 }
763
764 /****************************************************************************
765  Free a linked list of canonical ACE entries.
766 ****************************************************************************/
767
768 static void free_canon_ace_list( canon_ace *l_head )
769 {
770         canon_ace *list, *next;
771
772         for (list = l_head; list; list = next) {
773                 next = list->next;
774                 DLIST_REMOVE(l_head, list);
775                 TALLOC_FREE(list);
776         }
777 }
778
779 /****************************************************************************
780  Function to duplicate a canon_ace entry.
781 ****************************************************************************/
782
783 static canon_ace *dup_canon_ace( canon_ace *src_ace)
784 {
785         canon_ace *dst_ace = talloc(talloc_tos(), canon_ace);
786
787         if (dst_ace == NULL)
788                 return NULL;
789
790         *dst_ace = *src_ace;
791         dst_ace->prev = dst_ace->next = NULL;
792         return dst_ace;
793 }
794
795 /****************************************************************************
796  Print out a canon ace.
797 ****************************************************************************/
798
799 static void print_canon_ace(canon_ace *pace, int num)
800 {
801         dbgtext( "canon_ace index %d. Type = %s ", num, pace->attr == ALLOW_ACE ? "allow" : "deny" );
802         dbgtext( "SID = %s ", sid_string_dbg(&pace->trustee));
803         if (pace->owner_type == UID_ACE) {
804                 const char *u_name = uidtoname(pace->unix_ug.id);
805                 dbgtext( "uid %u (%s) ", (unsigned int)pace->unix_ug.id, u_name );
806         } else if (pace->owner_type == GID_ACE) {
807                 char *g_name = gidtoname(pace->unix_ug.id);
808                 dbgtext( "gid %u (%s) ", (unsigned int)pace->unix_ug.id, g_name );
809         } else
810                 dbgtext( "other ");
811         switch (pace->type) {
812                 case SMB_ACL_USER:
813                         dbgtext( "SMB_ACL_USER ");
814                         break;
815                 case SMB_ACL_USER_OBJ:
816                         dbgtext( "SMB_ACL_USER_OBJ ");
817                         break;
818                 case SMB_ACL_GROUP:
819                         dbgtext( "SMB_ACL_GROUP ");
820                         break;
821                 case SMB_ACL_GROUP_OBJ:
822                         dbgtext( "SMB_ACL_GROUP_OBJ ");
823                         break;
824                 case SMB_ACL_OTHER:
825                         dbgtext( "SMB_ACL_OTHER ");
826                         break;
827                 default:
828                         dbgtext( "MASK " );
829                         break;
830         }
831
832         dbgtext( "ace_flags = 0x%x ", (unsigned int)pace->ace_flags);
833         dbgtext( "perms ");
834         dbgtext( "%c", pace->perms & S_IRUSR ? 'r' : '-');
835         dbgtext( "%c", pace->perms & S_IWUSR ? 'w' : '-');
836         dbgtext( "%c\n", pace->perms & S_IXUSR ? 'x' : '-');
837 }
838
839 /****************************************************************************
840  Print out a canon ace list.
841 ****************************************************************************/
842
843 static void print_canon_ace_list(const char *name, canon_ace *ace_list)
844 {
845         int count = 0;
846
847         if( DEBUGLVL( 10 )) {
848                 dbgtext( "print_canon_ace_list: %s\n", name );
849                 for (;ace_list; ace_list = ace_list->next, count++)
850                         print_canon_ace(ace_list, count );
851         }
852 }
853
854 /****************************************************************************
855  Map POSIX ACL perms to canon_ace permissions (a mode_t containing only S_(R|W|X)USR bits).
856 ****************************************************************************/
857
858 static mode_t convert_permset_to_mode_t(SMB_ACL_PERMSET_T permset)
859 {
860         mode_t ret = 0;
861
862         ret |= (sys_acl_get_perm(permset, SMB_ACL_READ) ? S_IRUSR : 0);
863         ret |= (sys_acl_get_perm(permset, SMB_ACL_WRITE) ? S_IWUSR : 0);
864         ret |= (sys_acl_get_perm(permset, SMB_ACL_EXECUTE) ? S_IXUSR : 0);
865
866         return ret;
867 }
868
869 /****************************************************************************
870  Map generic UNIX permissions to canon_ace permissions (a mode_t containing only S_(R|W|X)USR bits).
871 ****************************************************************************/
872
873 static mode_t unix_perms_to_acl_perms(mode_t mode, int r_mask, int w_mask, int x_mask)
874 {
875         mode_t ret = 0;
876
877         if (mode & r_mask)
878                 ret |= S_IRUSR;
879         if (mode & w_mask)
880                 ret |= S_IWUSR;
881         if (mode & x_mask)
882                 ret |= S_IXUSR;
883
884         return ret;
885 }
886
887 /****************************************************************************
888  Map canon_ace permissions (a mode_t containing only S_(R|W|X)USR bits) to
889  an SMB_ACL_PERMSET_T.
890 ****************************************************************************/
891
892 static int map_acl_perms_to_permset(connection_struct *conn, mode_t mode, SMB_ACL_PERMSET_T *p_permset)
893 {
894         if (sys_acl_clear_perms(*p_permset) ==  -1)
895                 return -1;
896         if (mode & S_IRUSR) {
897                 if (sys_acl_add_perm(*p_permset, SMB_ACL_READ) == -1)
898                         return -1;
899         }
900         if (mode & S_IWUSR) {
901                 if (sys_acl_add_perm(*p_permset, SMB_ACL_WRITE) == -1)
902                         return -1;
903         }
904         if (mode & S_IXUSR) {
905                 if (sys_acl_add_perm(*p_permset, SMB_ACL_EXECUTE) == -1)
906                         return -1;
907         }
908         return 0;
909 }
910
911 /****************************************************************************
912  Function to create owner and group SIDs from a SMB_STRUCT_STAT.
913 ****************************************************************************/
914
915 void create_file_sids(const SMB_STRUCT_STAT *psbuf, struct dom_sid *powner_sid, struct dom_sid *pgroup_sid)
916 {
917         uid_to_sid( powner_sid, psbuf->st_ex_uid );
918         gid_to_sid( pgroup_sid, psbuf->st_ex_gid );
919 }
920
921 /****************************************************************************
922  Merge aces with a common UID or GID - if both are allow or deny, OR the permissions together and
923  delete the second one. If the first is deny, mask the permissions off and delete the allow
924  if the permissions become zero, delete the deny if the permissions are non zero.
925 ****************************************************************************/
926
927 static void merge_aces( canon_ace **pp_list_head, bool dir_acl)
928 {
929         canon_ace *l_head = *pp_list_head;
930         canon_ace *curr_ace_outer;
931         canon_ace *curr_ace_outer_next;
932
933         /*
934          * First, merge allow entries with identical SIDs, and deny entries
935          * with identical SIDs.
936          */
937
938         for (curr_ace_outer = l_head; curr_ace_outer; curr_ace_outer = curr_ace_outer_next) {
939                 canon_ace *curr_ace;
940                 canon_ace *curr_ace_next;
941
942                 curr_ace_outer_next = curr_ace_outer->next; /* Save the link in case we delete. */
943
944                 for (curr_ace = curr_ace_outer->next; curr_ace; curr_ace = curr_ace_next) {
945                         bool can_merge = false;
946
947                         curr_ace_next = curr_ace->next; /* Save the link in case of delete. */
948
949                         /* For file ACLs we can merge if the SIDs and ALLOW/DENY
950                          * types are the same. For directory acls we must also
951                          * ensure the POSIX ACL types are the same.
952                          *
953                          * For the IDMAP_BOTH case, we must not merge
954                          * the UID and GID ACE values for same SID
955                          */
956
957                         if (!dir_acl) {
958                                 can_merge = (curr_ace->unix_ug.id == curr_ace_outer->unix_ug.id &&
959                                              curr_ace->owner_type == curr_ace_outer->owner_type &&
960                                              (curr_ace->attr == curr_ace_outer->attr));
961                         } else {
962                                 can_merge = (curr_ace->unix_ug.id == curr_ace_outer->unix_ug.id &&
963                                              curr_ace->owner_type == curr_ace_outer->owner_type &&
964                                              (curr_ace->type == curr_ace_outer->type) &&
965                                              (curr_ace->attr == curr_ace_outer->attr));
966                         }
967
968                         if (can_merge) {
969                                 if( DEBUGLVL( 10 )) {
970                                         dbgtext("merge_aces: Merging ACE's\n");
971                                         print_canon_ace( curr_ace_outer, 0);
972                                         print_canon_ace( curr_ace, 0);
973                                 }
974
975                                 /* Merge two allow or two deny ACE's. */
976
977                                 /* Theoretically we shouldn't merge a dir ACE if
978                                  * one ACE has the CI flag set, and the other
979                                  * ACE has the OI flag set, but this is rare
980                                  * enough we can ignore it. */
981
982                                 curr_ace_outer->perms |= curr_ace->perms;
983                                 curr_ace_outer->ace_flags |= curr_ace->ace_flags;
984                                 DLIST_REMOVE(l_head, curr_ace);
985                                 TALLOC_FREE(curr_ace);
986                                 curr_ace_outer_next = curr_ace_outer->next; /* We may have deleted the link. */
987                         }
988                 }
989         }
990
991         /*
992          * Now go through and mask off allow permissions with deny permissions.
993          * We can delete either the allow or deny here as we know that each SID
994          * appears only once in the list.
995          */
996
997         for (curr_ace_outer = l_head; curr_ace_outer; curr_ace_outer = curr_ace_outer_next) {
998                 canon_ace *curr_ace;
999                 canon_ace *curr_ace_next;
1000
1001                 curr_ace_outer_next = curr_ace_outer->next; /* Save the link in case we delete. */
1002
1003                 for (curr_ace = curr_ace_outer->next; curr_ace; curr_ace = curr_ace_next) {
1004
1005                         curr_ace_next = curr_ace->next; /* Save the link in case of delete. */
1006
1007                         /*
1008                          * Subtract ACE's with different entries. Due to the ordering constraints
1009                          * we've put on the ACL, we know the deny must be the first one.
1010                          */
1011
1012                         if (curr_ace->unix_ug.id == curr_ace_outer->unix_ug.id &&
1013                             (curr_ace->owner_type == curr_ace_outer->owner_type) &&
1014                             (curr_ace_outer->attr == DENY_ACE) && (curr_ace->attr == ALLOW_ACE)) {
1015
1016                                 if( DEBUGLVL( 10 )) {
1017                                         dbgtext("merge_aces: Masking ACE's\n");
1018                                         print_canon_ace( curr_ace_outer, 0);
1019                                         print_canon_ace( curr_ace, 0);
1020                                 }
1021
1022                                 curr_ace->perms &= ~curr_ace_outer->perms;
1023
1024                                 if (curr_ace->perms == 0) {
1025
1026                                         /*
1027                                          * The deny overrides the allow. Remove the allow.
1028                                          */
1029
1030                                         DLIST_REMOVE(l_head, curr_ace);
1031                                         TALLOC_FREE(curr_ace);
1032                                         curr_ace_outer_next = curr_ace_outer->next; /* We may have deleted the link. */
1033
1034                                 } else {
1035
1036                                         /*
1037                                          * Even after removing permissions, there
1038                                          * are still allow permissions - delete the deny.
1039                                          * It is safe to delete the deny here,
1040                                          * as we are guarenteed by the deny first
1041                                          * ordering that all the deny entries for
1042                                          * this SID have already been merged into one
1043                                          * before we can get to an allow ace.
1044                                          */
1045
1046                                         DLIST_REMOVE(l_head, curr_ace_outer);
1047                                         TALLOC_FREE(curr_ace_outer);
1048                                         break;
1049                                 }
1050                         }
1051
1052                 } /* end for curr_ace */
1053         } /* end for curr_ace_outer */
1054
1055         /* We may have modified the list. */
1056
1057         *pp_list_head = l_head;
1058 }
1059
1060 /****************************************************************************
1061  Check if we need to return NT4.x compatible ACL entries.
1062 ****************************************************************************/
1063
1064 bool nt4_compatible_acls(void)
1065 {
1066         int compat = lp_acl_compatibility();
1067
1068         if (compat == ACL_COMPAT_AUTO) {
1069                 enum remote_arch_types ra_type = get_remote_arch();
1070
1071                 /* Automatically adapt to client */
1072                 return (ra_type <= RA_WINNT);
1073         } else
1074                 return (compat == ACL_COMPAT_WINNT);
1075 }
1076
1077
1078 /****************************************************************************
1079  Map canon_ace perms to permission bits NT.
1080  The attr element is not used here - we only process deny entries on set,
1081  not get. Deny entries are implicit on get with ace->perms = 0.
1082 ****************************************************************************/
1083
1084 uint32_t map_canon_ace_perms(int snum,
1085                                 enum security_ace_type *pacl_type,
1086                                 mode_t perms,
1087                                 bool directory_ace)
1088 {
1089         uint32_t nt_mask = 0;
1090
1091         *pacl_type = SEC_ACE_TYPE_ACCESS_ALLOWED;
1092
1093         if (lp_acl_map_full_control(snum) && ((perms & ALL_ACE_PERMS) == ALL_ACE_PERMS)) {
1094                 if (directory_ace) {
1095                         nt_mask = UNIX_DIRECTORY_ACCESS_RWX;
1096                 } else {
1097                         nt_mask = (UNIX_ACCESS_RWX & ~DELETE_ACCESS);
1098                 }
1099         } else if ((perms & ALL_ACE_PERMS) == (mode_t)0) {
1100                 /*
1101                  * Windows NT refuses to display ACEs with no permissions in them (but
1102                  * they are perfectly legal with Windows 2000). If the ACE has empty
1103                  * permissions we cannot use 0, so we use the otherwise unused
1104                  * WRITE_OWNER permission, which we ignore when we set an ACL.
1105                  * We abstract this into a #define of UNIX_ACCESS_NONE to allow this
1106                  * to be changed in the future.
1107                  */
1108
1109                 if (nt4_compatible_acls())
1110                         nt_mask = UNIX_ACCESS_NONE;
1111                 else
1112                         nt_mask = 0;
1113         } else {
1114                 if (directory_ace) {
1115                         nt_mask |= ((perms & S_IRUSR) ? UNIX_DIRECTORY_ACCESS_R : 0 );
1116                         nt_mask |= ((perms & S_IWUSR) ? UNIX_DIRECTORY_ACCESS_W : 0 );
1117                         nt_mask |= ((perms & S_IXUSR) ? UNIX_DIRECTORY_ACCESS_X : 0 );
1118                 } else {
1119                         nt_mask |= ((perms & S_IRUSR) ? UNIX_ACCESS_R : 0 );
1120                         nt_mask |= ((perms & S_IWUSR) ? UNIX_ACCESS_W : 0 );
1121                         nt_mask |= ((perms & S_IXUSR) ? UNIX_ACCESS_X : 0 );
1122                 }
1123         }
1124
1125         if ((perms & S_IWUSR) && lp_dos_filemode(snum)) {
1126                 nt_mask |= (SEC_STD_WRITE_DAC|SEC_STD_WRITE_OWNER|DELETE_ACCESS);
1127         }
1128
1129         DEBUG(10,("map_canon_ace_perms: Mapped (UNIX) %x to (NT) %x\n",
1130                         (unsigned int)perms, (unsigned int)nt_mask ));
1131
1132         return nt_mask;
1133 }
1134
1135 /****************************************************************************
1136  Map NT perms to a UNIX mode_t.
1137 ****************************************************************************/
1138
1139 #define FILE_SPECIFIC_READ_BITS (FILE_READ_DATA|FILE_READ_EA)
1140 #define FILE_SPECIFIC_WRITE_BITS (FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_WRITE_EA)
1141 #define FILE_SPECIFIC_EXECUTE_BITS (FILE_EXECUTE)
1142
1143 static mode_t map_nt_perms( uint32 *mask, int type)
1144 {
1145         mode_t mode = 0;
1146
1147         switch(type) {
1148         case S_IRUSR:
1149                 if((*mask) & GENERIC_ALL_ACCESS)
1150                         mode = S_IRUSR|S_IWUSR|S_IXUSR;
1151                 else {
1152                         mode |= ((*mask) & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IRUSR : 0;
1153                         mode |= ((*mask) & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWUSR : 0;
1154                         mode |= ((*mask) & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXUSR : 0;
1155                 }
1156                 break;
1157         case S_IRGRP:
1158                 if((*mask) & GENERIC_ALL_ACCESS)
1159                         mode = S_IRGRP|S_IWGRP|S_IXGRP;
1160                 else {
1161                         mode |= ((*mask) & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IRGRP : 0;
1162                         mode |= ((*mask) & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWGRP : 0;
1163                         mode |= ((*mask) & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXGRP : 0;
1164                 }
1165                 break;
1166         case S_IROTH:
1167                 if((*mask) & GENERIC_ALL_ACCESS)
1168                         mode = S_IROTH|S_IWOTH|S_IXOTH;
1169                 else {
1170                         mode |= ((*mask) & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IROTH : 0;
1171                         mode |= ((*mask) & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWOTH : 0;
1172                         mode |= ((*mask) & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXOTH : 0;
1173                 }
1174                 break;
1175         }
1176
1177         return mode;
1178 }
1179
1180 /****************************************************************************
1181  Unpack a struct security_descriptor into a UNIX owner and group.
1182 ****************************************************************************/
1183
1184 NTSTATUS unpack_nt_owners(struct connection_struct *conn,
1185                         uid_t *puser, gid_t *pgrp,
1186                         uint32 security_info_sent, const struct
1187                         security_descriptor *psd)
1188 {
1189         struct dom_sid owner_sid;
1190         struct dom_sid grp_sid;
1191
1192         *puser = (uid_t)-1;
1193         *pgrp = (gid_t)-1;
1194
1195         if(security_info_sent == 0) {
1196                 DEBUG(0,("unpack_nt_owners: no security info sent !\n"));
1197                 return NT_STATUS_OK;
1198         }
1199
1200         /*
1201          * Validate the owner and group SID's.
1202          */
1203
1204         memset(&owner_sid, '\0', sizeof(owner_sid));
1205         memset(&grp_sid, '\0', sizeof(grp_sid));
1206
1207         DEBUG(5,("unpack_nt_owners: validating owner_sids.\n"));
1208
1209         /*
1210          * Don't immediately fail if the owner sid cannot be validated.
1211          * This may be a group chown only set.
1212          */
1213
1214         if (security_info_sent & SECINFO_OWNER) {
1215                 sid_copy(&owner_sid, psd->owner_sid);
1216                 if (!sid_to_uid(&owner_sid, puser)) {
1217                         if (lp_force_unknown_acl_user(SNUM(conn))) {
1218                                 /* this allows take ownership to work
1219                                  * reasonably */
1220                                 *puser = get_current_uid(conn);
1221                         } else {
1222                                 DEBUG(3,("unpack_nt_owners: unable to validate"
1223                                          " owner sid for %s\n",
1224                                          sid_string_dbg(&owner_sid)));
1225                                 return NT_STATUS_INVALID_OWNER;
1226                         }
1227                 }
1228                 DEBUG(3,("unpack_nt_owners: owner sid mapped to uid %u\n",
1229                          (unsigned int)*puser ));
1230         }
1231
1232         /*
1233          * Don't immediately fail if the group sid cannot be validated.
1234          * This may be an owner chown only set.
1235          */
1236
1237         if (security_info_sent & SECINFO_GROUP) {
1238                 sid_copy(&grp_sid, psd->group_sid);
1239                 if (!sid_to_gid( &grp_sid, pgrp)) {
1240                         if (lp_force_unknown_acl_user(SNUM(conn))) {
1241                                 /* this allows take group ownership to work
1242                                  * reasonably */
1243                                 *pgrp = get_current_gid(conn);
1244                         } else {
1245                                 DEBUG(3,("unpack_nt_owners: unable to validate"
1246                                          " group sid.\n"));
1247                                 return NT_STATUS_INVALID_OWNER;
1248                         }
1249                 }
1250                 DEBUG(3,("unpack_nt_owners: group sid mapped to gid %u\n",
1251                          (unsigned int)*pgrp));
1252         }
1253
1254         DEBUG(5,("unpack_nt_owners: owner_sids validated.\n"));
1255
1256         return NT_STATUS_OK;
1257 }
1258
1259 /****************************************************************************
1260  Ensure the enforced permissions for this share apply.
1261 ****************************************************************************/
1262
1263 static void apply_default_perms(const struct share_params *params,
1264                                 const bool is_directory, canon_ace *pace,
1265                                 mode_t type)
1266 {
1267         mode_t and_bits = (mode_t)0;
1268         mode_t or_bits = (mode_t)0;
1269
1270         /* Get the initial bits to apply. */
1271
1272         if (is_directory) {
1273                 and_bits = lp_dir_mask(params->service);
1274                 or_bits = lp_force_dir_mode(params->service);
1275         } else {
1276                 and_bits = lp_create_mask(params->service);
1277                 or_bits = lp_force_create_mode(params->service);
1278         }
1279
1280         /* Now bounce them into the S_USR space. */     
1281         switch(type) {
1282         case S_IRUSR:
1283                 /* Ensure owner has read access. */
1284                 pace->perms |= S_IRUSR;
1285                 if (is_directory)
1286                         pace->perms |= (S_IWUSR|S_IXUSR);
1287                 and_bits = unix_perms_to_acl_perms(and_bits, S_IRUSR, S_IWUSR, S_IXUSR);
1288                 or_bits = unix_perms_to_acl_perms(or_bits, S_IRUSR, S_IWUSR, S_IXUSR);
1289                 break;
1290         case S_IRGRP:
1291                 and_bits = unix_perms_to_acl_perms(and_bits, S_IRGRP, S_IWGRP, S_IXGRP);
1292                 or_bits = unix_perms_to_acl_perms(or_bits, S_IRGRP, S_IWGRP, S_IXGRP);
1293                 break;
1294         case S_IROTH:
1295                 and_bits = unix_perms_to_acl_perms(and_bits, S_IROTH, S_IWOTH, S_IXOTH);
1296                 or_bits = unix_perms_to_acl_perms(or_bits, S_IROTH, S_IWOTH, S_IXOTH);
1297                 break;
1298         }
1299
1300         pace->perms = ((pace->perms & and_bits)|or_bits);
1301 }
1302
1303 /****************************************************************************
1304  Check if a given uid/SID is in a group gid/SID. This is probably very
1305  expensive and will need optimisation. A *lot* of optimisation :-). JRA.
1306 ****************************************************************************/
1307
1308 static bool uid_entry_in_group(connection_struct *conn, canon_ace *uid_ace, canon_ace *group_ace )
1309 {
1310         /* "Everyone" always matches every uid. */
1311
1312         if (dom_sid_equal(&group_ace->trustee, &global_sid_World))
1313                 return True;
1314
1315         /*
1316          * if it's the current user, we already have the unix token
1317          * and don't need to do the complex user_in_group_sid() call
1318          */
1319         if (uid_ace->unix_ug.id == get_current_uid(conn)) {
1320                 const struct security_unix_token *curr_utok = NULL;
1321                 size_t i;
1322
1323                 if (group_ace->unix_ug.id == get_current_gid(conn)) {
1324                         return True;
1325                 }
1326
1327                 curr_utok = get_current_utok(conn);
1328                 for (i=0; i < curr_utok->ngroups; i++) {
1329                         if (group_ace->unix_ug.id == curr_utok->groups[i]) {
1330                                 return True;
1331                         }
1332                 }
1333         }
1334
1335         /*
1336          * user_in_group_sid() uses create_token_from_sid()
1337          * which creates an artificial NT token given just a username,
1338          * so this is not reliable for users from foreign domains
1339          * exported by winbindd!
1340          */
1341         return user_sid_in_group_sid(&uid_ace->trustee, &group_ace->trustee);
1342 }
1343
1344 /****************************************************************************
1345  A well formed POSIX file or default ACL has at least 3 entries, a
1346  SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER_OBJ.
1347  In addition, the owner must always have at least read access.
1348  When using this call on get_acl, the pst struct is valid and contains
1349  the mode of the file.
1350 ****************************************************************************/
1351
1352 static bool ensure_canon_entry_valid_on_get(connection_struct *conn,
1353                                         canon_ace **pp_ace,
1354                                         const struct dom_sid *pfile_owner_sid,
1355                                         const struct dom_sid *pfile_grp_sid,
1356                                         const SMB_STRUCT_STAT *pst)
1357 {
1358         canon_ace *pace;
1359         bool got_user = false;
1360         bool got_group = false;
1361         bool got_other = false;
1362
1363         for (pace = *pp_ace; pace; pace = pace->next) {
1364                 if (pace->type == SMB_ACL_USER_OBJ) {
1365                         got_user = true;
1366                 } else if (pace->type == SMB_ACL_GROUP_OBJ) {
1367                         got_group = true;
1368                 } else if (pace->type == SMB_ACL_OTHER) {
1369                         got_other = true;
1370                 }
1371         }
1372
1373         if (!got_user) {
1374                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1375                         DEBUG(0,("malloc fail.\n"));
1376                         return false;
1377                 }
1378
1379                 ZERO_STRUCTP(pace);
1380                 pace->type = SMB_ACL_USER_OBJ;
1381                 pace->owner_type = UID_ACE;
1382                 pace->unix_ug.type = ID_TYPE_UID;
1383                 pace->unix_ug.id = pst->st_ex_uid;
1384                 pace->trustee = *pfile_owner_sid;
1385                 pace->attr = ALLOW_ACE;
1386                 pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRUSR, S_IWUSR, S_IXUSR);
1387                 DLIST_ADD(*pp_ace, pace);
1388         }
1389
1390         if (!got_group) {
1391                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1392                         DEBUG(0,("malloc fail.\n"));
1393                         return false;
1394                 }
1395
1396                 ZERO_STRUCTP(pace);
1397                 pace->type = SMB_ACL_GROUP_OBJ;
1398                 pace->owner_type = GID_ACE;
1399                 pace->unix_ug.type = ID_TYPE_GID;
1400                 pace->unix_ug.id = pst->st_ex_gid;
1401                 pace->trustee = *pfile_grp_sid;
1402                 pace->attr = ALLOW_ACE;
1403                 pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRGRP, S_IWGRP, S_IXGRP);
1404                 DLIST_ADD(*pp_ace, pace);
1405         }
1406
1407         if (!got_other) {
1408                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1409                         DEBUG(0,("malloc fail.\n"));
1410                         return false;
1411                 }
1412
1413                 ZERO_STRUCTP(pace);
1414                 pace->type = SMB_ACL_OTHER;
1415                 pace->owner_type = WORLD_ACE;
1416                 pace->unix_ug.type = ID_TYPE_NOT_SPECIFIED;
1417                 pace->unix_ug.id = -1;
1418                 pace->trustee = global_sid_World;
1419                 pace->attr = ALLOW_ACE;
1420                 pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IROTH, S_IWOTH, S_IXOTH);
1421                 DLIST_ADD(*pp_ace, pace);
1422         }
1423
1424         return true;
1425 }
1426
1427 /****************************************************************************
1428  A well formed POSIX file or default ACL has at least 3 entries, a
1429  SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER_OBJ.
1430  In addition, the owner must always have at least read access.
1431  When using this call on set_acl, the pst struct has
1432  been modified to have a mode containing the default for this file or directory
1433  type.
1434 ****************************************************************************/
1435
1436 static bool ensure_canon_entry_valid_on_set(connection_struct *conn,
1437                                         canon_ace **pp_ace,
1438                                         bool is_default_acl,
1439                                         const struct share_params *params,
1440                                         const bool is_directory,
1441                                         const struct dom_sid *pfile_owner_sid,
1442                                         const struct dom_sid *pfile_grp_sid,
1443                                         const SMB_STRUCT_STAT *pst)
1444 {
1445         canon_ace *pace;
1446         canon_ace *pace_user = NULL;
1447         canon_ace *pace_group = NULL;
1448         canon_ace *pace_other = NULL;
1449         bool got_duplicate_user = false;
1450         bool got_duplicate_group = false;
1451
1452         for (pace = *pp_ace; pace; pace = pace->next) {
1453                 if (pace->type == SMB_ACL_USER_OBJ) {
1454
1455                         if (!is_default_acl) {
1456                                 apply_default_perms(params, is_directory, pace, S_IRUSR);
1457                         }
1458                         pace_user = pace;
1459
1460                 } else if (pace->type == SMB_ACL_GROUP_OBJ) {
1461
1462                         /*
1463                          * Ensure create mask/force create mode is respected on set.
1464                          */
1465
1466                         if (!is_default_acl) {
1467                                 apply_default_perms(params, is_directory, pace, S_IRGRP);
1468                         }
1469                         pace_group = pace;
1470
1471                 } else if (pace->type == SMB_ACL_OTHER) {
1472
1473                         /*
1474                          * Ensure create mask/force create mode is respected on set.
1475                          */
1476
1477                         if (!is_default_acl) {
1478                                 apply_default_perms(params, is_directory, pace, S_IROTH);
1479                         }
1480                         pace_other = pace;
1481
1482                 } else if (pace->type == SMB_ACL_USER || pace->type == SMB_ACL_GROUP) {
1483
1484                         /*
1485                          * Ensure create mask/force create mode is respected on set.
1486                          */
1487
1488                         if (!is_default_acl) {
1489                                 apply_default_perms(params, is_directory, pace, S_IRGRP);
1490                         }
1491                 }
1492         }
1493
1494         if (!pace_user) {
1495                 canon_ace *pace_iter;
1496
1497                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1498                         DEBUG(0,("talloc fail.\n"));
1499                         return false;
1500                 }
1501
1502                 ZERO_STRUCTP(pace);
1503                 pace->type = SMB_ACL_USER_OBJ;
1504                 pace->owner_type = UID_ACE;
1505                 pace->unix_ug.type = ID_TYPE_UID;
1506                 pace->unix_ug.id = pst->st_ex_uid;
1507                 pace->trustee = *pfile_owner_sid;
1508                 pace->attr = ALLOW_ACE;
1509                 /* Start with existing user permissions, principle of least
1510                    surprises for the user. */
1511                 pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRUSR, S_IWUSR, S_IXUSR);
1512
1513                 /* See if the owning user is in any of the other groups in
1514                    the ACE, or if there's a matching user entry (by uid
1515                    or in the case of ID_TYPE_BOTH by SID).
1516                    If so, OR in the permissions from that entry. */
1517
1518
1519                 for (pace_iter = *pp_ace; pace_iter; pace_iter = pace_iter->next) {
1520                         if (pace_iter->type == SMB_ACL_USER &&
1521                                         pace_iter->unix_ug.id == pace->unix_ug.id) {
1522                                 pace->perms |= pace_iter->perms;
1523                         } else if (pace_iter->type == SMB_ACL_GROUP_OBJ || pace_iter->type == SMB_ACL_GROUP) {
1524                                 if (dom_sid_equal(&pace->trustee, &pace_iter->trustee)) {
1525                                         pace->perms |= pace_iter->perms;
1526                                 } else if (uid_entry_in_group(conn, pace, pace_iter)) {
1527                                         pace->perms |= pace_iter->perms;
1528                                 }
1529                         }
1530                 }
1531
1532                 if (pace->perms == 0) {
1533                         /* If we only got an "everyone" perm, just use that. */
1534                         if (pace_other)
1535                                 pace->perms = pace_other->perms;
1536                 }
1537
1538                 if (!is_default_acl) {
1539                         apply_default_perms(params, is_directory, pace, S_IRUSR);
1540                 }
1541
1542                 DLIST_ADD(*pp_ace, pace);
1543                 pace_user = pace;
1544         }
1545
1546         if (!pace_group) {
1547                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1548                         DEBUG(0,("talloc fail.\n"));
1549                         return false;
1550                 }
1551
1552                 ZERO_STRUCTP(pace);
1553                 pace->type = SMB_ACL_GROUP_OBJ;
1554                 pace->owner_type = GID_ACE;
1555                 pace->unix_ug.type = ID_TYPE_GID;
1556                 pace->unix_ug.id = pst->st_ex_gid;
1557                 pace->trustee = *pfile_grp_sid;
1558                 pace->attr = ALLOW_ACE;
1559
1560                 /* If we only got an "everyone" perm, just use that. */
1561                 if (pace_other) {
1562                         pace->perms = pace_other->perms;
1563                 } else {
1564                         pace->perms = 0;
1565                 }
1566                 if (!is_default_acl) {
1567                         apply_default_perms(params, is_directory, pace, S_IRGRP);
1568                 }
1569
1570                 DLIST_ADD(*pp_ace, pace);
1571                 pace_group = pace;
1572         }
1573
1574         if (!pace_other) {
1575                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1576                         DEBUG(0,("talloc fail.\n"));
1577                         return false;
1578                 }
1579
1580                 ZERO_STRUCTP(pace);
1581                 pace->type = SMB_ACL_OTHER;
1582                 pace->owner_type = WORLD_ACE;
1583                 pace->unix_ug.type = ID_TYPE_NOT_SPECIFIED;
1584                 pace->unix_ug.id = -1;
1585                 pace->trustee = global_sid_World;
1586                 pace->attr = ALLOW_ACE;
1587                 pace->perms = 0;
1588                 if (!is_default_acl) {
1589                         apply_default_perms(params, is_directory, pace, S_IROTH);
1590                 }
1591
1592                 DLIST_ADD(*pp_ace, pace);
1593                 pace_other = pace;
1594         }
1595
1596         /* Ensure when setting a POSIX ACL, that the uid for a
1597            SMB_ACL_USER_OBJ ACE (the owner ACE entry) has a duplicate
1598            permission entry as an SMB_ACL_USER, and a gid for a
1599            SMB_ACL_GROUP_OBJ ACE (the primary group ACE entry) also has
1600            a duplicate permission entry as an SMB_ACL_GROUP. If not,
1601            then if the ownership or group ownership of this file or
1602            directory gets changed, the user or group can lose their
1603            access. */
1604
1605         for (pace = *pp_ace; pace; pace = pace->next) {
1606                 if (pace->type == SMB_ACL_USER &&
1607                                 pace->unix_ug.id == pace_user->unix_ug.id) {
1608                         /* Already got one. */
1609                         got_duplicate_user = true;
1610                 } else if (pace->type == SMB_ACL_GROUP &&
1611                                 pace->unix_ug.id == pace_user->unix_ug.id) {
1612                         /* Already got one. */
1613                         got_duplicate_group = true;
1614                 } else if ((pace->type == SMB_ACL_GROUP)
1615                            && (dom_sid_equal(&pace->trustee, &pace_user->trustee))) {
1616                         /* If the SID owning the file appears
1617                          * in a group entry, then we have
1618                          * enough duplication, they will still
1619                          * have access */
1620                         got_duplicate_user = true;
1621                 }
1622         }
1623
1624         /* If the SID is equal for the user and group that we need
1625            to add the duplicate for, add only the group */
1626         if (!got_duplicate_user && !got_duplicate_group
1627                         && dom_sid_equal(&pace_group->trustee,
1628                                         &pace_user->trustee)) {
1629                 /* Add a duplicate SMB_ACL_GROUP entry, this
1630                  * will cover the owning SID as well, as it
1631                  * will always be mapped to both a uid and
1632                  * gid. */
1633
1634                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1635                         DEBUG(0,("talloc fail.\n"));
1636                         return false;
1637                 }
1638
1639                 ZERO_STRUCTP(pace);
1640                 pace->type = SMB_ACL_GROUP;;
1641                 pace->owner_type = GID_ACE;
1642                 pace->unix_ug.type = ID_TYPE_GID;
1643                 pace->unix_ug.id = pace_group->unix_ug.id;
1644                 pace->trustee = pace_group->trustee;
1645                 pace->attr = pace_group->attr;
1646                 pace->perms = pace_group->perms;
1647
1648                 DLIST_ADD(*pp_ace, pace);
1649
1650                 /* We're done here, make sure the
1651                    statements below are not executed. */
1652                 got_duplicate_user = true;
1653                 got_duplicate_group = true;
1654         }
1655
1656         if (!got_duplicate_user) {
1657                 /* Add a duplicate SMB_ACL_USER entry. */
1658                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1659                         DEBUG(0,("talloc fail.\n"));
1660                         return false;
1661                 }
1662
1663                 ZERO_STRUCTP(pace);
1664                 pace->type = SMB_ACL_USER;;
1665                 pace->owner_type = UID_ACE;
1666                 pace->unix_ug.type = ID_TYPE_UID;
1667                 pace->unix_ug.id = pace_user->unix_ug.id;
1668                 pace->trustee = pace_user->trustee;
1669                 pace->attr = pace_user->attr;
1670                 pace->perms = pace_user->perms;
1671
1672                 DLIST_ADD(*pp_ace, pace);
1673
1674                 got_duplicate_user = true;
1675         }
1676
1677         if (!got_duplicate_group) {
1678                 /* Add a duplicate SMB_ACL_GROUP entry. */
1679                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1680                         DEBUG(0,("talloc fail.\n"));
1681                         return false;
1682                 }
1683
1684                 ZERO_STRUCTP(pace);
1685                 pace->type = SMB_ACL_GROUP;;
1686                 pace->owner_type = GID_ACE;
1687                 pace->unix_ug.type = ID_TYPE_GID;
1688                 pace->unix_ug.id = pace_group->unix_ug.id;
1689                 pace->trustee = pace_group->trustee;
1690                 pace->attr = pace_group->attr;
1691                 pace->perms = pace_group->perms;
1692
1693                 DLIST_ADD(*pp_ace, pace);
1694
1695                 got_duplicate_group = true;
1696         }
1697
1698         return true;
1699 }
1700
1701 /****************************************************************************
1702  Check if a POSIX ACL has the required SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ entries.
1703  If it does not have them, check if there are any entries where the trustee is the
1704  file owner or the owning group, and map these to SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ.
1705  Note we must not do this to default directory ACLs.
1706 ****************************************************************************/
1707
1708 static void check_owning_objs(canon_ace *ace, struct dom_sid *pfile_owner_sid, struct dom_sid *pfile_grp_sid)
1709 {
1710         bool got_user_obj, got_group_obj;
1711         canon_ace *current_ace;
1712         int i, entries;
1713
1714         entries = count_canon_ace_list(ace);
1715         got_user_obj = False;
1716         got_group_obj = False;
1717
1718         for (i=0, current_ace = ace; i < entries; i++, current_ace = current_ace->next) {
1719                 if (current_ace->type == SMB_ACL_USER_OBJ)
1720                         got_user_obj = True;
1721                 else if (current_ace->type == SMB_ACL_GROUP_OBJ)
1722                         got_group_obj = True;
1723         }
1724         if (got_user_obj && got_group_obj) {
1725                 DEBUG(10,("check_owning_objs: ACL had owning user/group entries.\n"));
1726                 return;
1727         }
1728
1729         for (i=0, current_ace = ace; i < entries; i++, current_ace = current_ace->next) {
1730                 if (!got_user_obj && current_ace->owner_type == UID_ACE &&
1731                                 dom_sid_equal(&current_ace->trustee, pfile_owner_sid)) {
1732                         current_ace->type = SMB_ACL_USER_OBJ;
1733                         got_user_obj = True;
1734                 }
1735                 if (!got_group_obj && current_ace->owner_type == GID_ACE &&
1736                                 dom_sid_equal(&current_ace->trustee, pfile_grp_sid)) {
1737                         current_ace->type = SMB_ACL_GROUP_OBJ;
1738                         got_group_obj = True;
1739                 }
1740         }
1741         if (!got_user_obj)
1742                 DEBUG(10,("check_owning_objs: ACL is missing an owner entry.\n"));
1743         if (!got_group_obj)
1744                 DEBUG(10,("check_owning_objs: ACL is missing an owning group entry.\n"));
1745 }
1746
1747 static bool add_current_ace_to_acl(files_struct *fsp, struct security_ace *psa,
1748                                    canon_ace **file_ace, canon_ace **dir_ace,
1749                                    bool *got_file_allow, bool *got_dir_allow,
1750                                    bool *all_aces_are_inherit_only,
1751                                    canon_ace *current_ace)
1752 {
1753
1754         /*
1755          * Map the given NT permissions into a UNIX mode_t containing only
1756          * S_I(R|W|X)USR bits.
1757          */
1758
1759         current_ace->perms |= map_nt_perms( &psa->access_mask, S_IRUSR);
1760         current_ace->attr = (psa->type == SEC_ACE_TYPE_ACCESS_ALLOWED) ? ALLOW_ACE : DENY_ACE;
1761
1762         /* Store the ace_flag. */
1763         current_ace->ace_flags = psa->flags;
1764
1765         /*
1766          * Now add the created ace to either the file list, the directory
1767          * list, or both. We *MUST* preserve the order here (hence we use
1768          * DLIST_ADD_END) as NT ACLs are order dependent.
1769          */
1770
1771         if (fsp->is_directory) {
1772
1773                 /*
1774                  * We can only add to the default POSIX ACE list if the ACE is
1775                  * designed to be inherited by both files and directories.
1776                  */
1777
1778                 if ((psa->flags & (SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT)) ==
1779                     (SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT)) {
1780
1781                         canon_ace *current_dir_ace = current_ace;
1782                         DLIST_ADD_END(*dir_ace, current_ace, canon_ace *);
1783
1784                         /*
1785                          * Note if this was an allow ace. We can't process
1786                          * any further deny ace's after this.
1787                          */
1788
1789                         if (current_ace->attr == ALLOW_ACE)
1790                                 *got_dir_allow = True;
1791
1792                         if ((current_ace->attr == DENY_ACE) && *got_dir_allow) {
1793                                 DEBUG(0,("add_current_ace_to_acl: "
1794                                          "malformed ACL in "
1795                                          "inheritable ACL! Deny entry "
1796                                          "after Allow entry. Failing "
1797                                          "to set on file %s.\n",
1798                                          fsp_str_dbg(fsp)));
1799                                 return False;
1800                         }
1801
1802                         if( DEBUGLVL( 10 )) {
1803                                 dbgtext("add_current_ace_to_acl: adding dir ACL:\n");
1804                                 print_canon_ace( current_ace, 0);
1805                         }
1806
1807                         /*
1808                          * If this is not an inherit only ACE we need to add a duplicate
1809                          * to the file acl.
1810                          */
1811
1812                         if (!(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY)) {
1813                                 canon_ace *dup_ace = dup_canon_ace(current_ace);
1814
1815                                 if (!dup_ace) {
1816                                         DEBUG(0,("add_current_ace_to_acl: malloc fail !\n"));
1817                                         return False;
1818                                 }
1819
1820                                 /*
1821                                  * We must not free current_ace here as its
1822                                  * pointer is now owned by the dir_ace list.
1823                                  */
1824                                 current_ace = dup_ace;
1825                                 /* We've essentially split this ace into two,
1826                                  * and added the ace with inheritance request
1827                                  * bits to the directory ACL. Drop those bits for
1828                                  * the ACE we're adding to the file list. */
1829                                 current_ace->ace_flags &= ~(SEC_ACE_FLAG_OBJECT_INHERIT|
1830                                                             SEC_ACE_FLAG_CONTAINER_INHERIT|
1831                                                             SEC_ACE_FLAG_INHERIT_ONLY);
1832                         } else {
1833                                 /*
1834                                  * We must not free current_ace here as its
1835                                  * pointer is now owned by the dir_ace list.
1836                                  */
1837                                 current_ace = NULL;
1838                         }
1839
1840                         /*
1841                          * current_ace is now either owned by file_ace
1842                          * or is NULL. We can safely operate on current_dir_ace
1843                          * to treat mapping for default acl entries differently
1844                          * than access acl entries.
1845                          */
1846
1847                         if (current_dir_ace->owner_type == UID_ACE) {
1848                                 /*
1849                                  * We already decided above this is a uid,
1850                                  * for default acls ace's only CREATOR_OWNER
1851                                  * maps to ACL_USER_OBJ. All other uid
1852                                  * ace's are ACL_USER.
1853                                  */
1854                                 if (dom_sid_equal(&current_dir_ace->trustee,
1855                                                   &global_sid_Creator_Owner)) {
1856                                         current_dir_ace->type = SMB_ACL_USER_OBJ;
1857                                 } else {
1858                                         current_dir_ace->type = SMB_ACL_USER;
1859                                 }
1860                         }
1861
1862                         if (current_dir_ace->owner_type == GID_ACE) {
1863                                 /*
1864                                  * We already decided above this is a gid,
1865                                  * for default acls ace's only CREATOR_GROUP
1866                                  * maps to ACL_GROUP_OBJ. All other uid
1867                                  * ace's are ACL_GROUP.
1868                                  */
1869                                 if (dom_sid_equal(&current_dir_ace->trustee,
1870                                                   &global_sid_Creator_Group)) {
1871                                         current_dir_ace->type = SMB_ACL_GROUP_OBJ;
1872                                 } else {
1873                                         current_dir_ace->type = SMB_ACL_GROUP;
1874                                 }
1875                         }
1876                 }
1877         }
1878
1879         /*
1880          * Only add to the file ACL if not inherit only.
1881          */
1882
1883         if (current_ace && !(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY)) {
1884                 DLIST_ADD_END(*file_ace, current_ace, canon_ace *);
1885
1886                 /*
1887                  * Note if this was an allow ace. We can't process
1888                  * any further deny ace's after this.
1889                  */
1890
1891                 if (current_ace->attr == ALLOW_ACE)
1892                         *got_file_allow = True;
1893
1894                 if ((current_ace->attr == DENY_ACE) && got_file_allow) {
1895                         DEBUG(0,("add_current_ace_to_acl: malformed "
1896                                  "ACL in file ACL ! Deny entry after "
1897                                  "Allow entry. Failing to set on file "
1898                                  "%s.\n", fsp_str_dbg(fsp)));
1899                         return False;
1900                 }
1901
1902                 if( DEBUGLVL( 10 )) {
1903                         dbgtext("add_current_ace_to_acl: adding file ACL:\n");
1904                         print_canon_ace( current_ace, 0);
1905                 }
1906                 *all_aces_are_inherit_only = False;
1907                 /*
1908                  * We must not free current_ace here as its
1909                  * pointer is now owned by the file_ace list.
1910                  */
1911                 current_ace = NULL;
1912         }
1913
1914         /*
1915          * Free if ACE was not added.
1916          */
1917
1918         TALLOC_FREE(current_ace);
1919         return true;
1920 }
1921
1922 /****************************************************************************
1923  Unpack a struct security_descriptor into two canonical ace lists.
1924 ****************************************************************************/
1925
1926 static bool create_canon_ace_lists(files_struct *fsp,
1927                                         const SMB_STRUCT_STAT *pst,
1928                                         struct dom_sid *pfile_owner_sid,
1929                                         struct dom_sid *pfile_grp_sid,
1930                                         canon_ace **ppfile_ace,
1931                                         canon_ace **ppdir_ace,
1932                                         const struct security_acl *dacl)
1933 {
1934         bool all_aces_are_inherit_only = (fsp->is_directory ? True : False);
1935         canon_ace *file_ace = NULL;
1936         canon_ace *dir_ace = NULL;
1937         canon_ace *current_ace = NULL;
1938         bool got_dir_allow = False;
1939         bool got_file_allow = False;
1940         int i, j;
1941
1942         *ppfile_ace = NULL;
1943         *ppdir_ace = NULL;
1944
1945         /*
1946          * Convert the incoming ACL into a more regular form.
1947          */
1948
1949         for(i = 0; i < dacl->num_aces; i++) {
1950                 struct security_ace *psa = &dacl->aces[i];
1951
1952                 if((psa->type != SEC_ACE_TYPE_ACCESS_ALLOWED) && (psa->type != SEC_ACE_TYPE_ACCESS_DENIED)) {
1953                         DEBUG(3,("create_canon_ace_lists: unable to set anything but an ALLOW or DENY ACE.\n"));
1954                         return False;
1955                 }
1956
1957                 if (nt4_compatible_acls()) {
1958                         /*
1959                          * The security mask may be UNIX_ACCESS_NONE which should map into
1960                          * no permissions (we overload the WRITE_OWNER bit for this) or it
1961                          * should be one of the ALL/EXECUTE/READ/WRITE bits. Arrange for this
1962                          * to be so. Any other bits override the UNIX_ACCESS_NONE bit.
1963                          */
1964
1965                         /*
1966                          * Convert GENERIC bits to specific bits.
1967                          */
1968  
1969                         se_map_generic(&psa->access_mask, &file_generic_mapping);
1970
1971                         psa->access_mask &= (UNIX_ACCESS_NONE|FILE_ALL_ACCESS);
1972
1973                         if(psa->access_mask != UNIX_ACCESS_NONE)
1974                                 psa->access_mask &= ~UNIX_ACCESS_NONE;
1975                 }
1976         }
1977
1978         /*
1979          * Deal with the fact that NT 4.x re-writes the canonical format
1980          * that we return for default ACLs. If a directory ACE is identical
1981          * to a inherited directory ACE then NT changes the bits so that the
1982          * first ACE is set to OI|IO and the second ACE for this SID is set
1983          * to CI. We need to repair this. JRA.
1984          */
1985
1986         for(i = 0; i < dacl->num_aces; i++) {
1987                 struct security_ace *psa1 = &dacl->aces[i];
1988
1989                 for (j = i + 1; j < dacl->num_aces; j++) {
1990                         struct security_ace *psa2 = &dacl->aces[j];
1991
1992                         if (psa1->access_mask != psa2->access_mask)
1993                                 continue;
1994
1995                         if (!dom_sid_equal(&psa1->trustee, &psa2->trustee))
1996                                 continue;
1997
1998                         /*
1999                          * Ok - permission bits and SIDs are equal.
2000                          * Check if flags were re-written.
2001                          */
2002
2003                         if (psa1->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
2004
2005                                 psa1->flags |= (psa2->flags & (SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT));
2006                                 psa2->flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT);
2007
2008                         } else if (psa2->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
2009
2010                                 psa2->flags |= (psa1->flags & (SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT));
2011                                 psa1->flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT);
2012
2013                         }
2014                 }
2015         }
2016
2017         for(i = 0; i < dacl->num_aces; i++) {
2018                 struct security_ace *psa = &dacl->aces[i];
2019
2020                 /*
2021                  * Create a canon_ace entry representing this NT DACL ACE.
2022                  */
2023
2024                 if ((current_ace = talloc(talloc_tos(), canon_ace)) == NULL) {
2025                         free_canon_ace_list(file_ace);
2026                         free_canon_ace_list(dir_ace);
2027                         DEBUG(0,("create_canon_ace_lists: malloc fail.\n"));
2028                         return False;
2029                 }
2030
2031                 ZERO_STRUCTP(current_ace);
2032
2033                 sid_copy(&current_ace->trustee, &psa->trustee);
2034
2035                 /*
2036                  * Try and work out if the SID is a user or group
2037                  * as we need to flag these differently for POSIX.
2038                  * Note what kind of a POSIX ACL this should map to.
2039                  */
2040
2041                 if( dom_sid_equal(&current_ace->trustee, &global_sid_World)) {
2042                         current_ace->owner_type = WORLD_ACE;
2043                         current_ace->unix_ug.type = ID_TYPE_NOT_SPECIFIED;
2044                         current_ace->unix_ug.id = -1;
2045                         current_ace->type = SMB_ACL_OTHER;
2046                 } else if (dom_sid_equal(&current_ace->trustee, &global_sid_Creator_Owner)) {
2047                         current_ace->owner_type = UID_ACE;
2048                         current_ace->unix_ug.type = ID_TYPE_UID;
2049                         current_ace->unix_ug.id = pst->st_ex_uid;
2050                         current_ace->type = SMB_ACL_USER_OBJ;
2051
2052                         /*
2053                          * The Creator Owner entry only specifies inheritable permissions,
2054                          * never access permissions. WinNT doesn't always set the ACE to
2055                          * INHERIT_ONLY, though.
2056                          */
2057
2058                         psa->flags |= SEC_ACE_FLAG_INHERIT_ONLY;
2059
2060                 } else if (dom_sid_equal(&current_ace->trustee, &global_sid_Creator_Group)) {
2061                         current_ace->owner_type = GID_ACE;
2062                         current_ace->unix_ug.type = ID_TYPE_GID;
2063                         current_ace->unix_ug.id = pst->st_ex_gid;
2064                         current_ace->type = SMB_ACL_GROUP_OBJ;
2065
2066                         /*
2067                          * The Creator Group entry only specifies inheritable permissions,
2068                          * never access permissions. WinNT doesn't always set the ACE to
2069                          * INHERIT_ONLY, though.
2070                          */
2071                         psa->flags |= SEC_ACE_FLAG_INHERIT_ONLY;
2072
2073                 } else {
2074                         struct unixid unixid;
2075
2076                         if (!sids_to_unixids(&current_ace->trustee, 1, &unixid)) {
2077                                 free_canon_ace_list(file_ace);
2078                                 free_canon_ace_list(dir_ace);
2079                                 TALLOC_FREE(current_ace);
2080                                 DEBUG(0, ("create_canon_ace_lists: sids_to_unixids "
2081                                         "failed for %s (allocation failure)\n",
2082                                         sid_string_dbg(&current_ace->trustee)));
2083                                 return false;
2084                         }
2085
2086                         if (unixid.type == ID_TYPE_BOTH) {
2087                                 /* If it's the owning user, this is a
2088                                  * user_obj, not a user.  This way, we
2089                                  * get a valid ACL for groups that own
2090                                  * files, without putting user ACL
2091                                  * entries in for groups otherwise */
2092                                 if (unixid.id == pst->st_ex_uid) {
2093                                         current_ace->owner_type = UID_ACE;
2094                                         current_ace->unix_ug.type = ID_TYPE_UID;
2095                                         current_ace->unix_ug.id = unixid.id;
2096                                         current_ace->type = SMB_ACL_USER_OBJ;
2097
2098                                         /* Add the user object to the posix ACL,
2099                                            and proceed to the group mapping
2100                                            below. This handles the talloc_free
2101                                            of current_ace if not added for some
2102                                            reason */
2103                                         if (!add_current_ace_to_acl(fsp,
2104                                                         psa,
2105                                                         &file_ace,
2106                                                         &dir_ace,
2107                                                         &got_file_allow,
2108                                                         &got_dir_allow,
2109                                                         &all_aces_are_inherit_only,
2110                                                         current_ace)) {
2111                                                 free_canon_ace_list(file_ace);
2112                                                 free_canon_ace_list(dir_ace);
2113                                                 return false;
2114                                         }
2115
2116                                         if ((current_ace = talloc(talloc_tos(),
2117                                                         canon_ace)) == NULL) {
2118                                                 free_canon_ace_list(file_ace);
2119                                                 free_canon_ace_list(dir_ace);
2120                                                 DEBUG(0,("create_canon_ace_lists: "
2121                                                         "malloc fail.\n"));
2122                                                 return False;
2123                                         }
2124
2125                                         ZERO_STRUCTP(current_ace);
2126                                 }
2127
2128                                 sid_copy(&current_ace->trustee, &psa->trustee);
2129
2130                                 current_ace->unix_ug.type = ID_TYPE_GID;
2131                                 current_ace->unix_ug.id = unixid.id;
2132                                 current_ace->owner_type = GID_ACE;
2133                                 /* If it's the primary group, this is a
2134                                    group_obj, not a group. */
2135                                 if (current_ace->unix_ug.id == pst->st_ex_gid) {
2136                                         current_ace->type = SMB_ACL_GROUP_OBJ;
2137                                 } else {
2138                                         current_ace->type = SMB_ACL_GROUP;
2139                                 }
2140
2141                         } else if (unixid.type == ID_TYPE_UID) {
2142                                 current_ace->owner_type = UID_ACE;
2143                                 current_ace->unix_ug.type = ID_TYPE_UID;
2144                                 current_ace->unix_ug.id = unixid.id;
2145                                 /* If it's the owning user, this is a user_obj,
2146                                    not a user. */
2147                                 if (current_ace->unix_ug.id == pst->st_ex_uid) {
2148                                         current_ace->type = SMB_ACL_USER_OBJ;
2149                                 } else {
2150                                         current_ace->type = SMB_ACL_USER;
2151                                 }
2152                         } else if (unixid.type == ID_TYPE_GID) {
2153                                 current_ace->unix_ug.type = ID_TYPE_GID;
2154                                 current_ace->unix_ug.id = unixid.id;
2155                                 current_ace->owner_type = GID_ACE;
2156                                 /* If it's the primary group, this is a
2157                                    group_obj, not a group. */
2158                                 if (current_ace->unix_ug.id == pst->st_ex_gid) {
2159                                         current_ace->type = SMB_ACL_GROUP_OBJ;
2160                                 } else {
2161                                         current_ace->type = SMB_ACL_GROUP;
2162                                 }
2163                         } else {
2164                                 /*
2165                                  * Silently ignore map failures in non-mappable SIDs (NT Authority, BUILTIN etc).
2166                                  */
2167
2168                                 if (non_mappable_sid(&psa->trustee)) {
2169                                         DEBUG(10, ("create_canon_ace_lists: ignoring "
2170                                                    "non-mappable SID %s\n",
2171                                                    sid_string_dbg(&psa->trustee)));
2172                                         TALLOC_FREE(current_ace);
2173                                         continue;
2174                                 }
2175
2176                                 if (lp_force_unknown_acl_user(SNUM(fsp->conn))) {
2177                                         DEBUG(10, ("create_canon_ace_lists: ignoring "
2178                                                 "unknown or foreign SID %s\n",
2179                                                 sid_string_dbg(&psa->trustee)));
2180                                         TALLOC_FREE(current_ace);
2181                                         continue;
2182                                 }
2183
2184                                 free_canon_ace_list(file_ace);
2185                                 free_canon_ace_list(dir_ace);
2186                                 DEBUG(0, ("create_canon_ace_lists: unable to map SID "
2187                                           "%s to uid or gid.\n",
2188                                           sid_string_dbg(&current_ace->trustee)));
2189                                 TALLOC_FREE(current_ace);
2190                                 return false;
2191                         }
2192                 }
2193
2194                 /* handles the talloc_free of current_ace if not added for some reason */
2195                 if (!add_current_ace_to_acl(fsp, psa, &file_ace, &dir_ace,
2196                                             &got_file_allow, &got_dir_allow,
2197                                             &all_aces_are_inherit_only, current_ace)) {
2198                         free_canon_ace_list(file_ace);
2199                         free_canon_ace_list(dir_ace);
2200                         return false;
2201                 }
2202         }
2203
2204         if (fsp->is_directory && all_aces_are_inherit_only) {
2205                 /*
2206                  * Windows 2000 is doing one of these weird 'inherit acl'
2207                  * traverses to conserve NTFS ACL resources. Just pretend
2208                  * there was no DACL sent. JRA.
2209                  */
2210
2211                 DEBUG(10,("create_canon_ace_lists: Win2k inherit acl traverse. Ignoring DACL.\n"));
2212                 free_canon_ace_list(file_ace);
2213                 free_canon_ace_list(dir_ace);
2214                 file_ace = NULL;
2215                 dir_ace = NULL;
2216         } else {
2217                 /*
2218                  * Check if we have SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ entries in
2219                  * the file ACL. If we don't have them, check if any SMB_ACL_USER/SMB_ACL_GROUP
2220                  * entries can be converted to *_OBJ. Don't do this for the default
2221                  * ACL, we will create them separately for this if needed inside
2222                  * ensure_canon_entry_valid_on_set().
2223                  */
2224                 if (file_ace) {
2225                         check_owning_objs(file_ace, pfile_owner_sid, pfile_grp_sid);
2226                 }
2227         }
2228
2229         *ppfile_ace = file_ace;
2230         *ppdir_ace = dir_ace;
2231
2232         return True;
2233 }
2234
2235 /****************************************************************************
2236  ASCII art time again... JRA :-).
2237
2238  We have 4 cases to process when moving from an NT ACL to a POSIX ACL. Firstly,
2239  we insist the ACL is in canonical form (ie. all DENY entries preceede ALLOW
2240  entries). Secondly, the merge code has ensured that all duplicate SID entries for
2241  allow or deny have been merged, so the same SID can only appear once in the deny
2242  list or once in the allow list.
2243
2244  We then process as follows :
2245
2246  ---------------------------------------------------------------------------
2247  First pass - look for a Everyone DENY entry.
2248
2249  If it is deny all (rwx) trunate the list at this point.
2250  Else, walk the list from this point and use the deny permissions of this
2251  entry as a mask on all following allow entries. Finally, delete
2252  the Everyone DENY entry (we have applied it to everything possible).
2253
2254  In addition, in this pass we remove any DENY entries that have 
2255  no permissions (ie. they are a DENY nothing).
2256  ---------------------------------------------------------------------------
2257  Second pass - only deal with deny user entries.
2258
2259  DENY user1 (perms XXX)
2260
2261  new_perms = 0
2262  for all following allow group entries where user1 is in group
2263         new_perms |= group_perms;
2264
2265  user1 entry perms = new_perms & ~ XXX;
2266
2267  Convert the deny entry to an allow entry with the new perms and
2268  push to the end of the list. Note if the user was in no groups
2269  this maps to a specific allow nothing entry for this user.
2270
2271  The common case from the NT ACL choser (userX deny all) is
2272  optimised so we don't do the group lookup - we just map to
2273  an allow nothing entry.
2274
2275  What we're doing here is inferring the allow permissions the
2276  person setting the ACE on user1 wanted by looking at the allow
2277  permissions on the groups the user is currently in. This will
2278  be a snapshot, depending on group membership but is the best
2279  we can do and has the advantage of failing closed rather than
2280  open.
2281  ---------------------------------------------------------------------------
2282  Third pass - only deal with deny group entries.
2283
2284  DENY group1 (perms XXX)
2285
2286  for all following allow user entries where user is in group1
2287    user entry perms = user entry perms & ~ XXX;
2288
2289  If there is a group Everyone allow entry with permissions YYY,
2290  convert the group1 entry to an allow entry and modify its
2291  permissions to be :
2292
2293  new_perms = YYY & ~ XXX
2294
2295  and push to the end of the list.
2296
2297  If there is no group Everyone allow entry then convert the
2298  group1 entry to a allow nothing entry and push to the end of the list.
2299
2300  Note that the common case from the NT ACL choser (groupX deny all)
2301  cannot be optimised here as we need to modify user entries who are
2302  in the group to change them to a deny all also.
2303
2304  What we're doing here is modifying the allow permissions of
2305  user entries (which are more specific in POSIX ACLs) to mask
2306  out the explicit deny set on the group they are in. This will
2307  be a snapshot depending on current group membership but is the
2308  best we can do and has the advantage of failing closed rather
2309  than open.
2310  ---------------------------------------------------------------------------
2311  Fourth pass - cope with cumulative permissions.
2312
2313  for all allow user entries, if there exists an allow group entry with
2314  more permissive permissions, and the user is in that group, rewrite the
2315  allow user permissions to contain both sets of permissions.
2316
2317  Currently the code for this is #ifdef'ed out as these semantics make
2318  no sense to me. JRA.
2319  ---------------------------------------------------------------------------
2320
2321  Note we *MUST* do the deny user pass first as this will convert deny user
2322  entries into allow user entries which can then be processed by the deny
2323  group pass.
2324
2325  The above algorithm took a *lot* of thinking about - hence this
2326  explaination :-). JRA.
2327 ****************************************************************************/
2328
2329 /****************************************************************************
2330  Process a canon_ace list entries. This is very complex code. We need
2331  to go through and remove the "deny" permissions from any allow entry that matches
2332  the id of this entry. We have already refused any NT ACL that wasn't in correct
2333  order (DENY followed by ALLOW). If any allow entry ends up with zero permissions,
2334  we just remove it (to fail safe). We have already removed any duplicate ace
2335  entries. Treat an "Everyone" DENY_ACE as a special case - use it to mask all
2336  allow entries.
2337 ****************************************************************************/
2338
2339 static void process_deny_list(connection_struct *conn, canon_ace **pp_ace_list )
2340 {
2341         canon_ace *ace_list = *pp_ace_list;
2342         canon_ace *curr_ace = NULL;
2343         canon_ace *curr_ace_next = NULL;
2344
2345         /* Pass 1 above - look for an Everyone, deny entry. */
2346
2347         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2348                 canon_ace *allow_ace_p;
2349
2350                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2351
2352                 if (curr_ace->attr != DENY_ACE)
2353                         continue;
2354
2355                 if (curr_ace->perms == (mode_t)0) {
2356
2357                         /* Deny nothing entry - delete. */
2358
2359                         DLIST_REMOVE(ace_list, curr_ace);
2360                         continue;
2361                 }
2362
2363                 if (!dom_sid_equal(&curr_ace->trustee, &global_sid_World))
2364                         continue;
2365
2366                 /* JRATEST - assert. */
2367                 SMB_ASSERT(curr_ace->owner_type == WORLD_ACE);
2368
2369                 if (curr_ace->perms == ALL_ACE_PERMS) {
2370
2371                         /*
2372                          * Optimisation. This is a DENY_ALL to Everyone. Truncate the
2373                          * list at this point including this entry.
2374                          */
2375
2376                         canon_ace *prev_entry = DLIST_PREV(curr_ace);
2377
2378                         free_canon_ace_list( curr_ace );
2379                         if (prev_entry)
2380                                 DLIST_REMOVE(ace_list, prev_entry);
2381                         else {
2382                                 /* We deleted the entire list. */
2383                                 ace_list = NULL;
2384                         }
2385                         break;
2386                 }
2387
2388                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2389
2390                         /* 
2391                          * Only mask off allow entries.
2392                          */
2393
2394                         if (allow_ace_p->attr != ALLOW_ACE)
2395                                 continue;
2396
2397                         allow_ace_p->perms &= ~curr_ace->perms;
2398                 }
2399
2400                 /*
2401                  * Now it's been applied, remove it.
2402                  */
2403
2404                 DLIST_REMOVE(ace_list, curr_ace);
2405         }
2406
2407         /* Pass 2 above - deal with deny user entries. */
2408
2409         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2410                 mode_t new_perms = (mode_t)0;
2411                 canon_ace *allow_ace_p;
2412
2413                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2414
2415                 if (curr_ace->attr != DENY_ACE)
2416                         continue;
2417
2418                 if (curr_ace->owner_type != UID_ACE)
2419                         continue;
2420
2421                 if (curr_ace->perms == ALL_ACE_PERMS) {
2422
2423                         /*
2424                          * Optimisation - this is a deny everything to this user.
2425                          * Convert to an allow nothing and push to the end of the list.
2426                          */
2427
2428                         curr_ace->attr = ALLOW_ACE;
2429                         curr_ace->perms = (mode_t)0;
2430                         DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2431                         continue;
2432                 }
2433
2434                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2435
2436                         if (allow_ace_p->attr != ALLOW_ACE)
2437                                 continue;
2438
2439                         /* We process GID_ACE and WORLD_ACE entries only. */
2440
2441                         if (allow_ace_p->owner_type == UID_ACE)
2442                                 continue;
2443
2444                         if (uid_entry_in_group(conn, curr_ace, allow_ace_p))
2445                                 new_perms |= allow_ace_p->perms;
2446                 }
2447
2448                 /*
2449                  * Convert to a allow entry, modify the perms and push to the end
2450                  * of the list.
2451                  */
2452
2453                 curr_ace->attr = ALLOW_ACE;
2454                 curr_ace->perms = (new_perms & ~curr_ace->perms);
2455                 DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2456         }
2457
2458         /* Pass 3 above - deal with deny group entries. */
2459
2460         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2461                 canon_ace *allow_ace_p;
2462                 canon_ace *allow_everyone_p = NULL;
2463
2464                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2465
2466                 if (curr_ace->attr != DENY_ACE)
2467                         continue;
2468
2469                 if (curr_ace->owner_type != GID_ACE)
2470                         continue;
2471
2472                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2473
2474                         if (allow_ace_p->attr != ALLOW_ACE)
2475                                 continue;
2476
2477                         /* Store a pointer to the Everyone allow, if it exists. */
2478                         if (allow_ace_p->owner_type == WORLD_ACE)
2479                                 allow_everyone_p = allow_ace_p;
2480
2481                         /* We process UID_ACE entries only. */
2482
2483                         if (allow_ace_p->owner_type != UID_ACE)
2484                                 continue;
2485
2486                         /* Mask off the deny group perms. */
2487
2488                         if (uid_entry_in_group(conn, allow_ace_p, curr_ace))
2489                                 allow_ace_p->perms &= ~curr_ace->perms;
2490                 }
2491
2492                 /*
2493                  * Convert the deny to an allow with the correct perms and
2494                  * push to the end of the list.
2495                  */
2496
2497                 curr_ace->attr = ALLOW_ACE;
2498                 if (allow_everyone_p)
2499                         curr_ace->perms = allow_everyone_p->perms & ~curr_ace->perms;
2500                 else
2501                         curr_ace->perms = (mode_t)0;
2502                 DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2503         }
2504
2505         /* Doing this fourth pass allows Windows semantics to be layered
2506          * on top of POSIX semantics. I'm not sure if this is desirable.
2507          * For example, in W2K ACLs there is no way to say, "Group X no
2508          * access, user Y full access" if user Y is a member of group X.
2509          * This seems completely broken semantics to me.... JRA.
2510          */
2511
2512 #if 0
2513         /* Pass 4 above - deal with allow entries. */
2514
2515         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2516                 canon_ace *allow_ace_p;
2517
2518                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2519
2520                 if (curr_ace->attr != ALLOW_ACE)
2521                         continue;
2522
2523                 if (curr_ace->owner_type != UID_ACE)
2524                         continue;
2525
2526                 for (allow_ace_p = ace_list; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2527
2528                         if (allow_ace_p->attr != ALLOW_ACE)
2529                                 continue;
2530
2531                         /* We process GID_ACE entries only. */
2532
2533                         if (allow_ace_p->owner_type != GID_ACE)
2534                                 continue;
2535
2536                         /* OR in the group perms. */
2537
2538                         if (uid_entry_in_group(conn, curr_ace, allow_ace_p))
2539                                 curr_ace->perms |= allow_ace_p->perms;
2540                 }
2541         }
2542 #endif
2543
2544         *pp_ace_list = ace_list;
2545 }
2546
2547 /****************************************************************************
2548  Unpack a struct security_descriptor into two canonical ace lists. We don't depend on this
2549  succeeding.
2550 ****************************************************************************/
2551
2552 static bool unpack_canon_ace(files_struct *fsp,
2553                                 const SMB_STRUCT_STAT *pst,
2554                                 struct dom_sid *pfile_owner_sid,
2555                                 struct dom_sid *pfile_grp_sid,
2556                                 canon_ace **ppfile_ace,
2557                                 canon_ace **ppdir_ace,
2558                                 uint32 security_info_sent,
2559                                 const struct security_descriptor *psd)
2560 {
2561         canon_ace *file_ace = NULL;
2562         canon_ace *dir_ace = NULL;
2563
2564         *ppfile_ace = NULL;
2565         *ppdir_ace = NULL;
2566
2567         if(security_info_sent == 0) {
2568                 DEBUG(0,("unpack_canon_ace: no security info sent !\n"));
2569                 return False;
2570         }
2571
2572         /*
2573          * If no DACL then this is a chown only security descriptor.
2574          */
2575
2576         if(!(security_info_sent & SECINFO_DACL) || !psd->dacl)
2577                 return True;
2578
2579         /*
2580          * Now go through the DACL and create the canon_ace lists.
2581          */
2582
2583         if (!create_canon_ace_lists( fsp, pst, pfile_owner_sid, pfile_grp_sid,
2584                                                                 &file_ace, &dir_ace, psd->dacl))
2585                 return False;
2586
2587         if ((file_ace == NULL) && (dir_ace == NULL)) {
2588                 /* W2K traverse DACL set - ignore. */
2589                 return True;
2590         }
2591
2592         /*
2593          * Go through the canon_ace list and merge entries
2594          * belonging to identical users of identical allow or deny type.
2595          * We can do this as all deny entries come first, followed by
2596          * all allow entries (we have mandated this before accepting this acl).
2597          */
2598
2599         print_canon_ace_list( "file ace - before merge", file_ace);
2600         merge_aces( &file_ace, false);
2601
2602         print_canon_ace_list( "dir ace - before merge", dir_ace);
2603         merge_aces( &dir_ace, true);
2604
2605         /*
2606          * NT ACLs are order dependent. Go through the acl lists and
2607          * process DENY entries by masking the allow entries.
2608          */
2609
2610         print_canon_ace_list( "file ace - before deny", file_ace);
2611         process_deny_list(fsp->conn, &file_ace);
2612
2613         print_canon_ace_list( "dir ace - before deny", dir_ace);
2614         process_deny_list(fsp->conn, &dir_ace);
2615
2616         /*
2617          * A well formed POSIX file or default ACL has at least 3 entries, a 
2618          * SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER_OBJ
2619          * and optionally a mask entry. Ensure this is the case.
2620          */
2621
2622         print_canon_ace_list( "file ace - before valid", file_ace);
2623
2624         if (!ensure_canon_entry_valid_on_set(fsp->conn, &file_ace, false, fsp->conn->params,
2625                         fsp->is_directory, pfile_owner_sid, pfile_grp_sid, pst)) {
2626                 free_canon_ace_list(file_ace);
2627                 free_canon_ace_list(dir_ace);
2628                 return False;
2629         }
2630
2631         print_canon_ace_list( "dir ace - before valid", dir_ace);
2632
2633         if (dir_ace && !ensure_canon_entry_valid_on_set(fsp->conn, &dir_ace, true, fsp->conn->params,
2634                         fsp->is_directory, pfile_owner_sid, pfile_grp_sid, pst)) {
2635                 free_canon_ace_list(file_ace);
2636                 free_canon_ace_list(dir_ace);
2637                 return False;
2638         }
2639
2640         print_canon_ace_list( "file ace - return", file_ace);
2641         print_canon_ace_list( "dir ace - return", dir_ace);
2642
2643         *ppfile_ace = file_ace;
2644         *ppdir_ace = dir_ace;
2645         return True;
2646
2647 }
2648
2649 /******************************************************************************
2650  When returning permissions, try and fit NT display
2651  semantics if possible. Note the the canon_entries here must have been malloced.
2652  The list format should be - first entry = owner, followed by group and other user
2653  entries, last entry = other.
2654
2655  Note that this doesn't exactly match the NT semantics for an ACL. As POSIX entries
2656  are not ordered, and match on the most specific entry rather than walking a list,
2657  then a simple POSIX permission of rw-r--r-- should really map to 5 entries,
2658
2659  Entry 0: owner : deny all except read and write.
2660  Entry 1: owner : allow read and write.
2661  Entry 2: group : deny all except read.
2662  Entry 3: group : allow read.
2663  Entry 4: Everyone : allow read.
2664
2665  But NT cannot display this in their ACL editor !
2666 ********************************************************************************/
2667
2668 static void arrange_posix_perms(const char *filename, canon_ace **pp_list_head)
2669 {
2670         canon_ace *l_head = *pp_list_head;
2671         canon_ace *owner_ace = NULL;
2672         canon_ace *other_ace = NULL;
2673         canon_ace *ace = NULL;
2674
2675         for (ace = l_head; ace; ace = ace->next) {
2676                 if (ace->type == SMB_ACL_USER_OBJ)
2677                         owner_ace = ace;
2678                 else if (ace->type == SMB_ACL_OTHER) {
2679                         /* Last ace - this is "other" */
2680                         other_ace = ace;
2681                 }
2682         }
2683
2684         if (!owner_ace || !other_ace) {
2685                 DEBUG(0,("arrange_posix_perms: Invalid POSIX permissions for file %s, missing owner or other.\n",
2686                         filename ));
2687                 return;
2688         }
2689
2690         /*
2691          * The POSIX algorithm applies to owner first, and other last,
2692          * so ensure they are arranged in this order.
2693          */
2694
2695         if (owner_ace) {
2696                 DLIST_PROMOTE(l_head, owner_ace);
2697         }
2698
2699         if (other_ace) {
2700                 DLIST_DEMOTE(l_head, other_ace, canon_ace *);
2701         }
2702
2703         /* We have probably changed the head of the list. */
2704
2705         *pp_list_head = l_head;
2706 }
2707
2708 /****************************************************************************
2709  Create a linked list of canonical ACE entries.
2710 ****************************************************************************/
2711
2712 static canon_ace *canonicalise_acl(struct connection_struct *conn,
2713                                    const char *fname, SMB_ACL_T posix_acl,
2714                                    const SMB_STRUCT_STAT *psbuf,
2715                                    const struct dom_sid *powner, const struct dom_sid *pgroup, struct pai_val *pal, SMB_ACL_TYPE_T the_acl_type)
2716 {
2717         mode_t acl_mask = (S_IRUSR|S_IWUSR|S_IXUSR);
2718         canon_ace *l_head = NULL;
2719         canon_ace *ace = NULL;
2720         canon_ace *next_ace = NULL;
2721         int entry_id = SMB_ACL_FIRST_ENTRY;
2722         bool is_default_acl = (the_acl_type == SMB_ACL_TYPE_DEFAULT);
2723         SMB_ACL_ENTRY_T entry;
2724         size_t ace_count;
2725
2726         while ( posix_acl && (sys_acl_get_entry(posix_acl, entry_id, &entry) == 1)) {
2727                 SMB_ACL_TAG_T tagtype;
2728                 SMB_ACL_PERMSET_T permset;
2729                 struct dom_sid sid;
2730                 struct unixid unix_ug;
2731                 enum ace_owner owner_type;
2732
2733                 entry_id = SMB_ACL_NEXT_ENTRY;
2734
2735                 /* Is this a MASK entry ? */
2736                 if (sys_acl_get_tag_type(entry, &tagtype) == -1)
2737                         continue;
2738
2739                 if (sys_acl_get_permset(entry, &permset) == -1)
2740                         continue;
2741
2742                 /* Decide which SID to use based on the ACL type. */
2743                 switch(tagtype) {
2744                         case SMB_ACL_USER_OBJ:
2745                                 /* Get the SID from the owner. */
2746                                 sid_copy(&sid, powner);
2747                                 unix_ug.type = ID_TYPE_UID;
2748                                 unix_ug.id = psbuf->st_ex_uid;
2749                                 owner_type = UID_ACE;
2750                                 break;
2751                         case SMB_ACL_USER:
2752                                 {
2753                                         uid_t *puid = (uid_t *)sys_acl_get_qualifier(entry);
2754                                         if (puid == NULL) {
2755                                                 DEBUG(0,("canonicalise_acl: Failed to get uid.\n"));
2756                                                 continue;
2757                                         }
2758                                         uid_to_sid( &sid, *puid);
2759                                         unix_ug.type = ID_TYPE_UID;
2760                                         unix_ug.id = *puid;
2761                                         owner_type = UID_ACE;
2762                                         break;
2763                                 }
2764                         case SMB_ACL_GROUP_OBJ:
2765                                 /* Get the SID from the owning group. */
2766                                 sid_copy(&sid, pgroup);
2767                                 unix_ug.type = ID_TYPE_GID;
2768                                 unix_ug.id = psbuf->st_ex_gid;
2769                                 owner_type = GID_ACE;
2770                                 break;
2771                         case SMB_ACL_GROUP:
2772                                 {
2773                                         gid_t *pgid = (gid_t *)sys_acl_get_qualifier(entry);
2774                                         if (pgid == NULL) {
2775                                                 DEBUG(0,("canonicalise_acl: Failed to get gid.\n"));
2776                                                 continue;
2777                                         }
2778                                         gid_to_sid( &sid, *pgid);
2779                                         unix_ug.type = ID_TYPE_GID;
2780                                         unix_ug.id = *pgid;
2781                                         owner_type = GID_ACE;
2782                                         break;
2783                                 }
2784                         case SMB_ACL_MASK:
2785                                 acl_mask = convert_permset_to_mode_t(permset);
2786                                 continue; /* Don't count the mask as an entry. */
2787                         case SMB_ACL_OTHER:
2788                                 /* Use the Everyone SID */
2789                                 sid = global_sid_World;
2790                                 unix_ug.type = ID_TYPE_NOT_SPECIFIED;
2791                                 unix_ug.id = -1;
2792                                 owner_type = WORLD_ACE;
2793                                 break;
2794                         default:
2795                                 DEBUG(0,("canonicalise_acl: Unknown tagtype %u\n", (unsigned int)tagtype));
2796                                 continue;
2797                 }
2798
2799                 /*
2800                  * Add this entry to the list.
2801                  */
2802
2803                 if ((ace = talloc(talloc_tos(), canon_ace)) == NULL)
2804                         goto fail;
2805
2806                 ZERO_STRUCTP(ace);
2807                 ace->type = tagtype;
2808                 ace->perms = convert_permset_to_mode_t(permset);
2809                 ace->attr = ALLOW_ACE;
2810                 ace->trustee = sid;
2811                 ace->unix_ug = unix_ug;
2812                 ace->owner_type = owner_type;
2813                 ace->ace_flags = get_pai_flags(pal, ace, is_default_acl);
2814
2815                 DLIST_ADD(l_head, ace);
2816         }
2817
2818         /*
2819          * This next call will ensure we have at least a user/group/world set.
2820          */
2821
2822         if (!ensure_canon_entry_valid_on_get(conn, &l_head,
2823                                       powner, pgroup,
2824                                       psbuf))
2825                 goto fail;
2826
2827         /*
2828          * Now go through the list, masking the permissions with the
2829          * acl_mask. Ensure all DENY Entries are at the start of the list.
2830          */
2831
2832         DEBUG(10,("canonicalise_acl: %s ace entries before arrange :\n", is_default_acl ?  "Default" : "Access"));
2833
2834         for ( ace_count = 0, ace = l_head; ace; ace = next_ace, ace_count++) {
2835                 next_ace = ace->next;
2836
2837                 /* Masks are only applied to entries other than USER_OBJ and OTHER. */
2838                 if (ace->type != SMB_ACL_OTHER && ace->type != SMB_ACL_USER_OBJ)
2839                         ace->perms &= acl_mask;
2840
2841                 if (ace->perms == 0) {
2842                         DLIST_PROMOTE(l_head, ace);
2843                 }
2844
2845                 if( DEBUGLVL( 10 ) ) {
2846                         print_canon_ace(ace, ace_count);
2847                 }
2848         }
2849
2850         arrange_posix_perms(fname,&l_head );
2851
2852         print_canon_ace_list( "canonicalise_acl: ace entries after arrange", l_head );
2853
2854         return l_head;
2855
2856   fail:
2857
2858         free_canon_ace_list(l_head);
2859         return NULL;
2860 }
2861
2862 /****************************************************************************
2863  Check if the current user group list contains a given group.
2864 ****************************************************************************/
2865
2866 bool current_user_in_group(connection_struct *conn, gid_t gid)
2867 {
2868         int i;
2869         const struct security_unix_token *utok = get_current_utok(conn);
2870
2871         for (i = 0; i < utok->ngroups; i++) {
2872                 if (utok->groups[i] == gid) {
2873                         return True;
2874                 }
2875         }
2876
2877         return False;
2878 }
2879
2880 /****************************************************************************
2881  Should we override a deny ? Check 'acl group control' and 'dos filemode'.
2882 ****************************************************************************/
2883
2884 static bool acl_group_override(connection_struct *conn,
2885                                const struct smb_filename *smb_fname)
2886 {
2887         if ((errno != EPERM) && (errno != EACCES)) {
2888                 return false;
2889         }
2890
2891         /* file primary group == user primary or supplementary group */
2892         if (lp_acl_group_control(SNUM(conn)) &&
2893             current_user_in_group(conn, smb_fname->st.st_ex_gid)) {
2894                 return true;
2895         }
2896
2897         /* user has writeable permission */
2898         if (lp_dos_filemode(SNUM(conn)) &&
2899             can_write_to_file(conn, smb_fname)) {
2900                 return true;
2901         }
2902
2903         return false;
2904 }
2905
2906 /****************************************************************************
2907  Attempt to apply an ACL to a file or directory.
2908 ****************************************************************************/
2909
2910 static bool set_canon_ace_list(files_struct *fsp,
2911                                 canon_ace *the_ace,
2912                                 bool default_ace,
2913                                 const SMB_STRUCT_STAT *psbuf,
2914                                 bool *pacl_set_support)
2915 {
2916         connection_struct *conn = fsp->conn;
2917         bool ret = False;
2918         SMB_ACL_T the_acl = sys_acl_init();
2919         canon_ace *p_ace;
2920         int i;
2921         SMB_ACL_ENTRY_T mask_entry;
2922         bool got_mask_entry = False;
2923         SMB_ACL_PERMSET_T mask_permset;
2924         SMB_ACL_TYPE_T the_acl_type = (default_ace ? SMB_ACL_TYPE_DEFAULT : SMB_ACL_TYPE_ACCESS);
2925         bool needs_mask = False;
2926         mode_t mask_perms = 0;
2927
2928         /* Use the psbuf that was passed in. */
2929         if (psbuf != &fsp->fsp_name->st) {
2930                 fsp->fsp_name->st = *psbuf;
2931         }
2932
2933 #if defined(POSIX_ACL_NEEDS_MASK)
2934         /* HP-UX always wants to have a mask (called "class" there). */
2935         needs_mask = True;
2936 #endif
2937
2938         if (the_acl == NULL) {
2939                 DEBUG(0, ("sys_acl_init failed to allocate an ACL\n"));
2940                 return false;
2941         }
2942
2943         if( DEBUGLVL( 10 )) {
2944                 dbgtext("set_canon_ace_list: setting ACL:\n");
2945                 for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) {
2946                         print_canon_ace( p_ace, i);
2947                 }
2948         }
2949
2950         for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) {
2951                 SMB_ACL_ENTRY_T the_entry;
2952                 SMB_ACL_PERMSET_T the_permset;
2953
2954                 /*
2955                  * ACLs only "need" an ACL_MASK entry if there are any named user or
2956                  * named group entries. But if there is an ACL_MASK entry, it applies
2957                  * to ACL_USER, ACL_GROUP, and ACL_GROUP_OBJ entries. Set the mask
2958                  * so that it doesn't deny (i.e., mask off) any permissions.
2959                  */
2960
2961                 if (p_ace->type == SMB_ACL_USER || p_ace->type == SMB_ACL_GROUP) {
2962                         needs_mask = True;
2963                         mask_perms |= p_ace->perms;
2964                 } else if (p_ace->type == SMB_ACL_GROUP_OBJ) {
2965                         mask_perms |= p_ace->perms;
2966                 }
2967
2968                 /*
2969                  * Get the entry for this ACE.
2970                  */
2971
2972                 if (sys_acl_create_entry(&the_acl, &the_entry) == -1) {
2973                         DEBUG(0,("set_canon_ace_list: Failed to create entry %d. (%s)\n",
2974                                 i, strerror(errno) ));
2975                         goto fail;
2976                 }
2977
2978                 if (p_ace->type == SMB_ACL_MASK) {
2979                         mask_entry = the_entry;
2980                         got_mask_entry = True;
2981                 }
2982
2983                 /*
2984                  * Ok - we now know the ACL calls should be working, don't
2985                  * allow fallback to chmod.
2986                  */
2987
2988                 *pacl_set_support = True;
2989
2990                 /*
2991                  * Initialise the entry from the canon_ace.
2992                  */
2993
2994                 /*
2995                  * First tell the entry what type of ACE this is.
2996                  */
2997
2998                 if (sys_acl_set_tag_type(the_entry, p_ace->type) == -1) {
2999                         DEBUG(0,("set_canon_ace_list: Failed to set tag type on entry %d. (%s)\n",
3000                                 i, strerror(errno) ));
3001                         goto fail;
3002                 }
3003
3004                 /*
3005                  * Only set the qualifier (user or group id) if the entry is a user
3006                  * or group id ACE.
3007                  */
3008
3009                 if ((p_ace->type == SMB_ACL_USER) || (p_ace->type == SMB_ACL_GROUP)) {
3010                         if (sys_acl_set_qualifier(the_entry,(void *)&p_ace->unix_ug.id) == -1) {
3011                                 DEBUG(0,("set_canon_ace_list: Failed to set qualifier on entry %d. (%s)\n",
3012                                         i, strerror(errno) ));
3013                                 goto fail;
3014                         }
3015                 }
3016
3017                 /*
3018                  * Convert the mode_t perms in the canon_ace to a POSIX permset.
3019                  */
3020
3021                 if (sys_acl_get_permset(the_entry, &the_permset) == -1) {
3022                         DEBUG(0,("set_canon_ace_list: Failed to get permset on entry %d. (%s)\n",
3023                                 i, strerror(errno) ));
3024                         goto fail;
3025                 }
3026
3027                 if (map_acl_perms_to_permset(conn, p_ace->perms, &the_permset) == -1) {
3028                         DEBUG(0,("set_canon_ace_list: Failed to create permset for mode (%u) on entry %d. (%s)\n",
3029                                 (unsigned int)p_ace->perms, i, strerror(errno) ));
3030                         goto fail;
3031                 }
3032
3033                 /*
3034                  * ..and apply them to the entry.
3035                  */
3036
3037                 if (sys_acl_set_permset(the_entry, the_permset) == -1) {
3038                         DEBUG(0,("set_canon_ace_list: Failed to add permset on entry %d. (%s)\n",
3039                                 i, strerror(errno) ));
3040                         goto fail;
3041                 }
3042
3043                 if( DEBUGLVL( 10 ))
3044                         print_canon_ace( p_ace, i);
3045
3046         }
3047
3048         if (needs_mask && !got_mask_entry) {
3049                 if (sys_acl_create_entry(&the_acl, &mask_entry) == -1) {
3050                         DEBUG(0,("set_canon_ace_list: Failed to create mask entry. (%s)\n", strerror(errno) ));
3051                         goto fail;
3052                 }
3053
3054                 if (sys_acl_set_tag_type(mask_entry, SMB_ACL_MASK) == -1) {
3055                         DEBUG(0,("set_canon_ace_list: Failed to set tag type on mask entry. (%s)\n",strerror(errno) ));
3056                         goto fail;
3057                 }
3058
3059                 if (sys_acl_get_permset(mask_entry, &mask_permset) == -1) {
3060                         DEBUG(0,("set_canon_ace_list: Failed to get mask permset. (%s)\n", strerror(errno) ));
3061                         goto fail;
3062                 }
3063
3064                 if (map_acl_perms_to_permset(conn, S_IRUSR|S_IWUSR|S_IXUSR, &mask_permset) == -1) {
3065                         DEBUG(0,("set_canon_ace_list: Failed to create mask permset. (%s)\n", strerror(errno) ));
3066                         goto fail;
3067                 }
3068
3069                 if (sys_acl_set_permset(mask_entry, mask_permset) == -1) {
3070                         DEBUG(0,("set_canon_ace_list: Failed to add mask permset. (%s)\n", strerror(errno) ));
3071                         goto fail;
3072                 }
3073         }
3074
3075         /*
3076          * Finally apply it to the file or directory.
3077          */
3078
3079         if(default_ace || fsp->is_directory || fsp->fh->fd == -1) {
3080                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fsp->fsp_name->base_name,
3081                                              the_acl_type, the_acl) == -1) {
3082                         /*
3083                          * Some systems allow all the above calls and only fail with no ACL support
3084                          * when attempting to apply the acl. HPUX with HFS is an example of this. JRA.
3085                          */
3086                         if (no_acl_syscall_error(errno)) {
3087                                 *pacl_set_support = False;
3088                         }
3089
3090                         if (acl_group_override(conn, fsp->fsp_name)) {
3091                                 int sret;
3092
3093                                 DEBUG(5,("set_canon_ace_list: acl group "
3094                                          "control on and current user in file "
3095                                          "%s primary group.\n",
3096                                          fsp_str_dbg(fsp)));
3097
3098                                 become_root();
3099                                 sret = SMB_VFS_SYS_ACL_SET_FILE(conn,
3100                                     fsp->fsp_name->base_name, the_acl_type,
3101                                     the_acl);
3102                                 unbecome_root();
3103                                 if (sret == 0) {
3104                                         ret = True;     
3105                                 }
3106                         }
3107
3108                         if (ret == False) {
3109                                 DEBUG(2,("set_canon_ace_list: "
3110                                          "sys_acl_set_file type %s failed for "
3111                                          "file %s (%s).\n",
3112                                          the_acl_type == SMB_ACL_TYPE_DEFAULT ?
3113                                          "directory default" : "file",
3114                                          fsp_str_dbg(fsp), strerror(errno)));
3115                                 goto fail;
3116                         }
3117                 }
3118         } else {
3119                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl) == -1) {
3120                         /*
3121                          * Some systems allow all the above calls and only fail with no ACL support
3122                          * when attempting to apply the acl. HPUX with HFS is an example of this. JRA.
3123                          */
3124                         if (no_acl_syscall_error(errno)) {
3125                                 *pacl_set_support = False;
3126                         }
3127
3128                         if (acl_group_override(conn, fsp->fsp_name)) {
3129                                 int sret;
3130
3131                                 DEBUG(5,("set_canon_ace_list: acl group "
3132                                          "control on and current user in file "
3133                                          "%s primary group.\n",
3134                                          fsp_str_dbg(fsp)));
3135
3136                                 become_root();
3137                                 sret = SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl);
3138                                 unbecome_root();
3139                                 if (sret == 0) {
3140                                         ret = True;
3141                                 }
3142                         }
3143
3144                         if (ret == False) {
3145                                 DEBUG(2,("set_canon_ace_list: "
3146                                          "sys_acl_set_file failed for file %s "
3147                                          "(%s).\n",
3148                                          fsp_str_dbg(fsp), strerror(errno)));
3149                                 goto fail;
3150                         }
3151                 }
3152         }
3153
3154         ret = True;
3155
3156   fail:
3157
3158         if (the_acl != NULL) {
3159                 TALLOC_FREE(the_acl);
3160         }
3161
3162         return ret;
3163 }
3164
3165 /****************************************************************************
3166  Find a particular canon_ace entry.
3167 ****************************************************************************/
3168
3169 static struct canon_ace *canon_ace_entry_for(struct canon_ace *list, SMB_ACL_TAG_T type, struct unixid *id)
3170 {
3171         while (list) {
3172                 if (list->type == type && ((type != SMB_ACL_USER && type != SMB_ACL_GROUP) ||
3173                                 (type == SMB_ACL_USER  && id && id->id == list->unix_ug.id) ||
3174                                 (type == SMB_ACL_GROUP && id && id->id == list->unix_ug.id)))
3175                         break;
3176                 list = list->next;
3177         }
3178         return list;
3179 }
3180
3181 /****************************************************************************
3182  
3183 ****************************************************************************/
3184
3185 SMB_ACL_T free_empty_sys_acl(connection_struct *conn, SMB_ACL_T the_acl)
3186 {
3187         SMB_ACL_ENTRY_T entry;
3188
3189         if (!the_acl)
3190                 return NULL;
3191         if (sys_acl_get_entry(the_acl, SMB_ACL_FIRST_ENTRY, &entry) != 1) {
3192                 TALLOC_FREE(the_acl);
3193                 return NULL;
3194         }
3195         return the_acl;
3196 }
3197
3198 /****************************************************************************
3199  Convert a canon_ace to a generic 3 element permission - if possible.
3200 ****************************************************************************/
3201
3202 #define MAP_PERM(p,mask,result) (((p) & (mask)) ? (result) : 0 )
3203
3204 static bool convert_canon_ace_to_posix_perms( files_struct *fsp, canon_ace *file_ace_list, mode_t *posix_perms)
3205 {
3206         int snum = SNUM(fsp->conn);
3207         size_t ace_count = count_canon_ace_list(file_ace_list);
3208         canon_ace *ace_p;
3209         canon_ace *owner_ace = NULL;
3210         canon_ace *group_ace = NULL;
3211         canon_ace *other_ace = NULL;
3212         mode_t and_bits;
3213         mode_t or_bits;
3214
3215         if (ace_count != 3) {
3216                 DEBUG(3,("convert_canon_ace_to_posix_perms: Too many ACE "
3217                          "entries for file %s to convert to posix perms.\n",
3218                          fsp_str_dbg(fsp)));
3219                 return False;
3220         }
3221
3222         for (ace_p = file_ace_list; ace_p; ace_p = ace_p->next) {
3223                 if (ace_p->owner_type == UID_ACE)
3224                         owner_ace = ace_p;
3225                 else if (ace_p->owner_type == GID_ACE)
3226                         group_ace = ace_p;
3227                 else if (ace_p->owner_type == WORLD_ACE)
3228                         other_ace = ace_p;
3229         }
3230
3231         if (!owner_ace || !group_ace || !other_ace) {
3232                 DEBUG(3,("convert_canon_ace_to_posix_perms: Can't get "
3233                          "standard entries for file %s.\n", fsp_str_dbg(fsp)));
3234                 return False;
3235         }
3236
3237         *posix_perms = (mode_t)0;
3238
3239         *posix_perms |= owner_ace->perms;
3240         *posix_perms |= MAP_PERM(group_ace->perms, S_IRUSR, S_IRGRP);
3241         *posix_perms |= MAP_PERM(group_ace->perms, S_IWUSR, S_IWGRP);
3242         *posix_perms |= MAP_PERM(group_ace->perms, S_IXUSR, S_IXGRP);
3243         *posix_perms |= MAP_PERM(other_ace->perms, S_IRUSR, S_IROTH);
3244         *posix_perms |= MAP_PERM(other_ace->perms, S_IWUSR, S_IWOTH);
3245         *posix_perms |= MAP_PERM(other_ace->perms, S_IXUSR, S_IXOTH);
3246
3247         /* The owner must have at least read access. */
3248
3249         *posix_perms |= S_IRUSR;
3250         if (fsp->is_directory)
3251                 *posix_perms |= (S_IWUSR|S_IXUSR);
3252
3253         /* If requested apply the masks. */
3254
3255         /* Get the initial bits to apply. */
3256
3257         if (fsp->is_directory) {
3258                 and_bits = lp_dir_mask(snum);
3259                 or_bits = lp_force_dir_mode(snum);
3260         } else {
3261                 and_bits = lp_create_mask(snum);
3262                 or_bits = lp_force_create_mode(snum);
3263         }
3264
3265         *posix_perms = (((*posix_perms) & and_bits)|or_bits);
3266
3267         DEBUG(10,("convert_canon_ace_to_posix_perms: converted u=%o,g=%o,w=%o "
3268                   "to perm=0%o for file %s.\n", (int)owner_ace->perms,
3269                   (int)group_ace->perms, (int)other_ace->perms,
3270                   (int)*posix_perms, fsp_str_dbg(fsp)));
3271
3272         return True;
3273 }
3274
3275 /****************************************************************************
3276   Incoming NT ACLs on a directory can be split into a default POSIX acl (CI|OI|IO) and
3277   a normal POSIX acl. Win2k needs these split acls re-merging into one ACL
3278   with CI|OI set so it is inherited and also applies to the directory.
3279   Based on code from "Jim McDonough" <jmcd@us.ibm.com>.
3280 ****************************************************************************/
3281
3282 static size_t merge_default_aces( struct security_ace *nt_ace_list, size_t num_aces)
3283 {
3284         size_t i, j;
3285
3286         for (i = 0; i < num_aces; i++) {
3287                 for (j = i+1; j < num_aces; j++) {
3288                         uint32 i_flags_ni = (nt_ace_list[i].flags & ~SEC_ACE_FLAG_INHERITED_ACE);
3289                         uint32 j_flags_ni = (nt_ace_list[j].flags & ~SEC_ACE_FLAG_INHERITED_ACE);
3290                         bool i_inh = (nt_ace_list[i].flags & SEC_ACE_FLAG_INHERITED_ACE) ? True : False;
3291                         bool j_inh = (nt_ace_list[j].flags & SEC_ACE_FLAG_INHERITED_ACE) ? True : False;
3292
3293                         /* We know the lower number ACE's are file entries. */
3294                         if ((nt_ace_list[i].type == nt_ace_list[j].type) &&
3295                                 (nt_ace_list[i].size == nt_ace_list[j].size) &&
3296                                 (nt_ace_list[i].access_mask == nt_ace_list[j].access_mask) &&
3297                                 dom_sid_equal(&nt_ace_list[i].trustee, &nt_ace_list[j].trustee) &&
3298                                 (i_inh == j_inh) &&
3299                                 (i_flags_ni == 0) &&
3300                                 (j_flags_ni == (SEC_ACE_FLAG_OBJECT_INHERIT|
3301                                                   SEC_ACE_FLAG_CONTAINER_INHERIT|
3302                                                   SEC_ACE_FLAG_INHERIT_ONLY))) {
3303                                 /*
3304                                  * W2K wants to have access allowed zero access ACE's
3305                                  * at the end of the list. If the mask is zero, merge
3306                                  * the non-inherited ACE onto the inherited ACE.
3307                                  */
3308
3309                                 if (nt_ace_list[i].access_mask == 0) {
3310                                         nt_ace_list[j].flags = SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
3311                                                                 (i_inh ? SEC_ACE_FLAG_INHERITED_ACE : 0);
3312                                         if (num_aces - i - 1 > 0)
3313                                                 memmove(&nt_ace_list[i], &nt_ace_list[i+1], (num_aces-i-1) *
3314                                                                 sizeof(struct security_ace));
3315
3316                                         DEBUG(10,("merge_default_aces: Merging zero access ACE %u onto ACE %u.\n",
3317                                                 (unsigned int)i, (unsigned int)j ));
3318                                 } else {
3319                                         /*
3320                                          * These are identical except for the flags.
3321                                          * Merge the inherited ACE onto the non-inherited ACE.
3322                                          */
3323
3324                                         nt_ace_list[i].flags = SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
3325                                                                 (i_inh ? SEC_ACE_FLAG_INHERITED_ACE : 0);
3326                                         if (num_aces - j - 1 > 0)
3327                                                 memmove(&nt_ace_list[j], &nt_ace_list[j+1], (num_aces-j-1) *
3328                                                                 sizeof(struct security_ace));
3329
3330                                         DEBUG(10,("merge_default_aces: Merging ACE %u onto ACE %u.\n",
3331                                                 (unsigned int)j, (unsigned int)i ));
3332                                 }
3333                                 num_aces--;
3334                                 break;
3335                         }
3336                 }
3337         }
3338
3339         return num_aces;
3340 }
3341
3342 /*
3343  * Add or Replace ACE entry.
3344  * In some cases we need to add a specific ACE for compatibility reasons.
3345  * When doing that we must make sure we are not actually creating a duplicate
3346  * entry. So we need to search whether an ACE entry already exist and eventually
3347  * replacce the access mask, or add a completely new entry if none was found.
3348  *
3349  * This function assumes the array has enough space to add a new entry without
3350  * any reallocation of memory.
3351  */
3352
3353 static void add_or_replace_ace(struct security_ace *nt_ace_list, size_t *num_aces,
3354                                 const struct dom_sid *sid, enum security_ace_type type,
3355                                 uint32_t mask, uint8_t flags)
3356 {
3357         int i;
3358
3359         /* first search for a duplicate */
3360         for (i = 0; i < *num_aces; i++) {
3361                 if (dom_sid_equal(&nt_ace_list[i].trustee, sid) &&
3362                     (nt_ace_list[i].flags == flags)) break;
3363         }
3364
3365         if (i < *num_aces) { /* found */
3366                 nt_ace_list[i].type = type;
3367                 nt_ace_list[i].access_mask = mask;
3368                 DEBUG(10, ("Replacing ACE %d with SID %s and flags %02x\n",
3369                            i, sid_string_dbg(sid), flags));
3370                 return;
3371         }
3372
3373         /* not found, append it */
3374         init_sec_ace(&nt_ace_list[(*num_aces)++], sid, type, mask, flags);
3375 }
3376
3377
3378 /****************************************************************************
3379  Reply to query a security descriptor from an fsp. If it succeeds it allocates
3380  the space for the return elements and returns the size needed to return the
3381  security descriptor. This should be the only external function needed for
3382  the UNIX style get ACL.
3383 ****************************************************************************/
3384
3385 static NTSTATUS posix_get_nt_acl_common(struct connection_struct *conn,
3386                                       const char *name,
3387                                       const SMB_STRUCT_STAT *sbuf,
3388                                       struct pai_val *pal,
3389                                       SMB_ACL_T posix_acl,
3390                                       SMB_ACL_T def_acl,
3391                                       uint32_t security_info,
3392                                       struct security_descriptor **ppdesc)
3393 {
3394         struct dom_sid owner_sid;
3395         struct dom_sid group_sid;
3396         size_t sd_size = 0;
3397         struct security_acl *psa = NULL;
3398         size_t num_acls = 0;
3399         size_t num_def_acls = 0;
3400         size_t num_aces = 0;
3401         canon_ace *file_ace = NULL;
3402         canon_ace *dir_ace = NULL;
3403         struct security_ace *nt_ace_list = NULL;
3404         size_t num_profile_acls = 0;
3405         struct dom_sid orig_owner_sid;
3406         struct security_descriptor *psd = NULL;
3407         int i;
3408
3409         /*
3410          * Get the owner, group and world SIDs.
3411          */
3412
3413         create_file_sids(sbuf, &owner_sid, &group_sid);
3414
3415         if (lp_profile_acls(SNUM(conn))) {
3416                 /* For WXP SP1 the owner must be administrators. */
3417                 sid_copy(&orig_owner_sid, &owner_sid);
3418                 sid_copy(&owner_sid, &global_sid_Builtin_Administrators);
3419                 sid_copy(&group_sid, &global_sid_Builtin_Users);
3420                 num_profile_acls = 3;
3421         }
3422
3423         if ((security_info & SECINFO_DACL) && !(security_info & SECINFO_PROTECTED_DACL)) {
3424
3425                 /*
3426                  * In the optimum case Creator Owner and Creator Group would be used for
3427                  * the ACL_USER_OBJ and ACL_GROUP_OBJ entries, respectively, but this
3428                  * would lead to usability problems under Windows: The Creator entries
3429                  * are only available in browse lists of directories and not for files;
3430                  * additionally the identity of the owning group couldn't be determined.
3431                  * We therefore use those identities only for Default ACLs. 
3432                  */
3433
3434                 /* Create the canon_ace lists. */
3435                 file_ace = canonicalise_acl(conn, name, posix_acl, sbuf,
3436                                             &owner_sid, &group_sid, pal,
3437                                             SMB_ACL_TYPE_ACCESS);
3438
3439                 /* We must have *some* ACLS. */
3440         
3441                 if (count_canon_ace_list(file_ace) == 0) {
3442                         DEBUG(0,("get_nt_acl : No ACLs on file (%s) !\n", name));
3443                         goto done;
3444                 }
3445
3446                 if (S_ISDIR(sbuf->st_ex_mode) && def_acl) {
3447                         dir_ace = canonicalise_acl(conn, name, def_acl,
3448                                                    sbuf,
3449                                                    &global_sid_Creator_Owner,
3450                                                    &global_sid_Creator_Group,
3451                                                    pal, SMB_ACL_TYPE_DEFAULT);
3452                 }
3453
3454                 /*
3455                  * Create the NT ACE list from the canonical ace lists.
3456                  */
3457
3458                 {
3459                         canon_ace *ace;
3460                         enum security_ace_type nt_acl_type;
3461
3462                         if (nt4_compatible_acls() && dir_ace) {
3463                                 /*
3464                                  * NT 4 chokes if an ACL contains an INHERIT_ONLY entry
3465                                  * but no non-INHERIT_ONLY entry for one SID. So we only
3466                                  * remove entries from the Access ACL if the
3467                                  * corresponding Default ACL entries have also been
3468                                  * removed. ACEs for CREATOR-OWNER and CREATOR-GROUP
3469                                  * are exceptions. We can do nothing
3470                                  * intelligent if the Default ACL contains entries that
3471                                  * are not also contained in the Access ACL, so this
3472                                  * case will still fail under NT 4.
3473                                  */
3474
3475                                 ace = canon_ace_entry_for(dir_ace, SMB_ACL_OTHER, NULL);
3476                                 if (ace && !ace->perms) {
3477                                         DLIST_REMOVE(dir_ace, ace);
3478                                         TALLOC_FREE(ace);
3479
3480                                         ace = canon_ace_entry_for(file_ace, SMB_ACL_OTHER, NULL);
3481                                         if (ace && !ace->perms) {
3482                                                 DLIST_REMOVE(file_ace, ace);
3483                                                 TALLOC_FREE(ace);
3484                                         }
3485                                 }
3486
3487                                 /*
3488                                  * WinNT doesn't usually have Creator Group
3489                                  * in browse lists, so we send this entry to
3490                                  * WinNT even if it contains no relevant
3491                                  * permissions. Once we can add
3492                                  * Creator Group to browse lists we can
3493                                  * re-enable this.
3494                                  */
3495
3496 #if 0
3497                                 ace = canon_ace_entry_for(dir_ace, SMB_ACL_GROUP_OBJ, NULL);
3498                                 if (ace && !ace->perms) {
3499                                         DLIST_REMOVE(dir_ace, ace);
3500                                         TALLOC_FREE(ace);
3501                                 }
3502 #endif
3503
3504                                 ace = canon_ace_entry_for(file_ace, SMB_ACL_GROUP_OBJ, NULL);
3505                                 if (ace && !ace->perms) {
3506                                         DLIST_REMOVE(file_ace, ace);
3507                                         TALLOC_FREE(ace);
3508                                 }
3509                         }
3510
3511                         num_acls = count_canon_ace_list(file_ace);
3512                         num_def_acls = count_canon_ace_list(dir_ace);
3513
3514                         /* Allocate the ace list. */
3515                         if ((nt_ace_list = talloc_array(talloc_tos(), struct security_ace,num_acls + num_profile_acls + num_def_acls)) == NULL) {
3516                                 DEBUG(0,("get_nt_acl: Unable to malloc space for nt_ace_list.\n"));
3517                                 goto done;
3518                         }
3519
3520                         memset(nt_ace_list, '\0', (num_acls + num_def_acls) * sizeof(struct security_ace) );
3521
3522                         /*
3523                          * Create the NT ACE list from the canonical ace lists.
3524                          */
3525
3526                         for (ace = file_ace; ace != NULL; ace = ace->next) {
3527                                 uint32_t acc = map_canon_ace_perms(SNUM(conn),
3528                                                 &nt_acl_type,
3529                                                 ace->perms,
3530                                                 S_ISDIR(sbuf->st_ex_mode));
3531                                 init_sec_ace(&nt_ace_list[num_aces++],
3532                                         &ace->trustee,
3533                                         nt_acl_type,
3534                                         acc,
3535                                         ace->ace_flags);
3536                         }
3537
3538                         /* The User must have access to a profile share - even
3539                          * if we can't map the SID. */
3540                         if (lp_profile_acls(SNUM(conn))) {
3541                                 add_or_replace_ace(nt_ace_list, &num_aces,
3542                                                    &global_sid_Builtin_Users,
3543                                                    SEC_ACE_TYPE_ACCESS_ALLOWED,
3544                                                    FILE_GENERIC_ALL, 0);
3545                         }
3546
3547                         for (ace = dir_ace; ace != NULL; ace = ace->next) {
3548                                 uint32_t acc = map_canon_ace_perms(SNUM(conn),
3549                                                 &nt_acl_type,
3550                                                 ace->perms,
3551                                                 S_ISDIR(sbuf->st_ex_mode));
3552                                 init_sec_ace(&nt_ace_list[num_aces++],
3553                                         &ace->trustee,
3554                                         nt_acl_type,
3555                                         acc,
3556                                         ace->ace_flags |
3557                                         SEC_ACE_FLAG_OBJECT_INHERIT|
3558                                         SEC_ACE_FLAG_CONTAINER_INHERIT|
3559                                         SEC_ACE_FLAG_INHERIT_ONLY);
3560                         }
3561
3562                         /* The User must have access to a profile share - even
3563                          * if we can't map the SID. */
3564                         if (lp_profile_acls(SNUM(conn))) {
3565                                 add_or_replace_ace(nt_ace_list, &num_aces,
3566                                                 &global_sid_Builtin_Users,
3567                                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
3568                                                 FILE_GENERIC_ALL,
3569                                                 SEC_ACE_FLAG_OBJECT_INHERIT |
3570                                                 SEC_ACE_FLAG_CONTAINER_INHERIT |
3571                                                 SEC_ACE_FLAG_INHERIT_ONLY);
3572                         }
3573
3574                         /*
3575                          * Merge POSIX default ACLs and normal ACLs into one NT ACE.
3576                          * Win2K needs this to get the inheritance correct when replacing ACLs
3577                          * on a directory tree. Based on work by Jim @ IBM.
3578                          */
3579
3580                         num_aces = merge_default_aces(nt_ace_list, num_aces);
3581
3582                         if (lp_profile_acls(SNUM(conn))) {
3583                                 for (i = 0; i < num_aces; i++) {
3584                                         if (dom_sid_equal(&nt_ace_list[i].trustee, &owner_sid)) {
3585                                                 add_or_replace_ace(nt_ace_list, &num_aces,
3586                                                                    &orig_owner_sid,
3587                                                                    nt_ace_list[i].type,
3588                                                                    nt_ace_list[i].access_mask,
3589                                                                    nt_ace_list[i].flags);
3590                                                 break;
3591                                         }
3592                                 }
3593                         }
3594                 }
3595
3596                 if (num_aces) {
3597                         if((psa = make_sec_acl( talloc_tos(), NT4_ACL_REVISION, num_aces, nt_ace_list)) == NULL) {
3598                                 DEBUG(0,("get_nt_acl: Unable to malloc space for acl.\n"));
3599                                 goto done;
3600                         }
3601                 }
3602         } /* security_info & SECINFO_DACL */
3603
3604         psd = make_standard_sec_desc( talloc_tos(),
3605                         (security_info & SECINFO_OWNER) ? &owner_sid : NULL,
3606                         (security_info & SECINFO_GROUP) ? &group_sid : NULL,
3607                         psa,
3608                         &sd_size);
3609
3610         if(!psd) {
3611                 DEBUG(0,("get_nt_acl: Unable to malloc space for security descriptor.\n"));
3612                 sd_size = 0;
3613                 goto done;
3614         }
3615
3616         /*
3617          * Windows 2000: The DACL_PROTECTED flag in the security
3618          * descriptor marks the ACL as non-inheriting, i.e., no
3619          * ACEs from higher level directories propagate to this
3620          * ACL. In the POSIX ACL model permissions are only
3621          * inherited at file create time, so ACLs never contain
3622          * any ACEs that are inherited dynamically. The DACL_PROTECTED
3623          * flag doesn't seem to bother Windows NT.
3624          * Always set this if map acl inherit is turned off.
3625          */
3626         if (pal == NULL || !lp_map_acl_inherit(SNUM(conn))) {
3627                 psd->type |= SEC_DESC_DACL_PROTECTED;
3628         } else {
3629                 psd->type |= pal->sd_type;
3630         }
3631
3632         if (psd->dacl) {
3633                 dacl_sort_into_canonical_order(psd->dacl->aces, (unsigned int)psd->dacl->num_aces);
3634         }
3635
3636         *ppdesc = psd;
3637
3638  done:
3639
3640         if (posix_acl) {
3641                 TALLOC_FREE(posix_acl);
3642         }
3643         if (def_acl) {
3644                 TALLOC_FREE(def_acl);
3645         }
3646         free_canon_ace_list(file_ace);
3647         free_canon_ace_list(dir_ace);
3648         free_inherited_info(pal);
3649         TALLOC_FREE(nt_ace_list);
3650
3651         return NT_STATUS_OK;
3652 }
3653
3654 NTSTATUS posix_fget_nt_acl(struct files_struct *fsp, uint32_t security_info,
3655                            struct security_descriptor **ppdesc)
3656 {
3657         SMB_STRUCT_STAT sbuf;
3658         SMB_ACL_T posix_acl = NULL;
3659         struct pai_val *pal;
3660
3661         *ppdesc = NULL;
3662
3663         DEBUG(10,("posix_fget_nt_acl: called for file %s\n",
3664                   fsp_str_dbg(fsp)));
3665
3666         /* can it happen that fsp_name == NULL ? */
3667         if (fsp->is_directory ||  fsp->fh->fd == -1) {
3668                 return posix_get_nt_acl(fsp->conn, fsp->fsp_name->base_name,
3669                                         security_info, ppdesc);
3670         }
3671
3672         /* Get the stat struct for the owner info. */
3673         if(SMB_VFS_FSTAT(fsp, &sbuf) != 0) {
3674                 return map_nt_error_from_unix(errno);
3675         }
3676
3677         /* Get the ACL from the fd. */
3678         posix_acl = SMB_VFS_SYS_ACL_GET_FD(fsp);
3679
3680         pal = fload_inherited_info(fsp);
3681
3682         return posix_get_nt_acl_common(fsp->conn, fsp->fsp_name->base_name,
3683                                        &sbuf, pal, posix_acl, NULL,
3684                                        security_info, ppdesc);
3685 }
3686
3687 NTSTATUS posix_get_nt_acl(struct connection_struct *conn, const char *name,
3688                           uint32_t security_info, struct security_descriptor **ppdesc)
3689 {
3690         SMB_ACL_T posix_acl = NULL;
3691         SMB_ACL_T def_acl = NULL;
3692         struct pai_val *pal;
3693         struct smb_filename smb_fname;
3694         int ret;
3695
3696         *ppdesc = NULL;
3697
3698         DEBUG(10,("posix_get_nt_acl: called for file %s\n", name ));
3699
3700         ZERO_STRUCT(smb_fname);
3701         smb_fname.base_name = discard_const_p(char, name);
3702
3703         /* Get the stat struct for the owner info. */
3704         if (lp_posix_pathnames()) {
3705                 ret = SMB_VFS_LSTAT(conn, &smb_fname);
3706         } else {
3707                 ret = SMB_VFS_STAT(conn, &smb_fname);
3708         }
3709
3710         if (ret == -1) {
3711                 return map_nt_error_from_unix(errno);
3712         }
3713
3714         /* Get the ACL from the path. */
3715         posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, name, SMB_ACL_TYPE_ACCESS);
3716
3717         /* If it's a directory get the default POSIX ACL. */
3718         if(S_ISDIR(smb_fname.st.st_ex_mode)) {
3719                 def_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, name, SMB_ACL_TYPE_DEFAULT);
3720                 def_acl = free_empty_sys_acl(conn, def_acl);
3721         }
3722
3723         pal = load_inherited_info(conn, name);
3724
3725         return posix_get_nt_acl_common(conn, name, &smb_fname.st, pal,
3726                                        posix_acl, def_acl, security_info,
3727                                        ppdesc);
3728 }
3729
3730 /****************************************************************************
3731  Try to chown a file. We will be able to chown it under the following conditions.
3732
3733   1) If we have root privileges, then it will just work.
3734   2) If we have SeRestorePrivilege we can change the user + group to any other user. 
3735   3) If we have SeTakeOwnershipPrivilege we can change the user to the current user.
3736   4) If we have write permission to the file and dos_filemodes is set
3737      then allow chown to the currently authenticated user.
3738 ****************************************************************************/
3739
3740 NTSTATUS try_chown(files_struct *fsp, uid_t uid, gid_t gid)
3741 {
3742         NTSTATUS status;
3743
3744         if(!CAN_WRITE(fsp->conn)) {
3745                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
3746         }
3747
3748         /* Case (1). */
3749         status = vfs_chown_fsp(fsp, uid, gid);
3750         if (NT_STATUS_IS_OK(status)) {
3751                 return status;
3752         }
3753
3754         /* Case (2) / (3) */
3755         if (lp_enable_privileges()) {
3756                 bool has_take_ownership_priv = security_token_has_privilege(
3757                                                 get_current_nttok(fsp->conn),
3758                                                 SEC_PRIV_TAKE_OWNERSHIP);
3759                 bool has_restore_priv = security_token_has_privilege(
3760                                                 get_current_nttok(fsp->conn),
3761                                                 SEC_PRIV_RESTORE);
3762
3763                 if (has_restore_priv) {
3764                         ; /* Case (2) */
3765                 } else if (has_take_ownership_priv) {
3766                         /* Case (3) */
3767                         if (uid == get_current_uid(fsp->conn)) {
3768                                 gid = (gid_t)-1;
3769                         } else {
3770                                 has_take_ownership_priv = false;
3771                         }
3772                 }
3773
3774                 if (has_take_ownership_priv || has_restore_priv) {
3775                         become_root();
3776                         status = vfs_chown_fsp(fsp, uid, gid);
3777                         unbecome_root();
3778                         return status;
3779                 }
3780         }
3781
3782         /* Case (4). */
3783         if (!lp_dos_filemode(SNUM(fsp->conn))) {
3784                 return NT_STATUS_ACCESS_DENIED;
3785         }
3786
3787         /* only allow chown to the current user. This is more secure,
3788            and also copes with the case where the SID in a take ownership ACL is
3789            a local SID on the users workstation
3790         */
3791         if (uid != get_current_uid(fsp->conn)) {
3792                 return NT_STATUS_ACCESS_DENIED;
3793         }
3794
3795         become_root();
3796         /* Keep the current file gid the same. */
3797         status = vfs_chown_fsp(fsp, uid, (gid_t)-1);
3798         unbecome_root();
3799
3800         return status;
3801 }
3802
3803 #if 0
3804 /* Disable this - prevents ACL inheritance from the ACL editor. JRA. */
3805
3806 /****************************************************************************
3807  Take care of parent ACL inheritance.
3808 ****************************************************************************/
3809
3810 NTSTATUS append_parent_acl(files_struct *fsp,
3811                                 const struct security_descriptor *pcsd,
3812                                 struct security_descriptor **pp_new_sd)
3813 {
3814         struct smb_filename *smb_dname = NULL;
3815         struct security_descriptor *parent_sd = NULL;
3816         files_struct *parent_fsp = NULL;
3817         TALLOC_CTX *mem_ctx = talloc_tos();
3818         char *parent_name = NULL;
3819         struct security_ace *new_ace = NULL;
3820         unsigned int num_aces = pcsd->dacl->num_aces;
3821         NTSTATUS status;
3822         int info;
3823         unsigned int i, j;
3824         struct security_descriptor *psd = dup_sec_desc(talloc_tos(), pcsd);
3825         bool is_dacl_protected = (pcsd->type & SEC_DESC_DACL_PROTECTED);
3826
3827         if (psd == NULL) {
3828                 return NT_STATUS_NO_MEMORY;
3829         }
3830
3831         if (!parent_dirname(mem_ctx, fsp->fsp_name->base_name, &parent_name,
3832                             NULL)) {
3833                 return NT_STATUS_NO_MEMORY;
3834         }
3835
3836         status = create_synthetic_smb_fname(mem_ctx, parent_name, NULL, NULL,
3837                                             &smb_dname);
3838         if (!NT_STATUS_IS_OK(status)) {
3839                 goto fail;
3840         }
3841
3842         status = SMB_VFS_CREATE_FILE(
3843                 fsp->conn,                              /* conn */
3844                 NULL,                                   /* req */
3845                 0,                                      /* root_dir_fid */
3846                 smb_dname,                              /* fname */
3847                 FILE_READ_ATTRIBUTES,                   /* access_mask */
3848                 FILE_SHARE_NONE,                        /* share_access */
3849                 FILE_OPEN,                              /* create_disposition*/
3850                 FILE_DIRECTORY_FILE,                    /* create_options */
3851                 0,                                      /* file_attributes */
3852                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
3853                 0,                                      /* allocation_size */
3854                 NULL,                                   /* sd */
3855                 NULL,                                   /* ea_list */
3856                 &parent_fsp,                            /* result */
3857                 &info);                                 /* pinfo */
3858
3859         if (!NT_STATUS_IS_OK(status)) {
3860                 TALLOC_FREE(smb_dname);
3861                 return status;
3862         }
3863
3864         status = SMB_VFS_GET_NT_ACL(parent_fsp->conn, smb_dname->base_name,
3865                                     SECINFO_DACL, &parent_sd );
3866
3867         close_file(NULL, parent_fsp, NORMAL_CLOSE);
3868         TALLOC_FREE(smb_dname);
3869
3870         if (!NT_STATUS_IS_OK(status)) {
3871                 return status;
3872         }
3873
3874         /*
3875          * Make room for potentially all the ACLs from
3876          * the parent. We used to add the ugw triple here,
3877          * as we knew we were dealing with POSIX ACLs.
3878          * We no longer need to do so as we can guarentee
3879          * that a default ACL from the parent directory will
3880          * be well formed for POSIX ACLs if it came from a
3881          * POSIX ACL source, and if we're not writing to a
3882          * POSIX ACL sink then we don't care if it's not well
3883          * formed. JRA.
3884          */
3885
3886         num_aces += parent_sd->dacl->num_aces;
3887
3888         if((new_ace = talloc_zero_array(mem_ctx, struct security_ace,
3889                                         num_aces)) == NULL) {
3890                 return NT_STATUS_NO_MEMORY;
3891         }
3892
3893         /* Start by copying in all the given ACE entries. */
3894         for (i = 0; i < psd->dacl->num_aces; i++) {
3895                 sec_ace_copy(&new_ace[i], &psd->dacl->aces[i]);
3896         }
3897
3898         /*
3899          * Note that we're ignoring "inherit permissions" here
3900          * as that really only applies to newly created files. JRA.
3901          */
3902
3903         /* Finally append any inherited ACEs. */
3904         for (j = 0; j < parent_sd->dacl->num_aces; j++) {
3905                 struct security_ace *se = &parent_sd->dacl->aces[j];
3906
3907                 if (fsp->is_directory) {
3908                         if (!(se->flags & SEC_ACE_FLAG_CONTAINER_INHERIT)) {
3909                                 /* Doesn't apply to a directory - ignore. */
3910                                 DEBUG(10,("append_parent_acl: directory %s "
3911                                         "ignoring non container "
3912                                         "inherit flags %u on ACE with sid %s "
3913                                         "from parent %s\n",
3914                                         fsp_str_dbg(fsp),
3915                                         (unsigned int)se->flags,
3916                                         sid_string_dbg(&se->trustee),
3917                                         parent_name));
3918                                 continue;
3919                         }
3920                 } else {
3921                         if (!(se->flags & SEC_ACE_FLAG_OBJECT_INHERIT)) {
3922                                 /* Doesn't apply to a file - ignore. */
3923                                 DEBUG(10,("append_parent_acl: file %s "
3924                                         "ignoring non object "
3925                                         "inherit flags %u on ACE with sid %s "
3926                                         "from parent %s\n",
3927                                         fsp_str_dbg(fsp),
3928                                         (unsigned int)se->flags,
3929                                         sid_string_dbg(&se->trustee),
3930                                         parent_name));
3931                                 continue;
3932                         }
3933                 }
3934
3935                 if (is_dacl_protected) {
3936                         /* If the DACL is protected it means we must
3937                          * not overwrite an existing ACE entry with the
3938                          * same SID. This is order N^2. Ouch :-(. JRA. */
3939                         unsigned int k;
3940                         for (k = 0; k < psd->dacl->num_aces; k++) {
3941                                 if (dom_sid_equal(&psd->dacl->aces[k].trustee,
3942                                                 &se->trustee)) {
3943                                         break;
3944                                 }
3945                         }
3946                         if (k < psd->dacl->num_aces) {
3947                                 /* SID matched. Ignore. */
3948                                 DEBUG(10,("append_parent_acl: path %s "
3949                                         "ignoring ACE with protected sid %s "
3950                                         "from parent %s\n",
3951                                         fsp_str_dbg(fsp),
3952                                         sid_string_dbg(&se->trustee),
3953                                         parent_name));
3954                                 continue;
3955                         }
3956                 }
3957
3958                 sec_ace_copy(&new_ace[i], se);
3959                 if (se->flags & SEC_ACE_FLAG_NO_PROPAGATE_INHERIT) {
3960                         new_ace[i].flags &= ~(SEC_ACE_FLAG_VALID_INHERIT);
3961                 }
3962                 new_ace[i].flags |= SEC_ACE_FLAG_INHERITED_ACE;
3963
3964                 if (fsp->is_directory) {
3965                         /*
3966                          * Strip off any inherit only. It's applied.
3967                          */
3968                         new_ace[i].flags &= ~(SEC_ACE_FLAG_INHERIT_ONLY);
3969                         if (se->flags & SEC_ACE_FLAG_NO_PROPAGATE_INHERIT) {
3970                                 /* No further inheritance. */
3971                                 new_ace[i].flags &=
3972                                         ~(SEC_ACE_FLAG_CONTAINER_INHERIT|
3973                                         SEC_ACE_FLAG_OBJECT_INHERIT);
3974                         }
3975                 } else {
3976                         /*
3977                          * Strip off any container or inherit
3978                          * flags, they can't apply to objects.
3979                          */
3980                         new_ace[i].flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|
3981                                                 SEC_ACE_FLAG_INHERIT_ONLY|
3982                                                 SEC_ACE_FLAG_NO_PROPAGATE_INHERIT);
3983                 }
3984                 i++;
3985
3986                 DEBUG(10,("append_parent_acl: path %s "
3987                         "inheriting ACE with sid %s "
3988                         "from parent %s\n",
3989                         fsp_str_dbg(fsp),
3990                         sid_string_dbg(&se->trustee),
3991                         parent_name));
3992         }
3993
3994         psd->dacl->aces = new_ace;
3995         psd->dacl->num_aces = i;
3996         psd->type &= ~(SEC_DESC_DACL_AUTO_INHERITED|
3997                          SEC_DESC_DACL_AUTO_INHERIT_REQ);
3998
3999         *pp_new_sd = psd;
4000         return status;
4001 }
4002 #endif
4003
4004 /****************************************************************************
4005  Reply to set a security descriptor on an fsp. security_info_sent is the
4006  description of the following NT ACL.
4007  This should be the only external function needed for the UNIX style set ACL.
4008  We make a copy of psd_orig as internal functions modify the elements inside
4009  it, even though it's a const pointer.
4010 ****************************************************************************/
4011
4012 NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, const struct security_descriptor *psd_orig)
4013 {
4014         connection_struct *conn = fsp->conn;
4015         uid_t user = (uid_t)-1;
4016         gid_t grp = (gid_t)-1;
4017         struct dom_sid file_owner_sid;
4018         struct dom_sid file_grp_sid;
4019         canon_ace *file_ace_list = NULL;
4020         canon_ace *dir_ace_list = NULL;
4021         bool acl_perms = False;
4022         mode_t orig_mode = (mode_t)0;
4023         NTSTATUS status;
4024         bool set_acl_as_root = false;
4025         bool acl_set_support = false;
4026         bool ret = false;
4027         struct security_descriptor *psd = NULL;
4028
4029         DEBUG(10,("set_nt_acl: called for file %s\n",
4030                   fsp_str_dbg(fsp)));
4031
4032         if (!CAN_WRITE(conn)) {
4033                 DEBUG(10,("set acl rejected on read-only share\n"));
4034                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
4035         }
4036
4037         if (!psd_orig) {
4038                 return NT_STATUS_INVALID_PARAMETER;
4039         }
4040
4041         psd = dup_sec_desc(talloc_tos(), psd_orig);
4042         if (!psd) {
4043                 return NT_STATUS_NO_MEMORY;
4044         }
4045
4046         /*
4047          * Get the current state of the file.
4048          */
4049
4050         status = vfs_stat_fsp(fsp);
4051         if (!NT_STATUS_IS_OK(status)) {
4052                 return status;
4053         }
4054
4055         /* Save the original element we check against. */
4056         orig_mode = fsp->fsp_name->st.st_ex_mode;
4057
4058         /*
4059          * Unpack the user/group/world id's.
4060          */
4061
4062         /* POSIX can't cope with missing owner/group. */
4063         if ((security_info_sent & SECINFO_OWNER) && (psd->owner_sid == NULL)) {
4064                 security_info_sent &= ~SECINFO_OWNER;
4065         }
4066         if ((security_info_sent & SECINFO_GROUP) && (psd->group_sid == NULL)) {
4067                 security_info_sent &= ~SECINFO_GROUP;
4068         }
4069
4070         status = unpack_nt_owners( conn, &user, &grp, security_info_sent, psd);
4071         if (!NT_STATUS_IS_OK(status)) {
4072                 return status;
4073         }
4074
4075         /*
4076          * Do we need to chown ? If so this must be done first as the incoming
4077          * CREATOR_OWNER acl will be relative to the *new* owner, not the old.
4078          * Noticed by Simo.
4079          */
4080
4081         if (((user != (uid_t)-1) && (fsp->fsp_name->st.st_ex_uid != user)) ||
4082             (( grp != (gid_t)-1) && (fsp->fsp_name->st.st_ex_gid != grp))) {
4083
4084                 DEBUG(3,("set_nt_acl: chown %s. uid = %u, gid = %u.\n",
4085                          fsp_str_dbg(fsp), (unsigned int)user,
4086                          (unsigned int)grp));
4087
4088                 status = try_chown(fsp, user, grp);
4089                 if(!NT_STATUS_IS_OK(status)) {
4090                         DEBUG(3,("set_nt_acl: chown %s, %u, %u failed. Error "
4091                                 "= %s.\n", fsp_str_dbg(fsp),
4092                                 (unsigned int)user,
4093                                 (unsigned int)grp,
4094                                 nt_errstr(status)));
4095                         return status;
4096                 }
4097
4098                 /*
4099                  * Recheck the current state of the file, which may have changed.
4100                  * (suid/sgid bits, for instance)
4101                  */
4102
4103                 status = vfs_stat_fsp(fsp);
4104                 if (!NT_STATUS_IS_OK(status)) {
4105                         return status;
4106                 }
4107
4108                 /* Save the original element we check against. */
4109                 orig_mode = fsp->fsp_name->st.st_ex_mode;
4110
4111                 /* If we successfully chowned, we know we must
4112                  * be able to set the acl, so do it as root.
4113                  */
4114                 set_acl_as_root = true;
4115         }
4116
4117         create_file_sids(&fsp->fsp_name->st, &file_owner_sid, &file_grp_sid);
4118
4119         if((security_info_sent & SECINFO_DACL) &&
4120                         (psd->type & SEC_DESC_DACL_PRESENT) &&
4121                         (psd->dacl == NULL)) {
4122                 struct security_ace ace[3];
4123
4124                 /* We can't have NULL DACL in POSIX.
4125                    Use owner/group/Everyone -> full access. */
4126
4127                 init_sec_ace(&ace[0],
4128                                 &file_owner_sid,
4129                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
4130                                 GENERIC_ALL_ACCESS,
4131                                 0);
4132                 init_sec_ace(&ace[1],
4133                                 &file_grp_sid,
4134                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
4135                                 GENERIC_ALL_ACCESS,
4136                                 0);
4137                 init_sec_ace(&ace[2],
4138                                 &global_sid_World,
4139                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
4140                                 GENERIC_ALL_ACCESS,
4141                                 0);
4142                 psd->dacl = make_sec_acl(talloc_tos(),
4143                                         NT4_ACL_REVISION,
4144                                         3,
4145                                         ace);
4146                 if (psd->dacl == NULL) {
4147                         return NT_STATUS_NO_MEMORY;
4148                 }
4149                 security_acl_map_generic(psd->dacl, &file_generic_mapping);
4150         }
4151
4152         acl_perms = unpack_canon_ace(fsp, &fsp->fsp_name->st, &file_owner_sid,
4153                                      &file_grp_sid, &file_ace_list,
4154                                      &dir_ace_list, security_info_sent, psd);
4155
4156         /* Ignore W2K traverse DACL set. */
4157         if (!file_ace_list && !dir_ace_list) {
4158                 return NT_STATUS_OK;
4159         }
4160
4161         if (!acl_perms) {
4162                 DEBUG(3,("set_nt_acl: cannot set permissions\n"));
4163                 free_canon_ace_list(file_ace_list);
4164                 free_canon_ace_list(dir_ace_list);
4165                 return NT_STATUS_ACCESS_DENIED;
4166         }
4167
4168         /*
4169          * Only change security if we got a DACL.
4170          */
4171
4172         if(!(security_info_sent & SECINFO_DACL) || (psd->dacl == NULL)) {
4173                 free_canon_ace_list(file_ace_list);
4174                 free_canon_ace_list(dir_ace_list);
4175                 return NT_STATUS_OK;
4176         }
4177
4178         /*
4179          * Try using the POSIX ACL set first. Fall back to chmod if
4180          * we have no ACL support on this filesystem.
4181          */
4182
4183         if (acl_perms && file_ace_list) {
4184                 if (set_acl_as_root) {
4185                         become_root();
4186                 }
4187                 ret = set_canon_ace_list(fsp, file_ace_list, false,
4188                                          &fsp->fsp_name->st, &acl_set_support);
4189                 if (set_acl_as_root) {
4190                         unbecome_root();
4191                 }
4192                 if (acl_set_support && ret == false) {
4193                         DEBUG(3,("set_nt_acl: failed to set file acl on file "
4194                                  "%s (%s).\n", fsp_str_dbg(fsp),
4195                                  strerror(errno)));
4196                         free_canon_ace_list(file_ace_list);
4197                         free_canon_ace_list(dir_ace_list);
4198                         return map_nt_error_from_unix(errno);
4199                 }
4200         }
4201
4202         if (acl_perms && acl_set_support && fsp->is_directory) {
4203                 if (dir_ace_list) {
4204                         if (set_acl_as_root) {
4205                                 become_root();
4206                         }
4207                         ret = set_canon_ace_list(fsp, dir_ace_list, true,
4208                                                  &fsp->fsp_name->st,
4209                                                  &acl_set_support);
4210                         if (set_acl_as_root) {
4211                                 unbecome_root();
4212                         }
4213                         if (ret == false) {
4214                                 DEBUG(3,("set_nt_acl: failed to set default "
4215                                          "acl on directory %s (%s).\n",
4216                                          fsp_str_dbg(fsp), strerror(errno)));
4217                                 free_canon_ace_list(file_ace_list);
4218                                 free_canon_ace_list(dir_ace_list);
4219                                 return map_nt_error_from_unix(errno);
4220                         }
4221                 } else {
4222                         int sret = -1;
4223
4224                         /*
4225                          * No default ACL - delete one if it exists.
4226                          */
4227
4228                         if (set_acl_as_root) {
4229                                 become_root();
4230                         }
4231                         sret = SMB_VFS_SYS_ACL_DELETE_DEF_FILE(conn,
4232                             fsp->fsp_name->base_name);
4233                         if (set_acl_as_root) {
4234                                 unbecome_root();
4235                         }
4236                         if (sret == -1) {
4237                                 if (acl_group_override(conn, fsp->fsp_name)) {
4238                                         DEBUG(5,("set_nt_acl: acl group "
4239                                                  "control on and current user "
4240                                                  "in file %s primary group. "
4241                                                  "Override delete_def_acl\n",
4242                                                  fsp_str_dbg(fsp)));
4243
4244                                         become_root();
4245                                         sret =
4246                                             SMB_VFS_SYS_ACL_DELETE_DEF_FILE(
4247                                                     conn,
4248                                                     fsp->fsp_name->base_name);
4249                                         unbecome_root();
4250                                 }
4251
4252                                 if (sret == -1) {
4253                                         DEBUG(3,("set_nt_acl: sys_acl_delete_def_file failed (%s)\n", strerror(errno)));
4254                                         free_canon_ace_list(file_ace_list);
4255                                         free_canon_ace_list(dir_ace_list);
4256                                         return map_nt_error_from_unix(errno);
4257                                 }
4258                         }
4259                 }
4260         }
4261
4262         if (acl_set_support) {
4263                 if (set_acl_as_root) {
4264                         become_root();
4265                 }
4266                 store_inheritance_attributes(fsp,
4267                                 file_ace_list,
4268                                 dir_ace_list,
4269                                 psd->type);
4270                 if (set_acl_as_root) {
4271                         unbecome_root();
4272                 }
4273         }
4274
4275         /*
4276          * If we cannot set using POSIX ACLs we fall back to checking if we need to chmod.
4277          */
4278
4279         if(!acl_set_support && acl_perms) {
4280                 mode_t posix_perms;
4281
4282                 if (!convert_canon_ace_to_posix_perms( fsp, file_ace_list, &posix_perms)) {
4283                         free_canon_ace_list(file_ace_list);
4284                         free_canon_ace_list(dir_ace_list);
4285                         DEBUG(3,("set_nt_acl: failed to convert file acl to "
4286                                  "posix permissions for file %s.\n",
4287                                  fsp_str_dbg(fsp)));
4288                         return NT_STATUS_ACCESS_DENIED;
4289                 }
4290
4291                 if (orig_mode != posix_perms) {
4292                         int sret = -1;
4293
4294                         DEBUG(3,("set_nt_acl: chmod %s. perms = 0%o.\n",
4295                                  fsp_str_dbg(fsp), (unsigned int)posix_perms));
4296
4297                         if (set_acl_as_root) {
4298                                 become_root();
4299                         }
4300                         sret = SMB_VFS_CHMOD(conn, fsp->fsp_name->base_name,
4301                                              posix_perms);
4302                         if (set_acl_as_root) {
4303                                 unbecome_root();
4304                         }
4305                         if(sret == -1) {
4306                                 if (acl_group_override(conn, fsp->fsp_name)) {
4307                                         DEBUG(5,("set_nt_acl: acl group "
4308                                                  "control on and current user "
4309                                                  "in file %s primary group. "
4310                                                  "Override chmod\n",
4311                                                  fsp_str_dbg(fsp)));
4312
4313                                         become_root();
4314                                         sret = SMB_VFS_CHMOD(conn,
4315                                             fsp->fsp_name->base_name,
4316                                             posix_perms);
4317                                         unbecome_root();
4318                                 }
4319
4320                                 if (sret == -1) {
4321                                         DEBUG(3,("set_nt_acl: chmod %s, 0%o "
4322                                                  "failed. Error = %s.\n",
4323                                                  fsp_str_dbg(fsp),
4324                                                  (unsigned int)posix_perms,
4325                                                  strerror(errno)));
4326                                         free_canon_ace_list(file_ace_list);
4327                                         free_canon_ace_list(dir_ace_list);
4328                                         return map_nt_error_from_unix(errno);
4329                                 }
4330                         }
4331                 }
4332         }
4333
4334         free_canon_ace_list(file_ace_list);
4335         free_canon_ace_list(dir_ace_list);
4336
4337         /* Ensure the stat struct in the fsp is correct. */
4338         status = vfs_stat_fsp(fsp);
4339
4340         return NT_STATUS_OK;
4341 }
4342
4343 /****************************************************************************
4344  Get the actual group bits stored on a file with an ACL. Has no effect if
4345  the file has no ACL. Needed in dosmode code where the stat() will return
4346  the mask bits, not the real group bits, for a file with an ACL.
4347 ****************************************************************************/
4348
4349 int get_acl_group_bits( connection_struct *conn, const char *fname, mode_t *mode )
4350 {
4351         int entry_id = SMB_ACL_FIRST_ENTRY;
4352         SMB_ACL_ENTRY_T entry;
4353         SMB_ACL_T posix_acl;
4354         int result = -1;
4355
4356         posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, fname, SMB_ACL_TYPE_ACCESS);
4357         if (posix_acl == (SMB_ACL_T)NULL)
4358                 return -1;
4359
4360         while (sys_acl_get_entry(posix_acl, entry_id, &entry) == 1) {
4361                 SMB_ACL_TAG_T tagtype;
4362                 SMB_ACL_PERMSET_T permset;
4363
4364                 entry_id = SMB_ACL_NEXT_ENTRY;
4365
4366                 if (sys_acl_get_tag_type(entry, &tagtype) ==-1)
4367                         break;
4368
4369                 if (tagtype == SMB_ACL_GROUP_OBJ) {
4370                         if (sys_acl_get_permset(entry, &permset) == -1) {
4371                                 break;
4372                         } else {
4373                                 *mode &= ~(S_IRGRP|S_IWGRP|S_IXGRP);
4374                                 *mode |= (sys_acl_get_perm(permset, SMB_ACL_READ) ? S_IRGRP : 0);
4375                                 *mode |= (sys_acl_get_perm(permset, SMB_ACL_WRITE) ? S_IWGRP : 0);
4376                                 *mode |= (sys_acl_get_perm(permset, SMB_ACL_EXECUTE) ? S_IXGRP : 0);
4377                                 result = 0;
4378                                 break;
4379                         }
4380                 }
4381         }
4382         TALLOC_FREE(posix_acl);
4383         return result;
4384 }
4385
4386 /****************************************************************************
4387  Do a chmod by setting the ACL USER_OBJ, GROUP_OBJ and OTHER bits in an ACL
4388  and set the mask to rwx. Needed to preserve complex ACLs set by NT.
4389 ****************************************************************************/
4390
4391 static int chmod_acl_internals( connection_struct *conn, SMB_ACL_T posix_acl, mode_t mode)
4392 {
4393         int entry_id = SMB_ACL_FIRST_ENTRY;
4394         SMB_ACL_ENTRY_T entry;
4395         int num_entries = 0;
4396
4397         while ( sys_acl_get_entry(posix_acl, entry_id, &entry) == 1) {
4398                 SMB_ACL_TAG_T tagtype;
4399                 SMB_ACL_PERMSET_T permset;
4400                 mode_t perms;
4401
4402                 entry_id = SMB_ACL_NEXT_ENTRY;
4403
4404                 if (sys_acl_get_tag_type(entry, &tagtype) == -1)
4405                         return -1;
4406
4407                 if (sys_acl_get_permset(entry, &permset) == -1)
4408                         return -1;
4409
4410                 num_entries++;
4411
4412                 switch(tagtype) {
4413                         case SMB_ACL_USER_OBJ:
4414                                 perms = unix_perms_to_acl_perms(mode, S_IRUSR, S_IWUSR, S_IXUSR);
4415                                 break;
4416                         case SMB_ACL_GROUP_OBJ:
4417                                 perms = unix_perms_to_acl_perms(mode, S_IRGRP, S_IWGRP, S_IXGRP);
4418                                 break;
4419                         case SMB_ACL_MASK:
4420                                 /*
4421                                  * FIXME: The ACL_MASK entry permissions should really be set to
4422                                  * the union of the permissions of all ACL_USER,
4423                                  * ACL_GROUP_OBJ, and ACL_GROUP entries. That's what
4424                                  * acl_calc_mask() does, but Samba ACLs doesn't provide it.
4425                                  */
4426                                 perms = S_IRUSR|S_IWUSR|S_IXUSR;
4427                                 break;
4428                         case SMB_ACL_OTHER:
4429                                 perms = unix_perms_to_acl_perms(mode, S_IROTH, S_IWOTH, S_IXOTH);
4430                                 break;
4431                         default:
4432                                 continue;
4433                 }
4434
4435                 if (map_acl_perms_to_permset(conn, perms, &permset) == -1)
4436                         return -1;
4437
4438                 if (sys_acl_set_permset(entry, permset) == -1)
4439                         return -1;
4440         }
4441
4442         /*
4443          * If this is a simple 3 element ACL or no elements then it's a standard
4444          * UNIX permission set. Just use chmod...       
4445          */
4446
4447         if ((num_entries == 3) || (num_entries == 0))
4448                 return -1;
4449
4450         return 0;
4451 }
4452
4453 /****************************************************************************
4454  Get the access ACL of FROM, do a chmod by setting the ACL USER_OBJ,
4455  GROUP_OBJ and OTHER bits in an ACL and set the mask to rwx. Set the
4456  resulting ACL on TO.  Note that name is in UNIX character set.
4457 ****************************************************************************/
4458
4459 static int copy_access_posix_acl(connection_struct *conn, const char *from, const char *to, mode_t mode)
4460 {
4461         SMB_ACL_T posix_acl = NULL;
4462         int ret = -1;
4463
4464         if ((posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, from, SMB_ACL_TYPE_ACCESS)) == NULL)
4465                 return -1;
4466
4467         if ((ret = chmod_acl_internals(conn, posix_acl, mode)) == -1)
4468                 goto done;
4469
4470         ret = SMB_VFS_SYS_ACL_SET_FILE(conn, to, SMB_ACL_TYPE_ACCESS, posix_acl);
4471
4472  done:
4473
4474         TALLOC_FREE(posix_acl);
4475         return ret;
4476 }
4477
4478 /****************************************************************************
4479  Do a chmod by setting the ACL USER_OBJ, GROUP_OBJ and OTHER bits in an ACL
4480  and set the mask to rwx. Needed to preserve complex ACLs set by NT.
4481  Note that name is in UNIX character set.
4482 ****************************************************************************/
4483
4484 int chmod_acl(connection_struct *conn, const char *name, mode_t mode)
4485 {
4486         return copy_access_posix_acl(conn, name, name, mode);
4487 }
4488
4489 /****************************************************************************
4490  Check for an existing default POSIX ACL on a directory.
4491 ****************************************************************************/
4492
4493 static bool directory_has_default_posix_acl(connection_struct *conn, const char *fname)
4494 {
4495         SMB_ACL_T def_acl = SMB_VFS_SYS_ACL_GET_FILE( conn, fname, SMB_ACL_TYPE_DEFAULT);
4496         bool has_acl = False;
4497         SMB_ACL_ENTRY_T entry;
4498
4499         if (def_acl != NULL && (sys_acl_get_entry(def_acl, SMB_ACL_FIRST_ENTRY, &entry) == 1)) {
4500                 has_acl = True;
4501         }
4502
4503         if (def_acl) {
4504                 TALLOC_FREE(def_acl);
4505         }
4506         return has_acl;
4507 }
4508
4509 /****************************************************************************
4510  If the parent directory has no default ACL but it does have an Access ACL,
4511  inherit this Access ACL to file name.
4512 ****************************************************************************/
4513
4514 int inherit_access_posix_acl(connection_struct *conn, const char *inherit_from_dir,
4515                        const char *name, mode_t mode)
4516 {
4517         if (directory_has_default_posix_acl(conn, inherit_from_dir))
4518                 return 0;
4519
4520         return copy_access_posix_acl(conn, inherit_from_dir, name, mode);
4521 }
4522
4523 /****************************************************************************
4524  Do an fchmod by setting the ACL USER_OBJ, GROUP_OBJ and OTHER bits in an ACL
4525  and set the mask to rwx. Needed to preserve complex ACLs set by NT.
4526 ****************************************************************************/
4527
4528 int fchmod_acl(files_struct *fsp, mode_t mode)
4529 {
4530         connection_struct *conn = fsp->conn;
4531         SMB_ACL_T posix_acl = NULL;
4532         int ret = -1;
4533
4534         if ((posix_acl = SMB_VFS_SYS_ACL_GET_FD(fsp)) == NULL)
4535                 return -1;
4536
4537         if ((ret = chmod_acl_internals(conn, posix_acl, mode)) == -1)
4538                 goto done;
4539
4540         ret = SMB_VFS_SYS_ACL_SET_FD(fsp, posix_acl);
4541
4542   done:
4543
4544         TALLOC_FREE(posix_acl);
4545         return ret;
4546 }
4547
4548 /****************************************************************************
4549  Map from wire type to permset.
4550 ****************************************************************************/
4551
4552 static bool unix_ex_wire_to_permset(connection_struct *conn, unsigned char wire_perm, SMB_ACL_PERMSET_T *p_permset)
4553 {
4554         if (wire_perm & ~(SMB_POSIX_ACL_READ|SMB_POSIX_ACL_WRITE|SMB_POSIX_ACL_EXECUTE)) {
4555                 return False;
4556         }
4557
4558         if (sys_acl_clear_perms(*p_permset) ==  -1) {
4559                 return False;
4560         }
4561
4562         if (wire_perm & SMB_POSIX_ACL_READ) {
4563                 if (sys_acl_add_perm(*p_permset, SMB_ACL_READ) == -1) {
4564                         return False;
4565                 }
4566         }
4567         if (wire_perm & SMB_POSIX_ACL_WRITE) {
4568                 if (sys_acl_add_perm(*p_permset, SMB_ACL_WRITE) == -1) {
4569                         return False;
4570                 }
4571         }
4572         if (wire_perm & SMB_POSIX_ACL_EXECUTE) {
4573                 if (sys_acl_add_perm(*p_permset, SMB_ACL_EXECUTE) == -1) {
4574                         return False;
4575                 }
4576         }
4577         return True;
4578 }
4579
4580 /****************************************************************************
4581  Map from wire type to tagtype.
4582 ****************************************************************************/
4583
4584 static bool unix_ex_wire_to_tagtype(unsigned char wire_tt, SMB_ACL_TAG_T *p_tt)
4585 {
4586         switch (wire_tt) {
4587                 case SMB_POSIX_ACL_USER_OBJ:
4588                         *p_tt = SMB_ACL_USER_OBJ;
4589                         break;
4590                 case SMB_POSIX_ACL_USER:
4591                         *p_tt = SMB_ACL_USER;
4592                         break;
4593                 case SMB_POSIX_ACL_GROUP_OBJ:
4594                         *p_tt = SMB_ACL_GROUP_OBJ;
4595                         break;
4596                 case SMB_POSIX_ACL_GROUP:
4597                         *p_tt = SMB_ACL_GROUP;
4598                         break;
4599                 case SMB_POSIX_ACL_MASK:
4600                         *p_tt = SMB_ACL_MASK;
4601                         break;
4602                 case SMB_POSIX_ACL_OTHER:
4603                         *p_tt = SMB_ACL_OTHER;
4604                         break;
4605                 default:
4606                         return False;
4607         }
4608         return True;
4609 }
4610
4611 /****************************************************************************
4612  Create a new POSIX acl from wire permissions.
4613  FIXME ! How does the share mask/mode fit into this.... ?
4614 ****************************************************************************/
4615
4616 static SMB_ACL_T create_posix_acl_from_wire(connection_struct *conn, uint16 num_acls, const char *pdata)
4617 {
4618         unsigned int i;
4619         SMB_ACL_T the_acl = sys_acl_init();
4620
4621         if (the_acl == NULL) {
4622                 return NULL;
4623         }
4624
4625         for (i = 0; i < num_acls; i++) {
4626                 SMB_ACL_ENTRY_T the_entry;
4627                 SMB_ACL_PERMSET_T the_permset;
4628                 SMB_ACL_TAG_T tag_type;
4629
4630                 if (sys_acl_create_entry(&the_acl, &the_entry) == -1) {
4631                         DEBUG(0,("create_posix_acl_from_wire: Failed to create entry %u. (%s)\n",
4632                                 i, strerror(errno) ));
4633                         goto fail;
4634                 }
4635
4636                 if (!unix_ex_wire_to_tagtype(CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)), &tag_type)) {
4637                         DEBUG(0,("create_posix_acl_from_wire: invalid wire tagtype %u on entry %u.\n",
4638                                 CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)), i ));
4639                         goto fail;
4640                 }
4641
4642                 if (sys_acl_set_tag_type(the_entry, tag_type) == -1) {
4643                         DEBUG(0,("create_posix_acl_from_wire: Failed to set tagtype on entry %u. (%s)\n",
4644                                 i, strerror(errno) ));
4645                         goto fail;
4646                 }
4647
4648                 /* Get the permset pointer from the new ACL entry. */
4649                 if (sys_acl_get_permset(the_entry, &the_permset) == -1) {
4650                         DEBUG(0,("create_posix_acl_from_wire: Failed to get permset on entry %u. (%s)\n",
4651                                 i, strerror(errno) ));
4652                         goto fail;
4653                 }
4654
4655                 /* Map from wire to permissions. */
4656                 if (!unix_ex_wire_to_permset(conn, CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)+1), &the_permset)) {
4657                         DEBUG(0,("create_posix_acl_from_wire: invalid permset %u on entry %u.\n",
4658                                 CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE) + 1), i ));
4659                         goto fail;
4660                 }
4661
4662                 /* Now apply to the new ACL entry. */
4663                 if (sys_acl_set_permset(the_entry, the_permset) == -1) {
4664                         DEBUG(0,("create_posix_acl_from_wire: Failed to add permset on entry %u. (%s)\n",
4665                                 i, strerror(errno) ));
4666                         goto fail;
4667                 }
4668
4669                 if (tag_type == SMB_ACL_USER) {
4670                         uint32 uidval = IVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
4671                         uid_t uid = (uid_t)uidval;
4672                         if (sys_acl_set_qualifier(the_entry,(void *)&uid) == -1) {
4673                                 DEBUG(0,("create_posix_acl_from_wire: Failed to set uid %u on entry %u. (%s)\n",
4674                                         (unsigned int)uid, i, strerror(errno) ));
4675                                 goto fail;
4676                         }
4677                 }
4678
4679                 if (tag_type == SMB_ACL_GROUP) {
4680                         uint32 gidval = IVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
4681                         gid_t gid = (uid_t)gidval;
4682                         if (sys_acl_set_qualifier(the_entry,(void *)&gid) == -1) {
4683                                 DEBUG(0,("create_posix_acl_from_wire: Failed to set gid %u on entry %u. (%s)\n",
4684                                         (unsigned int)gid, i, strerror(errno) ));
4685                                 goto fail;
4686                         }
4687                 }
4688         }
4689
4690         return the_acl;
4691
4692  fail:
4693
4694         if (the_acl != NULL) {
4695                 TALLOC_FREE(the_acl);
4696         }
4697         return NULL;
4698 }
4699
4700 /****************************************************************************
4701  Calls from UNIX extensions - Default POSIX ACL set.
4702  If num_def_acls == 0 and not a directory just return. If it is a directory
4703  and num_def_acls == 0 then remove the default acl. Else set the default acl
4704  on the directory.
4705 ****************************************************************************/
4706
4707 bool set_unix_posix_default_acl(connection_struct *conn, const char *fname, const SMB_STRUCT_STAT *psbuf,
4708                                 uint16 num_def_acls, const char *pdata)
4709 {
4710         SMB_ACL_T def_acl = NULL;
4711
4712         if (!S_ISDIR(psbuf->st_ex_mode)) {
4713                 if (num_def_acls) {
4714                         DEBUG(5,("set_unix_posix_default_acl: Can't set default ACL on non-directory file %s\n", fname ));
4715                         errno = EISDIR;
4716                         return False;
4717                 } else {
4718                         return True;
4719                 }
4720         }
4721
4722         if (!num_def_acls) {
4723                 /* Remove the default ACL. */
4724                 if (SMB_VFS_SYS_ACL_DELETE_DEF_FILE(conn, fname) == -1) {
4725                         DEBUG(5,("set_unix_posix_default_acl: acl_delete_def_file failed on directory %s (%s)\n",
4726                                 fname, strerror(errno) ));
4727                         return False;
4728                 }
4729                 return True;
4730         }
4731
4732         if ((def_acl = create_posix_acl_from_wire(conn, num_def_acls, pdata)) == NULL) {
4733                 return False;
4734         }
4735
4736         if (SMB_VFS_SYS_ACL_SET_FILE(conn, fname, SMB_ACL_TYPE_DEFAULT, def_acl) == -1) {
4737                 DEBUG(5,("set_unix_posix_default_acl: acl_set_file failed on directory %s (%s)\n",
4738                         fname, strerror(errno) ));
4739                 TALLOC_FREE(def_acl);
4740                 return False;
4741         }
4742
4743         DEBUG(10,("set_unix_posix_default_acl: set default acl for file %s\n", fname ));
4744         TALLOC_FREE(def_acl);
4745         return True;
4746 }
4747
4748 /****************************************************************************
4749  Remove an ACL from a file. As we don't have acl_delete_entry() available
4750  we must read the current acl and copy all entries except MASK, USER and GROUP
4751  to a new acl, then set that. This (at least on Linux) causes any ACL to be
4752  removed.
4753  FIXME ! How does the share mask/mode fit into this.... ?
4754 ****************************************************************************/
4755
4756 static bool remove_posix_acl(connection_struct *conn, files_struct *fsp, const char *fname)
4757 {
4758         SMB_ACL_T file_acl = NULL;
4759         int entry_id = SMB_ACL_FIRST_ENTRY;
4760         SMB_ACL_ENTRY_T entry;
4761         bool ret = False;
4762         /* Create a new ACL with only 3 entries, u/g/w. */
4763         SMB_ACL_T new_file_acl = sys_acl_init();
4764         SMB_ACL_ENTRY_T user_ent = NULL;
4765         SMB_ACL_ENTRY_T group_ent = NULL;
4766         SMB_ACL_ENTRY_T other_ent = NULL;
4767
4768         if (new_file_acl == NULL) {
4769                 DEBUG(5,("remove_posix_acl: failed to init new ACL with 3 entries for file %s.\n", fname));
4770                 return False;
4771         }
4772
4773         /* Now create the u/g/w entries. */
4774         if (sys_acl_create_entry(&new_file_acl, &user_ent) == -1) {
4775                 DEBUG(5,("remove_posix_acl: Failed to create user entry for file %s. (%s)\n",
4776                         fname, strerror(errno) ));
4777                 goto done;
4778         }
4779         if (sys_acl_set_tag_type(user_ent, SMB_ACL_USER_OBJ) == -1) {
4780                 DEBUG(5,("remove_posix_acl: Failed to set user entry for file %s. (%s)\n",
4781                         fname, strerror(errno) ));
4782                 goto done;
4783         }
4784
4785         if (sys_acl_create_entry(&new_file_acl, &group_ent) == -1) {
4786                 DEBUG(5,("remove_posix_acl: Failed to create group entry for file %s. (%s)\n",
4787                         fname, strerror(errno) ));
4788                 goto done;
4789         }
4790         if (sys_acl_set_tag_type(group_ent, SMB_ACL_GROUP_OBJ) == -1) {
4791                 DEBUG(5,("remove_posix_acl: Failed to set group entry for file %s. (%s)\n",
4792                         fname, strerror(errno) ));
4793                 goto done;
4794         }
4795
4796         if (sys_acl_create_entry(&new_file_acl, &other_ent) == -1) {
4797                 DEBUG(5,("remove_posix_acl: Failed to create other entry for file %s. (%s)\n",
4798                         fname, strerror(errno) ));
4799                 goto done;
4800         }
4801         if (sys_acl_set_tag_type(other_ent, SMB_ACL_OTHER) == -1) {
4802                 DEBUG(5,("remove_posix_acl: Failed to set other entry for file %s. (%s)\n",
4803                         fname, strerror(errno) ));
4804                 goto done;
4805         }
4806
4807         /* Get the current file ACL. */
4808         if (fsp && fsp->fh->fd != -1) {
4809                 file_acl = SMB_VFS_SYS_ACL_GET_FD(fsp);
4810         } else {
4811                 file_acl = SMB_VFS_SYS_ACL_GET_FILE( conn, fname, SMB_ACL_TYPE_ACCESS);
4812         }
4813
4814         if (file_acl == NULL) {
4815                 /* This is only returned if an error occurred. Even for a file with
4816                    no acl a u/g/w acl should be returned. */
4817                 DEBUG(5,("remove_posix_acl: failed to get ACL from file %s (%s).\n",
4818                         fname, strerror(errno) ));
4819                 goto done;
4820         }
4821
4822         while ( sys_acl_get_entry(file_acl, entry_id, &entry) == 1) {
4823                 SMB_ACL_TAG_T tagtype;
4824                 SMB_ACL_PERMSET_T permset;
4825
4826                 entry_id = SMB_ACL_NEXT_ENTRY;
4827
4828                 if (sys_acl_get_tag_type(entry, &tagtype) == -1) {
4829                         DEBUG(5,("remove_posix_acl: failed to get tagtype from ACL on file %s (%s).\n",
4830                                 fname, strerror(errno) ));
4831                         goto done;
4832                 }
4833
4834                 if (sys_acl_get_permset(entry, &permset) == -1) {
4835                         DEBUG(5,("remove_posix_acl: failed to get permset from ACL on file %s (%s).\n",
4836                                 fname, strerror(errno) ));
4837                         goto done;
4838                 }
4839
4840                 if (tagtype == SMB_ACL_USER_OBJ) {
4841                         if (sys_acl_set_permset(user_ent, permset) == -1) {
4842                                 DEBUG(5,("remove_posix_acl: failed to set permset from ACL on file %s (%s).\n",
4843                                         fname, strerror(errno) ));
4844                         }
4845                 } else if (tagtype == SMB_ACL_GROUP_OBJ) {
4846                         if (sys_acl_set_permset(group_ent, permset) == -1) {
4847                                 DEBUG(5,("remove_posix_acl: failed to set permset from ACL on file %s (%s).\n",
4848                                         fname, strerror(errno) ));
4849                         }
4850                 } else if (tagtype == SMB_ACL_OTHER) {
4851                         if (sys_acl_set_permset(other_ent, permset) == -1) {
4852                                 DEBUG(5,("remove_posix_acl: failed to set permset from ACL on file %s (%s).\n",
4853                                         fname, strerror(errno) ));
4854                         }
4855                 }
4856         }
4857
4858         /* Set the new empty file ACL. */
4859         if (fsp && fsp->fh->fd != -1) {
4860                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, new_file_acl) == -1) {
4861                         DEBUG(5,("remove_posix_acl: acl_set_file failed on %s (%s)\n",
4862                                 fname, strerror(errno) ));
4863                         goto done;
4864                 }
4865         } else {
4866                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fname, SMB_ACL_TYPE_ACCESS, new_file_acl) == -1) {
4867                         DEBUG(5,("remove_posix_acl: acl_set_file failed on %s (%s)\n",
4868                                 fname, strerror(errno) ));
4869                         goto done;
4870                 }
4871         }
4872
4873         ret = True;
4874
4875  done:
4876
4877         if (file_acl) {
4878                 TALLOC_FREE(file_acl);
4879         }
4880         if (new_file_acl) {
4881                 TALLOC_FREE(new_file_acl);
4882         }
4883         return ret;
4884 }
4885
4886 /****************************************************************************
4887  Calls from UNIX extensions - POSIX ACL set.
4888  If num_def_acls == 0 then read/modify/write acl after removing all entries
4889  except SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER.
4890 ****************************************************************************/
4891
4892 bool set_unix_posix_acl(connection_struct *conn, files_struct *fsp, const char *fname, uint16 num_acls, const char *pdata)
4893 {
4894         SMB_ACL_T file_acl = NULL;
4895
4896         if (!num_acls) {
4897                 /* Remove the ACL from the file. */
4898                 return remove_posix_acl(conn, fsp, fname);
4899         }
4900
4901         if ((file_acl = create_posix_acl_from_wire(conn, num_acls, pdata)) == NULL) {
4902                 return False;
4903         }
4904
4905         if (fsp && fsp->fh->fd != -1) {
4906                 /* The preferred way - use an open fd. */
4907                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, file_acl) == -1) {
4908                         DEBUG(5,("set_unix_posix_acl: acl_set_file failed on %s (%s)\n",
4909                                 fname, strerror(errno) ));
4910                         TALLOC_FREE(file_acl);
4911                         return False;
4912                 }
4913         } else {
4914                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fname, SMB_ACL_TYPE_ACCESS, file_acl) == -1) {
4915                         DEBUG(5,("set_unix_posix_acl: acl_set_file failed on %s (%s)\n",
4916                                 fname, strerror(errno) ));
4917                         TALLOC_FREE(file_acl);
4918                         return False;
4919                 }
4920         }
4921
4922         DEBUG(10,("set_unix_posix_acl: set acl for file %s\n", fname ));
4923         TALLOC_FREE(file_acl);
4924         return True;
4925 }
4926
4927 /********************************************************************
4928  Pull the NT ACL from a file on disk or the OpenEventlog() access
4929  check.  Caller is responsible for freeing the returned security
4930  descriptor via TALLOC_FREE().  This is designed for dealing with 
4931  user space access checks in smbd outside of the VFS.  For example,
4932  checking access rights in OpenEventlog().
4933
4934  Assume we are dealing with files (for now)
4935 ********************************************************************/
4936
4937 struct security_descriptor *get_nt_acl_no_snum( TALLOC_CTX *ctx, const char *fname, uint32 security_info_wanted)
4938 {
4939         struct security_descriptor *psd, *ret_sd;
4940         connection_struct *conn;
4941         files_struct finfo;
4942         struct fd_handle fh;
4943         NTSTATUS status;
4944         TALLOC_CTX *frame = talloc_stackframe();
4945
4946         conn = talloc_zero(frame, connection_struct);
4947         if (conn == NULL) {
4948                 DEBUG(0, ("talloc failed\n"));
4949                 return NULL;
4950         }
4951
4952         if (!(conn->params = talloc(conn, struct share_params))) {
4953                 DEBUG(0,("get_nt_acl_no_snum: talloc() failed!\n"));
4954                 TALLOC_FREE(frame);
4955                 return NULL;
4956         }
4957
4958         conn->params->service = -1;
4959
4960         set_conn_connectpath(conn, "/");
4961
4962         if (!smbd_vfs_init(conn)) {
4963                 DEBUG(0,("get_nt_acl_no_snum: Unable to create a fake connection struct!\n"));
4964                 conn_free(conn);
4965                 TALLOC_FREE(frame);
4966                 return NULL;
4967         }
4968
4969         ZERO_STRUCT( finfo );
4970         ZERO_STRUCT( fh );
4971
4972         finfo.fnum = FNUM_FIELD_INVALID;
4973         finfo.conn = conn;
4974         finfo.fh = &fh;
4975         finfo.fh->fd = -1;
4976
4977         status = create_synthetic_smb_fname(frame, fname, NULL, NULL,
4978                                             &finfo.fsp_name);
4979         if (!NT_STATUS_IS_OK(status)) {
4980                 conn_free(conn);
4981                 TALLOC_FREE(frame);
4982                 return NULL;
4983         }
4984
4985         if (!NT_STATUS_IS_OK(SMB_VFS_FGET_NT_ACL( &finfo, security_info_wanted, &psd))) {
4986                 DEBUG(0,("get_nt_acl_no_snum: get_nt_acl returned zero.\n"));
4987                 TALLOC_FREE(finfo.fsp_name);
4988                 conn_free(conn);
4989                 TALLOC_FREE(frame);
4990                 return NULL;
4991         }
4992
4993         ret_sd = dup_sec_desc( ctx, psd );
4994
4995         TALLOC_FREE(finfo.fsp_name);
4996         conn_free(conn);
4997         TALLOC_FREE(frame);
4998
4999         return ret_sd;
5000 }
5001
5002 /* Stolen shamelessly from pvfs_default_acl() in source4 :-). */
5003
5004 NTSTATUS make_default_filesystem_acl(TALLOC_CTX *ctx,
5005                                         const char *name,
5006                                         SMB_STRUCT_STAT *psbuf,
5007                                         struct security_descriptor **ppdesc)
5008 {
5009         struct dom_sid owner_sid, group_sid;
5010         size_t size = 0;
5011         struct security_ace aces[4];
5012         uint32_t access_mask = 0;
5013         mode_t mode = psbuf->st_ex_mode;
5014         struct security_acl *new_dacl = NULL;
5015         int idx = 0;
5016
5017         DEBUG(10,("make_default_filesystem_acl: file %s mode = 0%o\n",
5018                 name, (int)mode ));
5019
5020         uid_to_sid(&owner_sid, psbuf->st_ex_uid);
5021         gid_to_sid(&group_sid, psbuf->st_ex_gid);
5022
5023         /*
5024          We provide up to 4 ACEs
5025                 - Owner
5026                 - Group
5027                 - Everyone
5028                 - NT System
5029         */
5030
5031         if (mode & S_IRUSR) {
5032                 if (mode & S_IWUSR) {
5033                         access_mask |= SEC_RIGHTS_FILE_ALL;
5034                 } else {
5035                         access_mask |= SEC_RIGHTS_FILE_READ | SEC_FILE_EXECUTE;
5036                 }
5037         }
5038         if (mode & S_IWUSR) {
5039                 access_mask |= SEC_RIGHTS_FILE_WRITE | SEC_STD_DELETE;
5040         }
5041
5042         init_sec_ace(&aces[idx],
5043                         &owner_sid,
5044                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5045                         access_mask,
5046                         0);
5047         idx++;
5048
5049         access_mask = 0;
5050         if (mode & S_IRGRP) {
5051                 access_mask |= SEC_RIGHTS_FILE_READ | SEC_FILE_EXECUTE;
5052         }
5053         if (mode & S_IWGRP) {
5054                 /* note that delete is not granted - this matches posix behaviour */
5055                 access_mask |= SEC_RIGHTS_FILE_WRITE;
5056         }
5057         if (access_mask) {
5058                 init_sec_ace(&aces[idx],
5059                         &group_sid,
5060                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5061                         access_mask,
5062                         0);
5063                 idx++;
5064         }
5065
5066         access_mask = 0;
5067         if (mode & S_IROTH) {
5068                 access_mask |= SEC_RIGHTS_FILE_READ | SEC_FILE_EXECUTE;
5069         }
5070         if (mode & S_IWOTH) {
5071                 access_mask |= SEC_RIGHTS_FILE_WRITE;
5072         }
5073         if (access_mask) {
5074                 init_sec_ace(&aces[idx],
5075                         &global_sid_World,
5076                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5077                         access_mask,
5078                         0);
5079                 idx++;
5080         }
5081
5082         init_sec_ace(&aces[idx],
5083                         &global_sid_System,
5084                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5085                         SEC_RIGHTS_FILE_ALL,
5086                         0);
5087         idx++;
5088
5089         new_dacl = make_sec_acl(ctx,
5090                         NT4_ACL_REVISION,
5091                         idx,
5092                         aces);
5093
5094         if (!new_dacl) {
5095                 return NT_STATUS_NO_MEMORY;
5096         }
5097
5098         *ppdesc = make_sec_desc(ctx,
5099                         SECURITY_DESCRIPTOR_REVISION_1,
5100                         SEC_DESC_SELF_RELATIVE|SEC_DESC_DACL_PRESENT,
5101                         &owner_sid,
5102                         &group_sid,
5103                         NULL,
5104                         new_dacl,
5105                         &size);
5106         if (!*ppdesc) {
5107                 return NT_STATUS_NO_MEMORY;
5108         }
5109         return NT_STATUS_OK;
5110 }