Simplify ensure_canon_entry_valid by splitting out the _get codepath.
[metze/samba/wip.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 get_acl, the pst struct is valid and contains
1432  the mode of the file. When using this call on set_acl, the pst struct has
1433  been modified to have a mode containing the default for this file or directory
1434  type.
1435 ****************************************************************************/
1436
1437 static bool ensure_canon_entry_valid(connection_struct *conn,
1438                                         canon_ace **pp_ace,
1439                                         bool is_default_acl,
1440                                         const struct share_params *params,
1441                                         const bool is_directory,
1442                                         const struct dom_sid *pfile_owner_sid,
1443                                         const struct dom_sid *pfile_grp_sid,
1444                                         const SMB_STRUCT_STAT *pst,
1445                                         bool setting_acl)
1446 {
1447         canon_ace *pace;
1448         canon_ace *pace_user = NULL;
1449         canon_ace *pace_group = NULL;
1450         canon_ace *pace_other = NULL;
1451
1452         for (pace = *pp_ace; pace; pace = pace->next) {
1453                 if (pace->type == SMB_ACL_USER_OBJ) {
1454
1455                         if (setting_acl && !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 (setting_acl && !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 (setting_acl && !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 (setting_acl && !is_default_acl) {
1489                                 apply_default_perms(params, is_directory, pace, S_IRGRP);
1490                         }
1491                 }
1492         }
1493
1494         if (!pace_user) {
1495                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1496                         DEBUG(0,("ensure_canon_entry_valid: malloc fail.\n"));
1497                         return False;
1498                 }
1499
1500                 ZERO_STRUCTP(pace);
1501                 pace->type = SMB_ACL_USER_OBJ;
1502                 pace->owner_type = UID_ACE;
1503                 pace->unix_ug.type = ID_TYPE_UID;
1504                 pace->unix_ug.id = pst->st_ex_uid;
1505                 pace->trustee = *pfile_owner_sid;
1506                 pace->attr = ALLOW_ACE;
1507                 /* Start with existing permissions, principle of least
1508                    surprises for the user. */
1509                 pace->perms = pst->st_ex_mode;
1510
1511                 if (setting_acl) {
1512                         /* See if the owning user is in any of the other groups in
1513                            the ACE, or if there's a matching user entry (by uid
1514                            or in the case of ID_TYPE_BOTH by SID).
1515                            If so, OR in the permissions from that entry. */
1516
1517                         canon_ace *pace_iter;
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                 } else {
1542                         pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRUSR, S_IWUSR, S_IXUSR);
1543                 }
1544
1545                 DLIST_ADD(*pp_ace, pace);
1546                 pace_user = pace;
1547         }
1548
1549         if (!pace_group) {
1550                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1551                         DEBUG(0,("ensure_canon_entry_valid: malloc fail.\n"));
1552                         return False;
1553                 }
1554
1555                 ZERO_STRUCTP(pace);
1556                 pace->type = SMB_ACL_GROUP_OBJ;
1557                 pace->owner_type = GID_ACE;
1558                 pace->unix_ug.type = ID_TYPE_GID;
1559                 pace->unix_ug.id = pst->st_ex_gid;
1560                 pace->trustee = *pfile_grp_sid;
1561                 pace->attr = ALLOW_ACE;
1562                 if (setting_acl) {
1563                         /* If we only got an "everyone" perm, just use that. */
1564                         if (pace_other)
1565                                 pace->perms = pace_other->perms;
1566                         else
1567                                 pace->perms = 0;
1568                         if (!is_default_acl) {
1569                                 apply_default_perms(params, is_directory, pace, S_IRGRP);
1570                         }
1571                 } else {
1572                         pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRGRP, S_IWGRP, S_IXGRP);
1573                 }
1574
1575                 DLIST_ADD(*pp_ace, pace);
1576                 pace_group = pace;
1577         }
1578
1579         if (!pace_other) {
1580                 if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1581                         DEBUG(0,("ensure_canon_entry_valid: malloc fail.\n"));
1582                         return False;
1583                 }
1584
1585                 ZERO_STRUCTP(pace);
1586                 pace->type = SMB_ACL_OTHER;
1587                 pace->owner_type = WORLD_ACE;
1588                 pace->unix_ug.type = ID_TYPE_NOT_SPECIFIED;
1589                 pace->unix_ug.id = -1;
1590                 pace->trustee = global_sid_World;
1591                 pace->attr = ALLOW_ACE;
1592                 if (setting_acl) {
1593                         pace->perms = 0;
1594                         if (!is_default_acl) {
1595                                 apply_default_perms(params, is_directory, pace, S_IROTH);
1596                         }
1597                 } else
1598                         pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IROTH, S_IWOTH, S_IXOTH);
1599
1600                 DLIST_ADD(*pp_ace, pace);
1601                 pace_other = pace;
1602         }
1603
1604         if (setting_acl) {
1605                 /* Ensure when setting a POSIX ACL, that the uid for a
1606                    SMB_ACL_USER_OBJ ACE (the owner ACE entry) has a duplicate
1607                    permission entry as an SMB_ACL_USER, and a gid for a
1608                    SMB_ACL_GROUP_OBJ ACE (the primary group ACE entry) also has
1609                    a duplicate permission entry as an SMB_ACL_GROUP. If not,
1610                    then if the ownership or group ownership of this file or
1611                    directory gets changed, the user or group can lose their
1612                    access. */
1613                 bool got_duplicate_user = false;
1614                 bool got_duplicate_group = false;
1615
1616                 for (pace = *pp_ace; pace; pace = pace->next) {
1617                         if (pace->type == SMB_ACL_USER &&
1618                                         pace->unix_ug.id == pace_user->unix_ug.id) {
1619                                 /* Already got one. */
1620                                 got_duplicate_user = true;
1621                         } else if (pace->type == SMB_ACL_GROUP &&
1622                                         pace->unix_ug.id == pace_user->unix_ug.id) {
1623                                 /* Already got one. */
1624                                 got_duplicate_group = true;
1625                         } else if ((pace->type == SMB_ACL_GROUP)
1626                                    && (dom_sid_equal(&pace->trustee, &pace_user->trustee))) {
1627                                 /* If the SID owning the file appears
1628                                  * in a group entry, then we have
1629                                  * enough duplication, they will still
1630                                  * have access */
1631                                 got_duplicate_user = true;
1632                         }
1633                 }
1634
1635                 /* If the SID is equal for the user and group that we need
1636                    to add the duplicate for, add only the group */
1637                 if (!got_duplicate_user && !got_duplicate_group
1638                                 && dom_sid_equal(&pace_group->trustee,
1639                                                 &pace_user->trustee)) {
1640                         /* Add a duplicate SMB_ACL_GROUP entry, this
1641                          * will cover the owning SID as well, as it
1642                          * will always be mapped to both a uid and
1643                          * gid. */
1644
1645                         if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1646                                 DEBUG(0,("ensure_canon_entry_valid: talloc fail.\n"));
1647                                 return false;
1648                         }
1649
1650                         ZERO_STRUCTP(pace);
1651                         pace->type = SMB_ACL_GROUP;;
1652                         pace->owner_type = GID_ACE;
1653                         pace->unix_ug.type = ID_TYPE_GID;
1654                         pace->unix_ug.id = pace_group->unix_ug.id;
1655                         pace->trustee = pace_group->trustee;
1656                         pace->attr = pace_group->attr;
1657                         pace->perms = pace_group->perms;
1658
1659                         DLIST_ADD(*pp_ace, pace);
1660
1661                         /* We're done here, make sure the
1662                            statements below are not executed. */
1663                         got_duplicate_user = true;
1664                         got_duplicate_group = true;
1665                 }
1666
1667                 if (!got_duplicate_user) {
1668                         /* Add a duplicate SMB_ACL_USER entry. */
1669                         if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1670                                 DEBUG(0,("ensure_canon_entry_valid: talloc fail.\n"));
1671                                 return false;
1672                         }
1673
1674                         ZERO_STRUCTP(pace);
1675                         pace->type = SMB_ACL_USER;;
1676                         pace->owner_type = UID_ACE;
1677                         pace->unix_ug.type = ID_TYPE_UID;
1678                         pace->unix_ug.id = pace_user->unix_ug.id;
1679                         pace->trustee = pace_user->trustee;
1680                         pace->attr = pace_user->attr;
1681                         pace->perms = pace_user->perms;
1682
1683                         DLIST_ADD(*pp_ace, pace);
1684
1685                         got_duplicate_user = true;
1686                 }
1687
1688                 if (!got_duplicate_group) {
1689                         /* Add a duplicate SMB_ACL_GROUP entry. */
1690                         if ((pace = talloc(talloc_tos(), canon_ace)) == NULL) {
1691                                 DEBUG(0,("ensure_canon_entry_valid: talloc fail.\n"));
1692                                 return false;
1693                         }
1694
1695                         ZERO_STRUCTP(pace);
1696                         pace->type = SMB_ACL_GROUP;;
1697                         pace->owner_type = GID_ACE;
1698                         pace->unix_ug.type = ID_TYPE_GID;
1699                         pace->unix_ug.id = pace_group->unix_ug.id;
1700                         pace->trustee = pace_group->trustee;
1701                         pace->attr = pace_group->attr;
1702                         pace->perms = pace_group->perms;
1703
1704                         DLIST_ADD(*pp_ace, pace);
1705
1706                         got_duplicate_group = true;
1707                 }
1708
1709         }
1710
1711         return True;
1712 }
1713
1714 /****************************************************************************
1715  Check if a POSIX ACL has the required SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ entries.
1716  If it does not have them, check if there are any entries where the trustee is the
1717  file owner or the owning group, and map these to SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ.
1718  Note we must not do this to default directory ACLs.
1719 ****************************************************************************/
1720
1721 static void check_owning_objs(canon_ace *ace, struct dom_sid *pfile_owner_sid, struct dom_sid *pfile_grp_sid)
1722 {
1723         bool got_user_obj, got_group_obj;
1724         canon_ace *current_ace;
1725         int i, entries;
1726
1727         entries = count_canon_ace_list(ace);
1728         got_user_obj = False;
1729         got_group_obj = False;
1730
1731         for (i=0, current_ace = ace; i < entries; i++, current_ace = current_ace->next) {
1732                 if (current_ace->type == SMB_ACL_USER_OBJ)
1733                         got_user_obj = True;
1734                 else if (current_ace->type == SMB_ACL_GROUP_OBJ)
1735                         got_group_obj = True;
1736         }
1737         if (got_user_obj && got_group_obj) {
1738                 DEBUG(10,("check_owning_objs: ACL had owning user/group entries.\n"));
1739                 return;
1740         }
1741
1742         for (i=0, current_ace = ace; i < entries; i++, current_ace = current_ace->next) {
1743                 if (!got_user_obj && current_ace->owner_type == UID_ACE &&
1744                                 dom_sid_equal(&current_ace->trustee, pfile_owner_sid)) {
1745                         current_ace->type = SMB_ACL_USER_OBJ;
1746                         got_user_obj = True;
1747                 }
1748                 if (!got_group_obj && current_ace->owner_type == GID_ACE &&
1749                                 dom_sid_equal(&current_ace->trustee, pfile_grp_sid)) {
1750                         current_ace->type = SMB_ACL_GROUP_OBJ;
1751                         got_group_obj = True;
1752                 }
1753         }
1754         if (!got_user_obj)
1755                 DEBUG(10,("check_owning_objs: ACL is missing an owner entry.\n"));
1756         if (!got_group_obj)
1757                 DEBUG(10,("check_owning_objs: ACL is missing an owning group entry.\n"));
1758 }
1759
1760 static bool add_current_ace_to_acl(files_struct *fsp, struct security_ace *psa,
1761                                    canon_ace **file_ace, canon_ace **dir_ace,
1762                                    bool *got_file_allow, bool *got_dir_allow,
1763                                    bool *all_aces_are_inherit_only,
1764                                    canon_ace *current_ace)
1765 {
1766
1767         /*
1768          * Map the given NT permissions into a UNIX mode_t containing only
1769          * S_I(R|W|X)USR bits.
1770          */
1771
1772         current_ace->perms |= map_nt_perms( &psa->access_mask, S_IRUSR);
1773         current_ace->attr = (psa->type == SEC_ACE_TYPE_ACCESS_ALLOWED) ? ALLOW_ACE : DENY_ACE;
1774
1775         /* Store the ace_flag. */
1776         current_ace->ace_flags = psa->flags;
1777
1778         /*
1779          * Now add the created ace to either the file list, the directory
1780          * list, or both. We *MUST* preserve the order here (hence we use
1781          * DLIST_ADD_END) as NT ACLs are order dependent.
1782          */
1783
1784         if (fsp->is_directory) {
1785
1786                 /*
1787                  * We can only add to the default POSIX ACE list if the ACE is
1788                  * designed to be inherited by both files and directories.
1789                  */
1790
1791                 if ((psa->flags & (SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT)) ==
1792                     (SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT)) {
1793
1794                         canon_ace *current_dir_ace = current_ace;
1795                         DLIST_ADD_END(*dir_ace, current_ace, canon_ace *);
1796
1797                         /*
1798                          * Note if this was an allow ace. We can't process
1799                          * any further deny ace's after this.
1800                          */
1801
1802                         if (current_ace->attr == ALLOW_ACE)
1803                                 *got_dir_allow = True;
1804
1805                         if ((current_ace->attr == DENY_ACE) && *got_dir_allow) {
1806                                 DEBUG(0,("add_current_ace_to_acl: "
1807                                          "malformed ACL in "
1808                                          "inheritable ACL! Deny entry "
1809                                          "after Allow entry. Failing "
1810                                          "to set on file %s.\n",
1811                                          fsp_str_dbg(fsp)));
1812                                 return False;
1813                         }
1814
1815                         if( DEBUGLVL( 10 )) {
1816                                 dbgtext("add_current_ace_to_acl: adding dir ACL:\n");
1817                                 print_canon_ace( current_ace, 0);
1818                         }
1819
1820                         /*
1821                          * If this is not an inherit only ACE we need to add a duplicate
1822                          * to the file acl.
1823                          */
1824
1825                         if (!(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY)) {
1826                                 canon_ace *dup_ace = dup_canon_ace(current_ace);
1827
1828                                 if (!dup_ace) {
1829                                         DEBUG(0,("add_current_ace_to_acl: malloc fail !\n"));
1830                                         return False;
1831                                 }
1832
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 = dup_ace;
1838                                 /* We've essentially split this ace into two,
1839                                  * and added the ace with inheritance request
1840                                  * bits to the directory ACL. Drop those bits for
1841                                  * the ACE we're adding to the file list. */
1842                                 current_ace->ace_flags &= ~(SEC_ACE_FLAG_OBJECT_INHERIT|
1843                                                             SEC_ACE_FLAG_CONTAINER_INHERIT|
1844                                                             SEC_ACE_FLAG_INHERIT_ONLY);
1845                         } else {
1846                                 /*
1847                                  * We must not free current_ace here as its
1848                                  * pointer is now owned by the dir_ace list.
1849                                  */
1850                                 current_ace = NULL;
1851                         }
1852
1853                         /*
1854                          * current_ace is now either owned by file_ace
1855                          * or is NULL. We can safely operate on current_dir_ace
1856                          * to treat mapping for default acl entries differently
1857                          * than access acl entries.
1858                          */
1859
1860                         if (current_dir_ace->owner_type == UID_ACE) {
1861                                 /*
1862                                  * We already decided above this is a uid,
1863                                  * for default acls ace's only CREATOR_OWNER
1864                                  * maps to ACL_USER_OBJ. All other uid
1865                                  * ace's are ACL_USER.
1866                                  */
1867                                 if (dom_sid_equal(&current_dir_ace->trustee,
1868                                                   &global_sid_Creator_Owner)) {
1869                                         current_dir_ace->type = SMB_ACL_USER_OBJ;
1870                                 } else {
1871                                         current_dir_ace->type = SMB_ACL_USER;
1872                                 }
1873                         }
1874
1875                         if (current_dir_ace->owner_type == GID_ACE) {
1876                                 /*
1877                                  * We already decided above this is a gid,
1878                                  * for default acls ace's only CREATOR_GROUP
1879                                  * maps to ACL_GROUP_OBJ. All other uid
1880                                  * ace's are ACL_GROUP.
1881                                  */
1882                                 if (dom_sid_equal(&current_dir_ace->trustee,
1883                                                   &global_sid_Creator_Group)) {
1884                                         current_dir_ace->type = SMB_ACL_GROUP_OBJ;
1885                                 } else {
1886                                         current_dir_ace->type = SMB_ACL_GROUP;
1887                                 }
1888                         }
1889                 }
1890         }
1891
1892         /*
1893          * Only add to the file ACL if not inherit only.
1894          */
1895
1896         if (current_ace && !(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY)) {
1897                 DLIST_ADD_END(*file_ace, current_ace, canon_ace *);
1898
1899                 /*
1900                  * Note if this was an allow ace. We can't process
1901                  * any further deny ace's after this.
1902                  */
1903
1904                 if (current_ace->attr == ALLOW_ACE)
1905                         *got_file_allow = True;
1906
1907                 if ((current_ace->attr == DENY_ACE) && got_file_allow) {
1908                         DEBUG(0,("add_current_ace_to_acl: malformed "
1909                                  "ACL in file ACL ! Deny entry after "
1910                                  "Allow entry. Failing to set on file "
1911                                  "%s.\n", fsp_str_dbg(fsp)));
1912                         return False;
1913                 }
1914
1915                 if( DEBUGLVL( 10 )) {
1916                         dbgtext("add_current_ace_to_acl: adding file ACL:\n");
1917                         print_canon_ace( current_ace, 0);
1918                 }
1919                 *all_aces_are_inherit_only = False;
1920                 /*
1921                  * We must not free current_ace here as its
1922                  * pointer is now owned by the file_ace list.
1923                  */
1924                 current_ace = NULL;
1925         }
1926
1927         /*
1928          * Free if ACE was not added.
1929          */
1930
1931         TALLOC_FREE(current_ace);
1932         return true;
1933 }
1934
1935 /****************************************************************************
1936  Unpack a struct security_descriptor into two canonical ace lists.
1937 ****************************************************************************/
1938
1939 static bool create_canon_ace_lists(files_struct *fsp,
1940                                         const SMB_STRUCT_STAT *pst,
1941                                         struct dom_sid *pfile_owner_sid,
1942                                         struct dom_sid *pfile_grp_sid,
1943                                         canon_ace **ppfile_ace,
1944                                         canon_ace **ppdir_ace,
1945                                         const struct security_acl *dacl)
1946 {
1947         bool all_aces_are_inherit_only = (fsp->is_directory ? True : False);
1948         canon_ace *file_ace = NULL;
1949         canon_ace *dir_ace = NULL;
1950         canon_ace *current_ace = NULL;
1951         bool got_dir_allow = False;
1952         bool got_file_allow = False;
1953         int i, j;
1954
1955         *ppfile_ace = NULL;
1956         *ppdir_ace = NULL;
1957
1958         /*
1959          * Convert the incoming ACL into a more regular form.
1960          */
1961
1962         for(i = 0; i < dacl->num_aces; i++) {
1963                 struct security_ace *psa = &dacl->aces[i];
1964
1965                 if((psa->type != SEC_ACE_TYPE_ACCESS_ALLOWED) && (psa->type != SEC_ACE_TYPE_ACCESS_DENIED)) {
1966                         DEBUG(3,("create_canon_ace_lists: unable to set anything but an ALLOW or DENY ACE.\n"));
1967                         return False;
1968                 }
1969
1970                 if (nt4_compatible_acls()) {
1971                         /*
1972                          * The security mask may be UNIX_ACCESS_NONE which should map into
1973                          * no permissions (we overload the WRITE_OWNER bit for this) or it
1974                          * should be one of the ALL/EXECUTE/READ/WRITE bits. Arrange for this
1975                          * to be so. Any other bits override the UNIX_ACCESS_NONE bit.
1976                          */
1977
1978                         /*
1979                          * Convert GENERIC bits to specific bits.
1980                          */
1981  
1982                         se_map_generic(&psa->access_mask, &file_generic_mapping);
1983
1984                         psa->access_mask &= (UNIX_ACCESS_NONE|FILE_ALL_ACCESS);
1985
1986                         if(psa->access_mask != UNIX_ACCESS_NONE)
1987                                 psa->access_mask &= ~UNIX_ACCESS_NONE;
1988                 }
1989         }
1990
1991         /*
1992          * Deal with the fact that NT 4.x re-writes the canonical format
1993          * that we return for default ACLs. If a directory ACE is identical
1994          * to a inherited directory ACE then NT changes the bits so that the
1995          * first ACE is set to OI|IO and the second ACE for this SID is set
1996          * to CI. We need to repair this. JRA.
1997          */
1998
1999         for(i = 0; i < dacl->num_aces; i++) {
2000                 struct security_ace *psa1 = &dacl->aces[i];
2001
2002                 for (j = i + 1; j < dacl->num_aces; j++) {
2003                         struct security_ace *psa2 = &dacl->aces[j];
2004
2005                         if (psa1->access_mask != psa2->access_mask)
2006                                 continue;
2007
2008                         if (!dom_sid_equal(&psa1->trustee, &psa2->trustee))
2009                                 continue;
2010
2011                         /*
2012                          * Ok - permission bits and SIDs are equal.
2013                          * Check if flags were re-written.
2014                          */
2015
2016                         if (psa1->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
2017
2018                                 psa1->flags |= (psa2->flags & (SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT));
2019                                 psa2->flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT);
2020
2021                         } else if (psa2->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
2022
2023                                 psa2->flags |= (psa1->flags & (SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT));
2024                                 psa1->flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT);
2025
2026                         }
2027                 }
2028         }
2029
2030         for(i = 0; i < dacl->num_aces; i++) {
2031                 struct security_ace *psa = &dacl->aces[i];
2032
2033                 /*
2034                  * Create a canon_ace entry representing this NT DACL ACE.
2035                  */
2036
2037                 if ((current_ace = talloc(talloc_tos(), canon_ace)) == NULL) {
2038                         free_canon_ace_list(file_ace);
2039                         free_canon_ace_list(dir_ace);
2040                         DEBUG(0,("create_canon_ace_lists: malloc fail.\n"));
2041                         return False;
2042                 }
2043
2044                 ZERO_STRUCTP(current_ace);
2045
2046                 sid_copy(&current_ace->trustee, &psa->trustee);
2047
2048                 /*
2049                  * Try and work out if the SID is a user or group
2050                  * as we need to flag these differently for POSIX.
2051                  * Note what kind of a POSIX ACL this should map to.
2052                  */
2053
2054                 if( dom_sid_equal(&current_ace->trustee, &global_sid_World)) {
2055                         current_ace->owner_type = WORLD_ACE;
2056                         current_ace->unix_ug.type = ID_TYPE_NOT_SPECIFIED;
2057                         current_ace->unix_ug.id = -1;
2058                         current_ace->type = SMB_ACL_OTHER;
2059                 } else if (dom_sid_equal(&current_ace->trustee, &global_sid_Creator_Owner)) {
2060                         current_ace->owner_type = UID_ACE;
2061                         current_ace->unix_ug.type = ID_TYPE_UID;
2062                         current_ace->unix_ug.id = pst->st_ex_uid;
2063                         current_ace->type = SMB_ACL_USER_OBJ;
2064
2065                         /*
2066                          * The Creator Owner entry only specifies inheritable permissions,
2067                          * never access permissions. WinNT doesn't always set the ACE to
2068                          * INHERIT_ONLY, though.
2069                          */
2070
2071                         psa->flags |= SEC_ACE_FLAG_INHERIT_ONLY;
2072
2073                 } else if (dom_sid_equal(&current_ace->trustee, &global_sid_Creator_Group)) {
2074                         current_ace->owner_type = GID_ACE;
2075                         current_ace->unix_ug.type = ID_TYPE_GID;
2076                         current_ace->unix_ug.id = pst->st_ex_gid;
2077                         current_ace->type = SMB_ACL_GROUP_OBJ;
2078
2079                         /*
2080                          * The Creator Group entry only specifies inheritable permissions,
2081                          * never access permissions. WinNT doesn't always set the ACE to
2082                          * INHERIT_ONLY, though.
2083                          */
2084                         psa->flags |= SEC_ACE_FLAG_INHERIT_ONLY;
2085
2086                 } else {
2087                         struct unixid unixid;
2088
2089                         if (!sids_to_unixids(&current_ace->trustee, 1, &unixid)) {
2090                                 free_canon_ace_list(file_ace);
2091                                 free_canon_ace_list(dir_ace);
2092                                 TALLOC_FREE(current_ace);
2093                                 DEBUG(0, ("create_canon_ace_lists: sids_to_unixids "
2094                                         "failed for %s (allocation failure)\n",
2095                                         sid_string_dbg(&current_ace->trustee)));
2096                                 return false;
2097                         }
2098
2099                         if (unixid.type == ID_TYPE_BOTH) {
2100                                 /* If it's the owning user, this is a
2101                                  * user_obj, not a user.  This way, we
2102                                  * get a valid ACL for groups that own
2103                                  * files, without putting user ACL
2104                                  * entries in for groups otherwise */
2105                                 if (unixid.id == pst->st_ex_uid) {
2106                                         current_ace->owner_type = UID_ACE;
2107                                         current_ace->unix_ug.type = ID_TYPE_UID;
2108                                         current_ace->unix_ug.id = unixid.id;
2109                                         current_ace->type = SMB_ACL_USER_OBJ;
2110
2111                                         /* Add the user object to the posix ACL,
2112                                            and proceed to the group mapping
2113                                            below. This handles the talloc_free
2114                                            of current_ace if not added for some
2115                                            reason */
2116                                         if (!add_current_ace_to_acl(fsp,
2117                                                         psa,
2118                                                         &file_ace,
2119                                                         &dir_ace,
2120                                                         &got_file_allow,
2121                                                         &got_dir_allow,
2122                                                         &all_aces_are_inherit_only,
2123                                                         current_ace)) {
2124                                                 free_canon_ace_list(file_ace);
2125                                                 free_canon_ace_list(dir_ace);
2126                                                 return false;
2127                                         }
2128
2129                                         if ((current_ace = talloc(talloc_tos(),
2130                                                         canon_ace)) == NULL) {
2131                                                 free_canon_ace_list(file_ace);
2132                                                 free_canon_ace_list(dir_ace);
2133                                                 DEBUG(0,("create_canon_ace_lists: "
2134                                                         "malloc fail.\n"));
2135                                                 return False;
2136                                         }
2137
2138                                         ZERO_STRUCTP(current_ace);
2139                                 }
2140
2141                                 sid_copy(&current_ace->trustee, &psa->trustee);
2142
2143                                 current_ace->unix_ug.type = ID_TYPE_GID;
2144                                 current_ace->unix_ug.id = unixid.id;
2145                                 current_ace->owner_type = GID_ACE;
2146                                 /* If it's the primary group, this is a
2147                                    group_obj, not a group. */
2148                                 if (current_ace->unix_ug.id == pst->st_ex_gid) {
2149                                         current_ace->type = SMB_ACL_GROUP_OBJ;
2150                                 } else {
2151                                         current_ace->type = SMB_ACL_GROUP;
2152                                 }
2153
2154                         } else if (unixid.type == ID_TYPE_UID) {
2155                                 current_ace->owner_type = UID_ACE;
2156                                 current_ace->unix_ug.type = ID_TYPE_UID;
2157                                 current_ace->unix_ug.id = unixid.id;
2158                                 /* If it's the owning user, this is a user_obj,
2159                                    not a user. */
2160                                 if (current_ace->unix_ug.id == pst->st_ex_uid) {
2161                                         current_ace->type = SMB_ACL_USER_OBJ;
2162                                 } else {
2163                                         current_ace->type = SMB_ACL_USER;
2164                                 }
2165                         } else if (unixid.type == ID_TYPE_GID) {
2166                                 current_ace->unix_ug.type = ID_TYPE_GID;
2167                                 current_ace->unix_ug.id = unixid.id;
2168                                 current_ace->owner_type = GID_ACE;
2169                                 /* If it's the primary group, this is a
2170                                    group_obj, not a group. */
2171                                 if (current_ace->unix_ug.id == pst->st_ex_gid) {
2172                                         current_ace->type = SMB_ACL_GROUP_OBJ;
2173                                 } else {
2174                                         current_ace->type = SMB_ACL_GROUP;
2175                                 }
2176                         } else {
2177                                 /*
2178                                  * Silently ignore map failures in non-mappable SIDs (NT Authority, BUILTIN etc).
2179                                  */
2180
2181                                 if (non_mappable_sid(&psa->trustee)) {
2182                                         DEBUG(10, ("create_canon_ace_lists: ignoring "
2183                                                    "non-mappable SID %s\n",
2184                                                    sid_string_dbg(&psa->trustee)));
2185                                         TALLOC_FREE(current_ace);
2186                                         continue;
2187                                 }
2188
2189                                 if (lp_force_unknown_acl_user(SNUM(fsp->conn))) {
2190                                         DEBUG(10, ("create_canon_ace_lists: ignoring "
2191                                                 "unknown or foreign SID %s\n",
2192                                                 sid_string_dbg(&psa->trustee)));
2193                                         TALLOC_FREE(current_ace);
2194                                         continue;
2195                                 }
2196
2197                                 free_canon_ace_list(file_ace);
2198                                 free_canon_ace_list(dir_ace);
2199                                 DEBUG(0, ("create_canon_ace_lists: unable to map SID "
2200                                           "%s to uid or gid.\n",
2201                                           sid_string_dbg(&current_ace->trustee)));
2202                                 TALLOC_FREE(current_ace);
2203                                 return false;
2204                         }
2205                 }
2206
2207                 /* handles the talloc_free of current_ace if not added for some reason */
2208                 if (!add_current_ace_to_acl(fsp, psa, &file_ace, &dir_ace,
2209                                             &got_file_allow, &got_dir_allow,
2210                                             &all_aces_are_inherit_only, current_ace)) {
2211                         free_canon_ace_list(file_ace);
2212                         free_canon_ace_list(dir_ace);
2213                         return false;
2214                 }
2215         }
2216
2217         if (fsp->is_directory && all_aces_are_inherit_only) {
2218                 /*
2219                  * Windows 2000 is doing one of these weird 'inherit acl'
2220                  * traverses to conserve NTFS ACL resources. Just pretend
2221                  * there was no DACL sent. JRA.
2222                  */
2223
2224                 DEBUG(10,("create_canon_ace_lists: Win2k inherit acl traverse. Ignoring DACL.\n"));
2225                 free_canon_ace_list(file_ace);
2226                 free_canon_ace_list(dir_ace);
2227                 file_ace = NULL;
2228                 dir_ace = NULL;
2229         } else {
2230                 /*
2231                  * Check if we have SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ entries in
2232                  * the file ACL. If we don't have them, check if any SMB_ACL_USER/SMB_ACL_GROUP
2233                  * entries can be converted to *_OBJ. Don't do this for the default
2234                  * ACL, we will create them separately for this if needed inside
2235                  * ensure_canon_entry_valid().
2236                  */
2237                 if (file_ace) {
2238                         check_owning_objs(file_ace, pfile_owner_sid, pfile_grp_sid);
2239                 }
2240         }
2241
2242         *ppfile_ace = file_ace;
2243         *ppdir_ace = dir_ace;
2244
2245         return True;
2246 }
2247
2248 /****************************************************************************
2249  ASCII art time again... JRA :-).
2250
2251  We have 4 cases to process when moving from an NT ACL to a POSIX ACL. Firstly,
2252  we insist the ACL is in canonical form (ie. all DENY entries preceede ALLOW
2253  entries). Secondly, the merge code has ensured that all duplicate SID entries for
2254  allow or deny have been merged, so the same SID can only appear once in the deny
2255  list or once in the allow list.
2256
2257  We then process as follows :
2258
2259  ---------------------------------------------------------------------------
2260  First pass - look for a Everyone DENY entry.
2261
2262  If it is deny all (rwx) trunate the list at this point.
2263  Else, walk the list from this point and use the deny permissions of this
2264  entry as a mask on all following allow entries. Finally, delete
2265  the Everyone DENY entry (we have applied it to everything possible).
2266
2267  In addition, in this pass we remove any DENY entries that have 
2268  no permissions (ie. they are a DENY nothing).
2269  ---------------------------------------------------------------------------
2270  Second pass - only deal with deny user entries.
2271
2272  DENY user1 (perms XXX)
2273
2274  new_perms = 0
2275  for all following allow group entries where user1 is in group
2276         new_perms |= group_perms;
2277
2278  user1 entry perms = new_perms & ~ XXX;
2279
2280  Convert the deny entry to an allow entry with the new perms and
2281  push to the end of the list. Note if the user was in no groups
2282  this maps to a specific allow nothing entry for this user.
2283
2284  The common case from the NT ACL choser (userX deny all) is
2285  optimised so we don't do the group lookup - we just map to
2286  an allow nothing entry.
2287
2288  What we're doing here is inferring the allow permissions the
2289  person setting the ACE on user1 wanted by looking at the allow
2290  permissions on the groups the user is currently in. This will
2291  be a snapshot, depending on group membership but is the best
2292  we can do and has the advantage of failing closed rather than
2293  open.
2294  ---------------------------------------------------------------------------
2295  Third pass - only deal with deny group entries.
2296
2297  DENY group1 (perms XXX)
2298
2299  for all following allow user entries where user is in group1
2300    user entry perms = user entry perms & ~ XXX;
2301
2302  If there is a group Everyone allow entry with permissions YYY,
2303  convert the group1 entry to an allow entry and modify its
2304  permissions to be :
2305
2306  new_perms = YYY & ~ XXX
2307
2308  and push to the end of the list.
2309
2310  If there is no group Everyone allow entry then convert the
2311  group1 entry to a allow nothing entry and push to the end of the list.
2312
2313  Note that the common case from the NT ACL choser (groupX deny all)
2314  cannot be optimised here as we need to modify user entries who are
2315  in the group to change them to a deny all also.
2316
2317  What we're doing here is modifying the allow permissions of
2318  user entries (which are more specific in POSIX ACLs) to mask
2319  out the explicit deny set on the group they are in. This will
2320  be a snapshot depending on current group membership but is the
2321  best we can do and has the advantage of failing closed rather
2322  than open.
2323  ---------------------------------------------------------------------------
2324  Fourth pass - cope with cumulative permissions.
2325
2326  for all allow user entries, if there exists an allow group entry with
2327  more permissive permissions, and the user is in that group, rewrite the
2328  allow user permissions to contain both sets of permissions.
2329
2330  Currently the code for this is #ifdef'ed out as these semantics make
2331  no sense to me. JRA.
2332  ---------------------------------------------------------------------------
2333
2334  Note we *MUST* do the deny user pass first as this will convert deny user
2335  entries into allow user entries which can then be processed by the deny
2336  group pass.
2337
2338  The above algorithm took a *lot* of thinking about - hence this
2339  explaination :-). JRA.
2340 ****************************************************************************/
2341
2342 /****************************************************************************
2343  Process a canon_ace list entries. This is very complex code. We need
2344  to go through and remove the "deny" permissions from any allow entry that matches
2345  the id of this entry. We have already refused any NT ACL that wasn't in correct
2346  order (DENY followed by ALLOW). If any allow entry ends up with zero permissions,
2347  we just remove it (to fail safe). We have already removed any duplicate ace
2348  entries. Treat an "Everyone" DENY_ACE as a special case - use it to mask all
2349  allow entries.
2350 ****************************************************************************/
2351
2352 static void process_deny_list(connection_struct *conn, canon_ace **pp_ace_list )
2353 {
2354         canon_ace *ace_list = *pp_ace_list;
2355         canon_ace *curr_ace = NULL;
2356         canon_ace *curr_ace_next = NULL;
2357
2358         /* Pass 1 above - look for an Everyone, deny entry. */
2359
2360         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2361                 canon_ace *allow_ace_p;
2362
2363                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2364
2365                 if (curr_ace->attr != DENY_ACE)
2366                         continue;
2367
2368                 if (curr_ace->perms == (mode_t)0) {
2369
2370                         /* Deny nothing entry - delete. */
2371
2372                         DLIST_REMOVE(ace_list, curr_ace);
2373                         continue;
2374                 }
2375
2376                 if (!dom_sid_equal(&curr_ace->trustee, &global_sid_World))
2377                         continue;
2378
2379                 /* JRATEST - assert. */
2380                 SMB_ASSERT(curr_ace->owner_type == WORLD_ACE);
2381
2382                 if (curr_ace->perms == ALL_ACE_PERMS) {
2383
2384                         /*
2385                          * Optimisation. This is a DENY_ALL to Everyone. Truncate the
2386                          * list at this point including this entry.
2387                          */
2388
2389                         canon_ace *prev_entry = DLIST_PREV(curr_ace);
2390
2391                         free_canon_ace_list( curr_ace );
2392                         if (prev_entry)
2393                                 DLIST_REMOVE(ace_list, prev_entry);
2394                         else {
2395                                 /* We deleted the entire list. */
2396                                 ace_list = NULL;
2397                         }
2398                         break;
2399                 }
2400
2401                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2402
2403                         /* 
2404                          * Only mask off allow entries.
2405                          */
2406
2407                         if (allow_ace_p->attr != ALLOW_ACE)
2408                                 continue;
2409
2410                         allow_ace_p->perms &= ~curr_ace->perms;
2411                 }
2412
2413                 /*
2414                  * Now it's been applied, remove it.
2415                  */
2416
2417                 DLIST_REMOVE(ace_list, curr_ace);
2418         }
2419
2420         /* Pass 2 above - deal with deny user entries. */
2421
2422         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2423                 mode_t new_perms = (mode_t)0;
2424                 canon_ace *allow_ace_p;
2425
2426                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2427
2428                 if (curr_ace->attr != DENY_ACE)
2429                         continue;
2430
2431                 if (curr_ace->owner_type != UID_ACE)
2432                         continue;
2433
2434                 if (curr_ace->perms == ALL_ACE_PERMS) {
2435
2436                         /*
2437                          * Optimisation - this is a deny everything to this user.
2438                          * Convert to an allow nothing and push to the end of the list.
2439                          */
2440
2441                         curr_ace->attr = ALLOW_ACE;
2442                         curr_ace->perms = (mode_t)0;
2443                         DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2444                         continue;
2445                 }
2446
2447                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2448
2449                         if (allow_ace_p->attr != ALLOW_ACE)
2450                                 continue;
2451
2452                         /* We process GID_ACE and WORLD_ACE entries only. */
2453
2454                         if (allow_ace_p->owner_type == UID_ACE)
2455                                 continue;
2456
2457                         if (uid_entry_in_group(conn, curr_ace, allow_ace_p))
2458                                 new_perms |= allow_ace_p->perms;
2459                 }
2460
2461                 /*
2462                  * Convert to a allow entry, modify the perms and push to the end
2463                  * of the list.
2464                  */
2465
2466                 curr_ace->attr = ALLOW_ACE;
2467                 curr_ace->perms = (new_perms & ~curr_ace->perms);
2468                 DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2469         }
2470
2471         /* Pass 3 above - deal with deny group entries. */
2472
2473         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2474                 canon_ace *allow_ace_p;
2475                 canon_ace *allow_everyone_p = NULL;
2476
2477                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2478
2479                 if (curr_ace->attr != DENY_ACE)
2480                         continue;
2481
2482                 if (curr_ace->owner_type != GID_ACE)
2483                         continue;
2484
2485                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2486
2487                         if (allow_ace_p->attr != ALLOW_ACE)
2488                                 continue;
2489
2490                         /* Store a pointer to the Everyone allow, if it exists. */
2491                         if (allow_ace_p->owner_type == WORLD_ACE)
2492                                 allow_everyone_p = allow_ace_p;
2493
2494                         /* We process UID_ACE entries only. */
2495
2496                         if (allow_ace_p->owner_type != UID_ACE)
2497                                 continue;
2498
2499                         /* Mask off the deny group perms. */
2500
2501                         if (uid_entry_in_group(conn, allow_ace_p, curr_ace))
2502                                 allow_ace_p->perms &= ~curr_ace->perms;
2503                 }
2504
2505                 /*
2506                  * Convert the deny to an allow with the correct perms and
2507                  * push to the end of the list.
2508                  */
2509
2510                 curr_ace->attr = ALLOW_ACE;
2511                 if (allow_everyone_p)
2512                         curr_ace->perms = allow_everyone_p->perms & ~curr_ace->perms;
2513                 else
2514                         curr_ace->perms = (mode_t)0;
2515                 DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2516         }
2517
2518         /* Doing this fourth pass allows Windows semantics to be layered
2519          * on top of POSIX semantics. I'm not sure if this is desirable.
2520          * For example, in W2K ACLs there is no way to say, "Group X no
2521          * access, user Y full access" if user Y is a member of group X.
2522          * This seems completely broken semantics to me.... JRA.
2523          */
2524
2525 #if 0
2526         /* Pass 4 above - deal with allow entries. */
2527
2528         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2529                 canon_ace *allow_ace_p;
2530
2531                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2532
2533                 if (curr_ace->attr != ALLOW_ACE)
2534                         continue;
2535
2536                 if (curr_ace->owner_type != UID_ACE)
2537                         continue;
2538
2539                 for (allow_ace_p = ace_list; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2540
2541                         if (allow_ace_p->attr != ALLOW_ACE)
2542                                 continue;
2543
2544                         /* We process GID_ACE entries only. */
2545
2546                         if (allow_ace_p->owner_type != GID_ACE)
2547                                 continue;
2548
2549                         /* OR in the group perms. */
2550
2551                         if (uid_entry_in_group(conn, curr_ace, allow_ace_p))
2552                                 curr_ace->perms |= allow_ace_p->perms;
2553                 }
2554         }
2555 #endif
2556
2557         *pp_ace_list = ace_list;
2558 }
2559
2560 /****************************************************************************
2561  Unpack a struct security_descriptor into two canonical ace lists. We don't depend on this
2562  succeeding.
2563 ****************************************************************************/
2564
2565 static bool unpack_canon_ace(files_struct *fsp,
2566                                 const SMB_STRUCT_STAT *pst,
2567                                 struct dom_sid *pfile_owner_sid,
2568                                 struct dom_sid *pfile_grp_sid,
2569                                 canon_ace **ppfile_ace,
2570                                 canon_ace **ppdir_ace,
2571                                 uint32 security_info_sent,
2572                                 const struct security_descriptor *psd)
2573 {
2574         canon_ace *file_ace = NULL;
2575         canon_ace *dir_ace = NULL;
2576
2577         *ppfile_ace = NULL;
2578         *ppdir_ace = NULL;
2579
2580         if(security_info_sent == 0) {
2581                 DEBUG(0,("unpack_canon_ace: no security info sent !\n"));
2582                 return False;
2583         }
2584
2585         /*
2586          * If no DACL then this is a chown only security descriptor.
2587          */
2588
2589         if(!(security_info_sent & SECINFO_DACL) || !psd->dacl)
2590                 return True;
2591
2592         /*
2593          * Now go through the DACL and create the canon_ace lists.
2594          */
2595
2596         if (!create_canon_ace_lists( fsp, pst, pfile_owner_sid, pfile_grp_sid,
2597                                                                 &file_ace, &dir_ace, psd->dacl))
2598                 return False;
2599
2600         if ((file_ace == NULL) && (dir_ace == NULL)) {
2601                 /* W2K traverse DACL set - ignore. */
2602                 return True;
2603         }
2604
2605         /*
2606          * Go through the canon_ace list and merge entries
2607          * belonging to identical users of identical allow or deny type.
2608          * We can do this as all deny entries come first, followed by
2609          * all allow entries (we have mandated this before accepting this acl).
2610          */
2611
2612         print_canon_ace_list( "file ace - before merge", file_ace);
2613         merge_aces( &file_ace, false);
2614
2615         print_canon_ace_list( "dir ace - before merge", dir_ace);
2616         merge_aces( &dir_ace, true);
2617
2618         /*
2619          * NT ACLs are order dependent. Go through the acl lists and
2620          * process DENY entries by masking the allow entries.
2621          */
2622
2623         print_canon_ace_list( "file ace - before deny", file_ace);
2624         process_deny_list(fsp->conn, &file_ace);
2625
2626         print_canon_ace_list( "dir ace - before deny", dir_ace);
2627         process_deny_list(fsp->conn, &dir_ace);
2628
2629         /*
2630          * A well formed POSIX file or default ACL has at least 3 entries, a 
2631          * SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER_OBJ
2632          * and optionally a mask entry. Ensure this is the case.
2633          */
2634
2635         print_canon_ace_list( "file ace - before valid", file_ace);
2636
2637         if (!ensure_canon_entry_valid(fsp->conn, &file_ace, false, fsp->conn->params,
2638                         fsp->is_directory, pfile_owner_sid, pfile_grp_sid, pst, True)) {
2639                 free_canon_ace_list(file_ace);
2640                 free_canon_ace_list(dir_ace);
2641                 return False;
2642         }
2643
2644         print_canon_ace_list( "dir ace - before valid", dir_ace);
2645
2646         if (dir_ace && !ensure_canon_entry_valid(fsp->conn, &dir_ace, true, fsp->conn->params,
2647                         fsp->is_directory, pfile_owner_sid, pfile_grp_sid, pst, True)) {
2648                 free_canon_ace_list(file_ace);
2649                 free_canon_ace_list(dir_ace);
2650                 return False;
2651         }
2652
2653         print_canon_ace_list( "file ace - return", file_ace);
2654         print_canon_ace_list( "dir ace - return", dir_ace);
2655
2656         *ppfile_ace = file_ace;
2657         *ppdir_ace = dir_ace;
2658         return True;
2659
2660 }
2661
2662 /******************************************************************************
2663  When returning permissions, try and fit NT display
2664  semantics if possible. Note the the canon_entries here must have been malloced.
2665  The list format should be - first entry = owner, followed by group and other user
2666  entries, last entry = other.
2667
2668  Note that this doesn't exactly match the NT semantics for an ACL. As POSIX entries
2669  are not ordered, and match on the most specific entry rather than walking a list,
2670  then a simple POSIX permission of rw-r--r-- should really map to 5 entries,
2671
2672  Entry 0: owner : deny all except read and write.
2673  Entry 1: owner : allow read and write.
2674  Entry 2: group : deny all except read.
2675  Entry 3: group : allow read.
2676  Entry 4: Everyone : allow read.
2677
2678  But NT cannot display this in their ACL editor !
2679 ********************************************************************************/
2680
2681 static void arrange_posix_perms(const char *filename, canon_ace **pp_list_head)
2682 {
2683         canon_ace *l_head = *pp_list_head;
2684         canon_ace *owner_ace = NULL;
2685         canon_ace *other_ace = NULL;
2686         canon_ace *ace = NULL;
2687
2688         for (ace = l_head; ace; ace = ace->next) {
2689                 if (ace->type == SMB_ACL_USER_OBJ)
2690                         owner_ace = ace;
2691                 else if (ace->type == SMB_ACL_OTHER) {
2692                         /* Last ace - this is "other" */
2693                         other_ace = ace;
2694                 }
2695         }
2696
2697         if (!owner_ace || !other_ace) {
2698                 DEBUG(0,("arrange_posix_perms: Invalid POSIX permissions for file %s, missing owner or other.\n",
2699                         filename ));
2700                 return;
2701         }
2702
2703         /*
2704          * The POSIX algorithm applies to owner first, and other last,
2705          * so ensure they are arranged in this order.
2706          */
2707
2708         if (owner_ace) {
2709                 DLIST_PROMOTE(l_head, owner_ace);
2710         }
2711
2712         if (other_ace) {
2713                 DLIST_DEMOTE(l_head, other_ace, canon_ace *);
2714         }
2715
2716         /* We have probably changed the head of the list. */
2717
2718         *pp_list_head = l_head;
2719 }
2720
2721 /****************************************************************************
2722  Create a linked list of canonical ACE entries.
2723 ****************************************************************************/
2724
2725 static canon_ace *canonicalise_acl(struct connection_struct *conn,
2726                                    const char *fname, SMB_ACL_T posix_acl,
2727                                    const SMB_STRUCT_STAT *psbuf,
2728                                    const struct dom_sid *powner, const struct dom_sid *pgroup, struct pai_val *pal, SMB_ACL_TYPE_T the_acl_type)
2729 {
2730         mode_t acl_mask = (S_IRUSR|S_IWUSR|S_IXUSR);
2731         canon_ace *l_head = NULL;
2732         canon_ace *ace = NULL;
2733         canon_ace *next_ace = NULL;
2734         int entry_id = SMB_ACL_FIRST_ENTRY;
2735         bool is_default_acl = (the_acl_type == SMB_ACL_TYPE_DEFAULT);
2736         SMB_ACL_ENTRY_T entry;
2737         size_t ace_count;
2738
2739         while ( posix_acl && (sys_acl_get_entry(posix_acl, entry_id, &entry) == 1)) {
2740                 SMB_ACL_TAG_T tagtype;
2741                 SMB_ACL_PERMSET_T permset;
2742                 struct dom_sid sid;
2743                 struct unixid unix_ug;
2744                 enum ace_owner owner_type;
2745
2746                 entry_id = SMB_ACL_NEXT_ENTRY;
2747
2748                 /* Is this a MASK entry ? */
2749                 if (sys_acl_get_tag_type(entry, &tagtype) == -1)
2750                         continue;
2751
2752                 if (sys_acl_get_permset(entry, &permset) == -1)
2753                         continue;
2754
2755                 /* Decide which SID to use based on the ACL type. */
2756                 switch(tagtype) {
2757                         case SMB_ACL_USER_OBJ:
2758                                 /* Get the SID from the owner. */
2759                                 sid_copy(&sid, powner);
2760                                 unix_ug.type = ID_TYPE_UID;
2761                                 unix_ug.id = psbuf->st_ex_uid;
2762                                 owner_type = UID_ACE;
2763                                 break;
2764                         case SMB_ACL_USER:
2765                                 {
2766                                         uid_t *puid = (uid_t *)sys_acl_get_qualifier(entry);
2767                                         if (puid == NULL) {
2768                                                 DEBUG(0,("canonicalise_acl: Failed to get uid.\n"));
2769                                                 continue;
2770                                         }
2771                                         uid_to_sid( &sid, *puid);
2772                                         unix_ug.type = ID_TYPE_UID;
2773                                         unix_ug.id = *puid;
2774                                         owner_type = UID_ACE;
2775                                         break;
2776                                 }
2777                         case SMB_ACL_GROUP_OBJ:
2778                                 /* Get the SID from the owning group. */
2779                                 sid_copy(&sid, pgroup);
2780                                 unix_ug.type = ID_TYPE_GID;
2781                                 unix_ug.id = psbuf->st_ex_gid;
2782                                 owner_type = GID_ACE;
2783                                 break;
2784                         case SMB_ACL_GROUP:
2785                                 {
2786                                         gid_t *pgid = (gid_t *)sys_acl_get_qualifier(entry);
2787                                         if (pgid == NULL) {
2788                                                 DEBUG(0,("canonicalise_acl: Failed to get gid.\n"));
2789                                                 continue;
2790                                         }
2791                                         gid_to_sid( &sid, *pgid);
2792                                         unix_ug.type = ID_TYPE_GID;
2793                                         unix_ug.id = *pgid;
2794                                         owner_type = GID_ACE;
2795                                         break;
2796                                 }
2797                         case SMB_ACL_MASK:
2798                                 acl_mask = convert_permset_to_mode_t(permset);
2799                                 continue; /* Don't count the mask as an entry. */
2800                         case SMB_ACL_OTHER:
2801                                 /* Use the Everyone SID */
2802                                 sid = global_sid_World;
2803                                 unix_ug.type = ID_TYPE_NOT_SPECIFIED;
2804                                 unix_ug.id = -1;
2805                                 owner_type = WORLD_ACE;
2806                                 break;
2807                         default:
2808                                 DEBUG(0,("canonicalise_acl: Unknown tagtype %u\n", (unsigned int)tagtype));
2809                                 continue;
2810                 }
2811
2812                 /*
2813                  * Add this entry to the list.
2814                  */
2815
2816                 if ((ace = talloc(talloc_tos(), canon_ace)) == NULL)
2817                         goto fail;
2818
2819                 ZERO_STRUCTP(ace);
2820                 ace->type = tagtype;
2821                 ace->perms = convert_permset_to_mode_t(permset);
2822                 ace->attr = ALLOW_ACE;
2823                 ace->trustee = sid;
2824                 ace->unix_ug = unix_ug;
2825                 ace->owner_type = owner_type;
2826                 ace->ace_flags = get_pai_flags(pal, ace, is_default_acl);
2827
2828                 DLIST_ADD(l_head, ace);
2829         }
2830
2831         /*
2832          * This next call will ensure we have at least a user/group/world set.
2833          */
2834
2835         if (!ensure_canon_entry_valid_on_get(conn, &l_head,
2836                                       powner, pgroup,
2837                                       psbuf))
2838                 goto fail;
2839
2840         /*
2841          * Now go through the list, masking the permissions with the
2842          * acl_mask. Ensure all DENY Entries are at the start of the list.
2843          */
2844
2845         DEBUG(10,("canonicalise_acl: %s ace entries before arrange :\n", is_default_acl ?  "Default" : "Access"));
2846
2847         for ( ace_count = 0, ace = l_head; ace; ace = next_ace, ace_count++) {
2848                 next_ace = ace->next;
2849
2850                 /* Masks are only applied to entries other than USER_OBJ and OTHER. */
2851                 if (ace->type != SMB_ACL_OTHER && ace->type != SMB_ACL_USER_OBJ)
2852                         ace->perms &= acl_mask;
2853
2854                 if (ace->perms == 0) {
2855                         DLIST_PROMOTE(l_head, ace);
2856                 }
2857
2858                 if( DEBUGLVL( 10 ) ) {
2859                         print_canon_ace(ace, ace_count);
2860                 }
2861         }
2862
2863         arrange_posix_perms(fname,&l_head );
2864
2865         print_canon_ace_list( "canonicalise_acl: ace entries after arrange", l_head );
2866
2867         return l_head;
2868
2869   fail:
2870
2871         free_canon_ace_list(l_head);
2872         return NULL;
2873 }
2874
2875 /****************************************************************************
2876  Check if the current user group list contains a given group.
2877 ****************************************************************************/
2878
2879 bool current_user_in_group(connection_struct *conn, gid_t gid)
2880 {
2881         int i;
2882         const struct security_unix_token *utok = get_current_utok(conn);
2883
2884         for (i = 0; i < utok->ngroups; i++) {
2885                 if (utok->groups[i] == gid) {
2886                         return True;
2887                 }
2888         }
2889
2890         return False;
2891 }
2892
2893 /****************************************************************************
2894  Should we override a deny ? Check 'acl group control' and 'dos filemode'.
2895 ****************************************************************************/
2896
2897 static bool acl_group_override(connection_struct *conn,
2898                                const struct smb_filename *smb_fname)
2899 {
2900         if ((errno != EPERM) && (errno != EACCES)) {
2901                 return false;
2902         }
2903
2904         /* file primary group == user primary or supplementary group */
2905         if (lp_acl_group_control(SNUM(conn)) &&
2906             current_user_in_group(conn, smb_fname->st.st_ex_gid)) {
2907                 return true;
2908         }
2909
2910         /* user has writeable permission */
2911         if (lp_dos_filemode(SNUM(conn)) &&
2912             can_write_to_file(conn, smb_fname)) {
2913                 return true;
2914         }
2915
2916         return false;
2917 }
2918
2919 /****************************************************************************
2920  Attempt to apply an ACL to a file or directory.
2921 ****************************************************************************/
2922
2923 static bool set_canon_ace_list(files_struct *fsp,
2924                                 canon_ace *the_ace,
2925                                 bool default_ace,
2926                                 const SMB_STRUCT_STAT *psbuf,
2927                                 bool *pacl_set_support)
2928 {
2929         connection_struct *conn = fsp->conn;
2930         bool ret = False;
2931         SMB_ACL_T the_acl = sys_acl_init();
2932         canon_ace *p_ace;
2933         int i;
2934         SMB_ACL_ENTRY_T mask_entry;
2935         bool got_mask_entry = False;
2936         SMB_ACL_PERMSET_T mask_permset;
2937         SMB_ACL_TYPE_T the_acl_type = (default_ace ? SMB_ACL_TYPE_DEFAULT : SMB_ACL_TYPE_ACCESS);
2938         bool needs_mask = False;
2939         mode_t mask_perms = 0;
2940
2941         /* Use the psbuf that was passed in. */
2942         if (psbuf != &fsp->fsp_name->st) {
2943                 fsp->fsp_name->st = *psbuf;
2944         }
2945
2946 #if defined(POSIX_ACL_NEEDS_MASK)
2947         /* HP-UX always wants to have a mask (called "class" there). */
2948         needs_mask = True;
2949 #endif
2950
2951         if (the_acl == NULL) {
2952                 DEBUG(0, ("sys_acl_init failed to allocate an ACL\n"));
2953                 return false;
2954         }
2955
2956         if( DEBUGLVL( 10 )) {
2957                 dbgtext("set_canon_ace_list: setting ACL:\n");
2958                 for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) {
2959                         print_canon_ace( p_ace, i);
2960                 }
2961         }
2962
2963         for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) {
2964                 SMB_ACL_ENTRY_T the_entry;
2965                 SMB_ACL_PERMSET_T the_permset;
2966
2967                 /*
2968                  * ACLs only "need" an ACL_MASK entry if there are any named user or
2969                  * named group entries. But if there is an ACL_MASK entry, it applies
2970                  * to ACL_USER, ACL_GROUP, and ACL_GROUP_OBJ entries. Set the mask
2971                  * so that it doesn't deny (i.e., mask off) any permissions.
2972                  */
2973
2974                 if (p_ace->type == SMB_ACL_USER || p_ace->type == SMB_ACL_GROUP) {
2975                         needs_mask = True;
2976                         mask_perms |= p_ace->perms;
2977                 } else if (p_ace->type == SMB_ACL_GROUP_OBJ) {
2978                         mask_perms |= p_ace->perms;
2979                 }
2980
2981                 /*
2982                  * Get the entry for this ACE.
2983                  */
2984
2985                 if (sys_acl_create_entry(&the_acl, &the_entry) == -1) {
2986                         DEBUG(0,("set_canon_ace_list: Failed to create entry %d. (%s)\n",
2987                                 i, strerror(errno) ));
2988                         goto fail;
2989                 }
2990
2991                 if (p_ace->type == SMB_ACL_MASK) {
2992                         mask_entry = the_entry;
2993                         got_mask_entry = True;
2994                 }
2995
2996                 /*
2997                  * Ok - we now know the ACL calls should be working, don't
2998                  * allow fallback to chmod.
2999                  */
3000
3001                 *pacl_set_support = True;
3002
3003                 /*
3004                  * Initialise the entry from the canon_ace.
3005                  */
3006
3007                 /*
3008                  * First tell the entry what type of ACE this is.
3009                  */
3010
3011                 if (sys_acl_set_tag_type(the_entry, p_ace->type) == -1) {
3012                         DEBUG(0,("set_canon_ace_list: Failed to set tag type on entry %d. (%s)\n",
3013                                 i, strerror(errno) ));
3014                         goto fail;
3015                 }
3016
3017                 /*
3018                  * Only set the qualifier (user or group id) if the entry is a user
3019                  * or group id ACE.
3020                  */
3021
3022                 if ((p_ace->type == SMB_ACL_USER) || (p_ace->type == SMB_ACL_GROUP)) {
3023                         if (sys_acl_set_qualifier(the_entry,(void *)&p_ace->unix_ug.id) == -1) {
3024                                 DEBUG(0,("set_canon_ace_list: Failed to set qualifier on entry %d. (%s)\n",
3025                                         i, strerror(errno) ));
3026                                 goto fail;
3027                         }
3028                 }
3029
3030                 /*
3031                  * Convert the mode_t perms in the canon_ace to a POSIX permset.
3032                  */
3033
3034                 if (sys_acl_get_permset(the_entry, &the_permset) == -1) {
3035                         DEBUG(0,("set_canon_ace_list: Failed to get permset on entry %d. (%s)\n",
3036                                 i, strerror(errno) ));
3037                         goto fail;
3038                 }
3039
3040                 if (map_acl_perms_to_permset(conn, p_ace->perms, &the_permset) == -1) {
3041                         DEBUG(0,("set_canon_ace_list: Failed to create permset for mode (%u) on entry %d. (%s)\n",
3042                                 (unsigned int)p_ace->perms, i, strerror(errno) ));
3043                         goto fail;
3044                 }
3045
3046                 /*
3047                  * ..and apply them to the entry.
3048                  */
3049
3050                 if (sys_acl_set_permset(the_entry, the_permset) == -1) {
3051                         DEBUG(0,("set_canon_ace_list: Failed to add permset on entry %d. (%s)\n",
3052                                 i, strerror(errno) ));
3053                         goto fail;
3054                 }
3055
3056                 if( DEBUGLVL( 10 ))
3057                         print_canon_ace( p_ace, i);
3058
3059         }
3060
3061         if (needs_mask && !got_mask_entry) {
3062                 if (sys_acl_create_entry(&the_acl, &mask_entry) == -1) {
3063                         DEBUG(0,("set_canon_ace_list: Failed to create mask entry. (%s)\n", strerror(errno) ));
3064                         goto fail;
3065                 }
3066
3067                 if (sys_acl_set_tag_type(mask_entry, SMB_ACL_MASK) == -1) {
3068                         DEBUG(0,("set_canon_ace_list: Failed to set tag type on mask entry. (%s)\n",strerror(errno) ));
3069                         goto fail;
3070                 }
3071
3072                 if (sys_acl_get_permset(mask_entry, &mask_permset) == -1) {
3073                         DEBUG(0,("set_canon_ace_list: Failed to get mask permset. (%s)\n", strerror(errno) ));
3074                         goto fail;
3075                 }
3076
3077                 if (map_acl_perms_to_permset(conn, S_IRUSR|S_IWUSR|S_IXUSR, &mask_permset) == -1) {
3078                         DEBUG(0,("set_canon_ace_list: Failed to create mask permset. (%s)\n", strerror(errno) ));
3079                         goto fail;
3080                 }
3081
3082                 if (sys_acl_set_permset(mask_entry, mask_permset) == -1) {
3083                         DEBUG(0,("set_canon_ace_list: Failed to add mask permset. (%s)\n", strerror(errno) ));
3084                         goto fail;
3085                 }
3086         }
3087
3088         /*
3089          * Finally apply it to the file or directory.
3090          */
3091
3092         if(default_ace || fsp->is_directory || fsp->fh->fd == -1) {
3093                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fsp->fsp_name->base_name,
3094                                              the_acl_type, the_acl) == -1) {
3095                         /*
3096                          * Some systems allow all the above calls and only fail with no ACL support
3097                          * when attempting to apply the acl. HPUX with HFS is an example of this. JRA.
3098                          */
3099                         if (no_acl_syscall_error(errno)) {
3100                                 *pacl_set_support = False;
3101                         }
3102
3103                         if (acl_group_override(conn, fsp->fsp_name)) {
3104                                 int sret;
3105
3106                                 DEBUG(5,("set_canon_ace_list: acl group "
3107                                          "control on and current user in file "
3108                                          "%s primary group.\n",
3109                                          fsp_str_dbg(fsp)));
3110
3111                                 become_root();
3112                                 sret = SMB_VFS_SYS_ACL_SET_FILE(conn,
3113                                     fsp->fsp_name->base_name, the_acl_type,
3114                                     the_acl);
3115                                 unbecome_root();
3116                                 if (sret == 0) {
3117                                         ret = True;     
3118                                 }
3119                         }
3120
3121                         if (ret == False) {
3122                                 DEBUG(2,("set_canon_ace_list: "
3123                                          "sys_acl_set_file type %s failed for "
3124                                          "file %s (%s).\n",
3125                                          the_acl_type == SMB_ACL_TYPE_DEFAULT ?
3126                                          "directory default" : "file",
3127                                          fsp_str_dbg(fsp), strerror(errno)));
3128                                 goto fail;
3129                         }
3130                 }
3131         } else {
3132                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl) == -1) {
3133                         /*
3134                          * Some systems allow all the above calls and only fail with no ACL support
3135                          * when attempting to apply the acl. HPUX with HFS is an example of this. JRA.
3136                          */
3137                         if (no_acl_syscall_error(errno)) {
3138                                 *pacl_set_support = False;
3139                         }
3140
3141                         if (acl_group_override(conn, fsp->fsp_name)) {
3142                                 int sret;
3143
3144                                 DEBUG(5,("set_canon_ace_list: acl group "
3145                                          "control on and current user in file "
3146                                          "%s primary group.\n",
3147                                          fsp_str_dbg(fsp)));
3148
3149                                 become_root();
3150                                 sret = SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl);
3151                                 unbecome_root();
3152                                 if (sret == 0) {
3153                                         ret = True;
3154                                 }
3155                         }
3156
3157                         if (ret == False) {
3158                                 DEBUG(2,("set_canon_ace_list: "
3159                                          "sys_acl_set_file failed for file %s "
3160                                          "(%s).\n",
3161                                          fsp_str_dbg(fsp), strerror(errno)));
3162                                 goto fail;
3163                         }
3164                 }
3165         }
3166
3167         ret = True;
3168
3169   fail:
3170
3171         if (the_acl != NULL) {
3172                 TALLOC_FREE(the_acl);
3173         }
3174
3175         return ret;
3176 }
3177
3178 /****************************************************************************
3179  Find a particular canon_ace entry.
3180 ****************************************************************************/
3181
3182 static struct canon_ace *canon_ace_entry_for(struct canon_ace *list, SMB_ACL_TAG_T type, struct unixid *id)
3183 {
3184         while (list) {
3185                 if (list->type == type && ((type != SMB_ACL_USER && type != SMB_ACL_GROUP) ||
3186                                 (type == SMB_ACL_USER  && id && id->id == list->unix_ug.id) ||
3187                                 (type == SMB_ACL_GROUP && id && id->id == list->unix_ug.id)))
3188                         break;
3189                 list = list->next;
3190         }
3191         return list;
3192 }
3193
3194 /****************************************************************************
3195  
3196 ****************************************************************************/
3197
3198 SMB_ACL_T free_empty_sys_acl(connection_struct *conn, SMB_ACL_T the_acl)
3199 {
3200         SMB_ACL_ENTRY_T entry;
3201
3202         if (!the_acl)
3203                 return NULL;
3204         if (sys_acl_get_entry(the_acl, SMB_ACL_FIRST_ENTRY, &entry) != 1) {
3205                 TALLOC_FREE(the_acl);
3206                 return NULL;
3207         }
3208         return the_acl;
3209 }
3210
3211 /****************************************************************************
3212  Convert a canon_ace to a generic 3 element permission - if possible.
3213 ****************************************************************************/
3214
3215 #define MAP_PERM(p,mask,result) (((p) & (mask)) ? (result) : 0 )
3216
3217 static bool convert_canon_ace_to_posix_perms( files_struct *fsp, canon_ace *file_ace_list, mode_t *posix_perms)
3218 {
3219         int snum = SNUM(fsp->conn);
3220         size_t ace_count = count_canon_ace_list(file_ace_list);
3221         canon_ace *ace_p;
3222         canon_ace *owner_ace = NULL;
3223         canon_ace *group_ace = NULL;
3224         canon_ace *other_ace = NULL;
3225         mode_t and_bits;
3226         mode_t or_bits;
3227
3228         if (ace_count != 3) {
3229                 DEBUG(3,("convert_canon_ace_to_posix_perms: Too many ACE "
3230                          "entries for file %s to convert to posix perms.\n",
3231                          fsp_str_dbg(fsp)));
3232                 return False;
3233         }
3234
3235         for (ace_p = file_ace_list; ace_p; ace_p = ace_p->next) {
3236                 if (ace_p->owner_type == UID_ACE)
3237                         owner_ace = ace_p;
3238                 else if (ace_p->owner_type == GID_ACE)
3239                         group_ace = ace_p;
3240                 else if (ace_p->owner_type == WORLD_ACE)
3241                         other_ace = ace_p;
3242         }
3243
3244         if (!owner_ace || !group_ace || !other_ace) {
3245                 DEBUG(3,("convert_canon_ace_to_posix_perms: Can't get "
3246                          "standard entries for file %s.\n", fsp_str_dbg(fsp)));
3247                 return False;
3248         }
3249
3250         *posix_perms = (mode_t)0;
3251
3252         *posix_perms |= owner_ace->perms;
3253         *posix_perms |= MAP_PERM(group_ace->perms, S_IRUSR, S_IRGRP);
3254         *posix_perms |= MAP_PERM(group_ace->perms, S_IWUSR, S_IWGRP);
3255         *posix_perms |= MAP_PERM(group_ace->perms, S_IXUSR, S_IXGRP);
3256         *posix_perms |= MAP_PERM(other_ace->perms, S_IRUSR, S_IROTH);
3257         *posix_perms |= MAP_PERM(other_ace->perms, S_IWUSR, S_IWOTH);
3258         *posix_perms |= MAP_PERM(other_ace->perms, S_IXUSR, S_IXOTH);
3259
3260         /* The owner must have at least read access. */
3261
3262         *posix_perms |= S_IRUSR;
3263         if (fsp->is_directory)
3264                 *posix_perms |= (S_IWUSR|S_IXUSR);
3265
3266         /* If requested apply the masks. */
3267
3268         /* Get the initial bits to apply. */
3269
3270         if (fsp->is_directory) {
3271                 and_bits = lp_dir_mask(snum);
3272                 or_bits = lp_force_dir_mode(snum);
3273         } else {
3274                 and_bits = lp_create_mask(snum);
3275                 or_bits = lp_force_create_mode(snum);
3276         }
3277
3278         *posix_perms = (((*posix_perms) & and_bits)|or_bits);
3279
3280         DEBUG(10,("convert_canon_ace_to_posix_perms: converted u=%o,g=%o,w=%o "
3281                   "to perm=0%o for file %s.\n", (int)owner_ace->perms,
3282                   (int)group_ace->perms, (int)other_ace->perms,
3283                   (int)*posix_perms, fsp_str_dbg(fsp)));
3284
3285         return True;
3286 }
3287
3288 /****************************************************************************
3289   Incoming NT ACLs on a directory can be split into a default POSIX acl (CI|OI|IO) and
3290   a normal POSIX acl. Win2k needs these split acls re-merging into one ACL
3291   with CI|OI set so it is inherited and also applies to the directory.
3292   Based on code from "Jim McDonough" <jmcd@us.ibm.com>.
3293 ****************************************************************************/
3294
3295 static size_t merge_default_aces( struct security_ace *nt_ace_list, size_t num_aces)
3296 {
3297         size_t i, j;
3298
3299         for (i = 0; i < num_aces; i++) {
3300                 for (j = i+1; j < num_aces; j++) {
3301                         uint32 i_flags_ni = (nt_ace_list[i].flags & ~SEC_ACE_FLAG_INHERITED_ACE);
3302                         uint32 j_flags_ni = (nt_ace_list[j].flags & ~SEC_ACE_FLAG_INHERITED_ACE);
3303                         bool i_inh = (nt_ace_list[i].flags & SEC_ACE_FLAG_INHERITED_ACE) ? True : False;
3304                         bool j_inh = (nt_ace_list[j].flags & SEC_ACE_FLAG_INHERITED_ACE) ? True : False;
3305
3306                         /* We know the lower number ACE's are file entries. */
3307                         if ((nt_ace_list[i].type == nt_ace_list[j].type) &&
3308                                 (nt_ace_list[i].size == nt_ace_list[j].size) &&
3309                                 (nt_ace_list[i].access_mask == nt_ace_list[j].access_mask) &&
3310                                 dom_sid_equal(&nt_ace_list[i].trustee, &nt_ace_list[j].trustee) &&
3311                                 (i_inh == j_inh) &&
3312                                 (i_flags_ni == 0) &&
3313                                 (j_flags_ni == (SEC_ACE_FLAG_OBJECT_INHERIT|
3314                                                   SEC_ACE_FLAG_CONTAINER_INHERIT|
3315                                                   SEC_ACE_FLAG_INHERIT_ONLY))) {
3316                                 /*
3317                                  * W2K wants to have access allowed zero access ACE's
3318                                  * at the end of the list. If the mask is zero, merge
3319                                  * the non-inherited ACE onto the inherited ACE.
3320                                  */
3321
3322                                 if (nt_ace_list[i].access_mask == 0) {
3323                                         nt_ace_list[j].flags = SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
3324                                                                 (i_inh ? SEC_ACE_FLAG_INHERITED_ACE : 0);
3325                                         if (num_aces - i - 1 > 0)
3326                                                 memmove(&nt_ace_list[i], &nt_ace_list[i+1], (num_aces-i-1) *
3327                                                                 sizeof(struct security_ace));
3328
3329                                         DEBUG(10,("merge_default_aces: Merging zero access ACE %u onto ACE %u.\n",
3330                                                 (unsigned int)i, (unsigned int)j ));
3331                                 } else {
3332                                         /*
3333                                          * These are identical except for the flags.
3334                                          * Merge the inherited ACE onto the non-inherited ACE.
3335                                          */
3336
3337                                         nt_ace_list[i].flags = SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
3338                                                                 (i_inh ? SEC_ACE_FLAG_INHERITED_ACE : 0);
3339                                         if (num_aces - j - 1 > 0)
3340                                                 memmove(&nt_ace_list[j], &nt_ace_list[j+1], (num_aces-j-1) *
3341                                                                 sizeof(struct security_ace));
3342
3343                                         DEBUG(10,("merge_default_aces: Merging ACE %u onto ACE %u.\n",
3344                                                 (unsigned int)j, (unsigned int)i ));
3345                                 }
3346                                 num_aces--;
3347                                 break;
3348                         }
3349                 }
3350         }
3351
3352         return num_aces;
3353 }
3354
3355 /*
3356  * Add or Replace ACE entry.
3357  * In some cases we need to add a specific ACE for compatibility reasons.
3358  * When doing that we must make sure we are not actually creating a duplicate
3359  * entry. So we need to search whether an ACE entry already exist and eventually
3360  * replacce the access mask, or add a completely new entry if none was found.
3361  *
3362  * This function assumes the array has enough space to add a new entry without
3363  * any reallocation of memory.
3364  */
3365
3366 static void add_or_replace_ace(struct security_ace *nt_ace_list, size_t *num_aces,
3367                                 const struct dom_sid *sid, enum security_ace_type type,
3368                                 uint32_t mask, uint8_t flags)
3369 {
3370         int i;
3371
3372         /* first search for a duplicate */
3373         for (i = 0; i < *num_aces; i++) {
3374                 if (dom_sid_equal(&nt_ace_list[i].trustee, sid) &&
3375                     (nt_ace_list[i].flags == flags)) break;
3376         }
3377
3378         if (i < *num_aces) { /* found */
3379                 nt_ace_list[i].type = type;
3380                 nt_ace_list[i].access_mask = mask;
3381                 DEBUG(10, ("Replacing ACE %d with SID %s and flags %02x\n",
3382                            i, sid_string_dbg(sid), flags));
3383                 return;
3384         }
3385
3386         /* not found, append it */
3387         init_sec_ace(&nt_ace_list[(*num_aces)++], sid, type, mask, flags);
3388 }
3389
3390
3391 /****************************************************************************
3392  Reply to query a security descriptor from an fsp. If it succeeds it allocates
3393  the space for the return elements and returns the size needed to return the
3394  security descriptor. This should be the only external function needed for
3395  the UNIX style get ACL.
3396 ****************************************************************************/
3397
3398 static NTSTATUS posix_get_nt_acl_common(struct connection_struct *conn,
3399                                       const char *name,
3400                                       const SMB_STRUCT_STAT *sbuf,
3401                                       struct pai_val *pal,
3402                                       SMB_ACL_T posix_acl,
3403                                       SMB_ACL_T def_acl,
3404                                       uint32_t security_info,
3405                                       struct security_descriptor **ppdesc)
3406 {
3407         struct dom_sid owner_sid;
3408         struct dom_sid group_sid;
3409         size_t sd_size = 0;
3410         struct security_acl *psa = NULL;
3411         size_t num_acls = 0;
3412         size_t num_def_acls = 0;
3413         size_t num_aces = 0;
3414         canon_ace *file_ace = NULL;
3415         canon_ace *dir_ace = NULL;
3416         struct security_ace *nt_ace_list = NULL;
3417         size_t num_profile_acls = 0;
3418         struct dom_sid orig_owner_sid;
3419         struct security_descriptor *psd = NULL;
3420         int i;
3421
3422         /*
3423          * Get the owner, group and world SIDs.
3424          */
3425
3426         create_file_sids(sbuf, &owner_sid, &group_sid);
3427
3428         if (lp_profile_acls(SNUM(conn))) {
3429                 /* For WXP SP1 the owner must be administrators. */
3430                 sid_copy(&orig_owner_sid, &owner_sid);
3431                 sid_copy(&owner_sid, &global_sid_Builtin_Administrators);
3432                 sid_copy(&group_sid, &global_sid_Builtin_Users);
3433                 num_profile_acls = 3;
3434         }
3435
3436         if ((security_info & SECINFO_DACL) && !(security_info & SECINFO_PROTECTED_DACL)) {
3437
3438                 /*
3439                  * In the optimum case Creator Owner and Creator Group would be used for
3440                  * the ACL_USER_OBJ and ACL_GROUP_OBJ entries, respectively, but this
3441                  * would lead to usability problems under Windows: The Creator entries
3442                  * are only available in browse lists of directories and not for files;
3443                  * additionally the identity of the owning group couldn't be determined.
3444                  * We therefore use those identities only for Default ACLs. 
3445                  */
3446
3447                 /* Create the canon_ace lists. */
3448                 file_ace = canonicalise_acl(conn, name, posix_acl, sbuf,
3449                                             &owner_sid, &group_sid, pal,
3450                                             SMB_ACL_TYPE_ACCESS);
3451
3452                 /* We must have *some* ACLS. */
3453         
3454                 if (count_canon_ace_list(file_ace) == 0) {
3455                         DEBUG(0,("get_nt_acl : No ACLs on file (%s) !\n", name));
3456                         goto done;
3457                 }
3458
3459                 if (S_ISDIR(sbuf->st_ex_mode) && def_acl) {
3460                         dir_ace = canonicalise_acl(conn, name, def_acl,
3461                                                    sbuf,
3462                                                    &global_sid_Creator_Owner,
3463                                                    &global_sid_Creator_Group,
3464                                                    pal, SMB_ACL_TYPE_DEFAULT);
3465                 }
3466
3467                 /*
3468                  * Create the NT ACE list from the canonical ace lists.
3469                  */
3470
3471                 {
3472                         canon_ace *ace;
3473                         enum security_ace_type nt_acl_type;
3474
3475                         if (nt4_compatible_acls() && dir_ace) {
3476                                 /*
3477                                  * NT 4 chokes if an ACL contains an INHERIT_ONLY entry
3478                                  * but no non-INHERIT_ONLY entry for one SID. So we only
3479                                  * remove entries from the Access ACL if the
3480                                  * corresponding Default ACL entries have also been
3481                                  * removed. ACEs for CREATOR-OWNER and CREATOR-GROUP
3482                                  * are exceptions. We can do nothing
3483                                  * intelligent if the Default ACL contains entries that
3484                                  * are not also contained in the Access ACL, so this
3485                                  * case will still fail under NT 4.
3486                                  */
3487
3488                                 ace = canon_ace_entry_for(dir_ace, SMB_ACL_OTHER, NULL);
3489                                 if (ace && !ace->perms) {
3490                                         DLIST_REMOVE(dir_ace, ace);
3491                                         TALLOC_FREE(ace);
3492
3493                                         ace = canon_ace_entry_for(file_ace, SMB_ACL_OTHER, NULL);
3494                                         if (ace && !ace->perms) {
3495                                                 DLIST_REMOVE(file_ace, ace);
3496                                                 TALLOC_FREE(ace);
3497                                         }
3498                                 }
3499
3500                                 /*
3501                                  * WinNT doesn't usually have Creator Group
3502                                  * in browse lists, so we send this entry to
3503                                  * WinNT even if it contains no relevant
3504                                  * permissions. Once we can add
3505                                  * Creator Group to browse lists we can
3506                                  * re-enable this.
3507                                  */
3508
3509 #if 0
3510                                 ace = canon_ace_entry_for(dir_ace, SMB_ACL_GROUP_OBJ, NULL);
3511                                 if (ace && !ace->perms) {
3512                                         DLIST_REMOVE(dir_ace, ace);
3513                                         TALLOC_FREE(ace);
3514                                 }
3515 #endif
3516
3517                                 ace = canon_ace_entry_for(file_ace, SMB_ACL_GROUP_OBJ, NULL);
3518                                 if (ace && !ace->perms) {
3519                                         DLIST_REMOVE(file_ace, ace);
3520                                         TALLOC_FREE(ace);
3521                                 }
3522                         }
3523
3524                         num_acls = count_canon_ace_list(file_ace);
3525                         num_def_acls = count_canon_ace_list(dir_ace);
3526
3527                         /* Allocate the ace list. */
3528                         if ((nt_ace_list = talloc_array(talloc_tos(), struct security_ace,num_acls + num_profile_acls + num_def_acls)) == NULL) {
3529                                 DEBUG(0,("get_nt_acl: Unable to malloc space for nt_ace_list.\n"));
3530                                 goto done;
3531                         }
3532
3533                         memset(nt_ace_list, '\0', (num_acls + num_def_acls) * sizeof(struct security_ace) );
3534
3535                         /*
3536                          * Create the NT ACE list from the canonical ace lists.
3537                          */
3538
3539                         for (ace = file_ace; ace != NULL; ace = ace->next) {
3540                                 uint32_t acc = map_canon_ace_perms(SNUM(conn),
3541                                                 &nt_acl_type,
3542                                                 ace->perms,
3543                                                 S_ISDIR(sbuf->st_ex_mode));
3544                                 init_sec_ace(&nt_ace_list[num_aces++],
3545                                         &ace->trustee,
3546                                         nt_acl_type,
3547                                         acc,
3548                                         ace->ace_flags);
3549                         }
3550
3551                         /* The User must have access to a profile share - even
3552                          * if we can't map the SID. */
3553                         if (lp_profile_acls(SNUM(conn))) {
3554                                 add_or_replace_ace(nt_ace_list, &num_aces,
3555                                                    &global_sid_Builtin_Users,
3556                                                    SEC_ACE_TYPE_ACCESS_ALLOWED,
3557                                                    FILE_GENERIC_ALL, 0);
3558                         }
3559
3560                         for (ace = dir_ace; ace != NULL; ace = ace->next) {
3561                                 uint32_t acc = map_canon_ace_perms(SNUM(conn),
3562                                                 &nt_acl_type,
3563                                                 ace->perms,
3564                                                 S_ISDIR(sbuf->st_ex_mode));
3565                                 init_sec_ace(&nt_ace_list[num_aces++],
3566                                         &ace->trustee,
3567                                         nt_acl_type,
3568                                         acc,
3569                                         ace->ace_flags |
3570                                         SEC_ACE_FLAG_OBJECT_INHERIT|
3571                                         SEC_ACE_FLAG_CONTAINER_INHERIT|
3572                                         SEC_ACE_FLAG_INHERIT_ONLY);
3573                         }
3574
3575                         /* The User must have access to a profile share - even
3576                          * if we can't map the SID. */
3577                         if (lp_profile_acls(SNUM(conn))) {
3578                                 add_or_replace_ace(nt_ace_list, &num_aces,
3579                                                 &global_sid_Builtin_Users,
3580                                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
3581                                                 FILE_GENERIC_ALL,
3582                                                 SEC_ACE_FLAG_OBJECT_INHERIT |
3583                                                 SEC_ACE_FLAG_CONTAINER_INHERIT |
3584                                                 SEC_ACE_FLAG_INHERIT_ONLY);
3585                         }
3586
3587                         /*
3588                          * Merge POSIX default ACLs and normal ACLs into one NT ACE.
3589                          * Win2K needs this to get the inheritance correct when replacing ACLs
3590                          * on a directory tree. Based on work by Jim @ IBM.
3591                          */
3592
3593                         num_aces = merge_default_aces(nt_ace_list, num_aces);
3594
3595                         if (lp_profile_acls(SNUM(conn))) {
3596                                 for (i = 0; i < num_aces; i++) {
3597                                         if (dom_sid_equal(&nt_ace_list[i].trustee, &owner_sid)) {
3598                                                 add_or_replace_ace(nt_ace_list, &num_aces,
3599                                                                    &orig_owner_sid,
3600                                                                    nt_ace_list[i].type,
3601                                                                    nt_ace_list[i].access_mask,
3602                                                                    nt_ace_list[i].flags);
3603                                                 break;
3604                                         }
3605                                 }
3606                         }
3607                 }
3608
3609                 if (num_aces) {
3610                         if((psa = make_sec_acl( talloc_tos(), NT4_ACL_REVISION, num_aces, nt_ace_list)) == NULL) {
3611                                 DEBUG(0,("get_nt_acl: Unable to malloc space for acl.\n"));
3612                                 goto done;
3613                         }
3614                 }
3615         } /* security_info & SECINFO_DACL */
3616
3617         psd = make_standard_sec_desc( talloc_tos(),
3618                         (security_info & SECINFO_OWNER) ? &owner_sid : NULL,
3619                         (security_info & SECINFO_GROUP) ? &group_sid : NULL,
3620                         psa,
3621                         &sd_size);
3622
3623         if(!psd) {
3624                 DEBUG(0,("get_nt_acl: Unable to malloc space for security descriptor.\n"));
3625                 sd_size = 0;
3626                 goto done;
3627         }
3628
3629         /*
3630          * Windows 2000: The DACL_PROTECTED flag in the security
3631          * descriptor marks the ACL as non-inheriting, i.e., no
3632          * ACEs from higher level directories propagate to this
3633          * ACL. In the POSIX ACL model permissions are only
3634          * inherited at file create time, so ACLs never contain
3635          * any ACEs that are inherited dynamically. The DACL_PROTECTED
3636          * flag doesn't seem to bother Windows NT.
3637          * Always set this if map acl inherit is turned off.
3638          */
3639         if (pal == NULL || !lp_map_acl_inherit(SNUM(conn))) {
3640                 psd->type |= SEC_DESC_DACL_PROTECTED;
3641         } else {
3642                 psd->type |= pal->sd_type;
3643         }
3644
3645         if (psd->dacl) {
3646                 dacl_sort_into_canonical_order(psd->dacl->aces, (unsigned int)psd->dacl->num_aces);
3647         }
3648
3649         *ppdesc = psd;
3650
3651  done:
3652
3653         if (posix_acl) {
3654                 TALLOC_FREE(posix_acl);
3655         }
3656         if (def_acl) {
3657                 TALLOC_FREE(def_acl);
3658         }
3659         free_canon_ace_list(file_ace);
3660         free_canon_ace_list(dir_ace);
3661         free_inherited_info(pal);
3662         TALLOC_FREE(nt_ace_list);
3663
3664         return NT_STATUS_OK;
3665 }
3666
3667 NTSTATUS posix_fget_nt_acl(struct files_struct *fsp, uint32_t security_info,
3668                            struct security_descriptor **ppdesc)
3669 {
3670         SMB_STRUCT_STAT sbuf;
3671         SMB_ACL_T posix_acl = NULL;
3672         struct pai_val *pal;
3673
3674         *ppdesc = NULL;
3675
3676         DEBUG(10,("posix_fget_nt_acl: called for file %s\n",
3677                   fsp_str_dbg(fsp)));
3678
3679         /* can it happen that fsp_name == NULL ? */
3680         if (fsp->is_directory ||  fsp->fh->fd == -1) {
3681                 return posix_get_nt_acl(fsp->conn, fsp->fsp_name->base_name,
3682                                         security_info, ppdesc);
3683         }
3684
3685         /* Get the stat struct for the owner info. */
3686         if(SMB_VFS_FSTAT(fsp, &sbuf) != 0) {
3687                 return map_nt_error_from_unix(errno);
3688         }
3689
3690         /* Get the ACL from the fd. */
3691         posix_acl = SMB_VFS_SYS_ACL_GET_FD(fsp);
3692
3693         pal = fload_inherited_info(fsp);
3694
3695         return posix_get_nt_acl_common(fsp->conn, fsp->fsp_name->base_name,
3696                                        &sbuf, pal, posix_acl, NULL,
3697                                        security_info, ppdesc);
3698 }
3699
3700 NTSTATUS posix_get_nt_acl(struct connection_struct *conn, const char *name,
3701                           uint32_t security_info, struct security_descriptor **ppdesc)
3702 {
3703         SMB_ACL_T posix_acl = NULL;
3704         SMB_ACL_T def_acl = NULL;
3705         struct pai_val *pal;
3706         struct smb_filename smb_fname;
3707         int ret;
3708
3709         *ppdesc = NULL;
3710
3711         DEBUG(10,("posix_get_nt_acl: called for file %s\n", name ));
3712
3713         ZERO_STRUCT(smb_fname);
3714         smb_fname.base_name = discard_const_p(char, name);
3715
3716         /* Get the stat struct for the owner info. */
3717         if (lp_posix_pathnames()) {
3718                 ret = SMB_VFS_LSTAT(conn, &smb_fname);
3719         } else {
3720                 ret = SMB_VFS_STAT(conn, &smb_fname);
3721         }
3722
3723         if (ret == -1) {
3724                 return map_nt_error_from_unix(errno);
3725         }
3726
3727         /* Get the ACL from the path. */
3728         posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, name, SMB_ACL_TYPE_ACCESS);
3729
3730         /* If it's a directory get the default POSIX ACL. */
3731         if(S_ISDIR(smb_fname.st.st_ex_mode)) {
3732                 def_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, name, SMB_ACL_TYPE_DEFAULT);
3733                 def_acl = free_empty_sys_acl(conn, def_acl);
3734         }
3735
3736         pal = load_inherited_info(conn, name);
3737
3738         return posix_get_nt_acl_common(conn, name, &smb_fname.st, pal,
3739                                        posix_acl, def_acl, security_info,
3740                                        ppdesc);
3741 }
3742
3743 /****************************************************************************
3744  Try to chown a file. We will be able to chown it under the following conditions.
3745
3746   1) If we have root privileges, then it will just work.
3747   2) If we have SeRestorePrivilege we can change the user + group to any other user. 
3748   3) If we have SeTakeOwnershipPrivilege we can change the user to the current user.
3749   4) If we have write permission to the file and dos_filemodes is set
3750      then allow chown to the currently authenticated user.
3751 ****************************************************************************/
3752
3753 NTSTATUS try_chown(files_struct *fsp, uid_t uid, gid_t gid)
3754 {
3755         NTSTATUS status;
3756
3757         if(!CAN_WRITE(fsp->conn)) {
3758                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
3759         }
3760
3761         /* Case (1). */
3762         status = vfs_chown_fsp(fsp, uid, gid);
3763         if (NT_STATUS_IS_OK(status)) {
3764                 return status;
3765         }
3766
3767         /* Case (2) / (3) */
3768         if (lp_enable_privileges()) {
3769                 bool has_take_ownership_priv = security_token_has_privilege(
3770                                                 get_current_nttok(fsp->conn),
3771                                                 SEC_PRIV_TAKE_OWNERSHIP);
3772                 bool has_restore_priv = security_token_has_privilege(
3773                                                 get_current_nttok(fsp->conn),
3774                                                 SEC_PRIV_RESTORE);
3775
3776                 if (has_restore_priv) {
3777                         ; /* Case (2) */
3778                 } else if (has_take_ownership_priv) {
3779                         /* Case (3) */
3780                         if (uid == get_current_uid(fsp->conn)) {
3781                                 gid = (gid_t)-1;
3782                         } else {
3783                                 has_take_ownership_priv = false;
3784                         }
3785                 }
3786
3787                 if (has_take_ownership_priv || has_restore_priv) {
3788                         become_root();
3789                         status = vfs_chown_fsp(fsp, uid, gid);
3790                         unbecome_root();
3791                         return status;
3792                 }
3793         }
3794
3795         /* Case (4). */
3796         if (!lp_dos_filemode(SNUM(fsp->conn))) {
3797                 return NT_STATUS_ACCESS_DENIED;
3798         }
3799
3800         /* only allow chown to the current user. This is more secure,
3801            and also copes with the case where the SID in a take ownership ACL is
3802            a local SID on the users workstation
3803         */
3804         if (uid != get_current_uid(fsp->conn)) {
3805                 return NT_STATUS_ACCESS_DENIED;
3806         }
3807
3808         become_root();
3809         /* Keep the current file gid the same. */
3810         status = vfs_chown_fsp(fsp, uid, (gid_t)-1);
3811         unbecome_root();
3812
3813         return status;
3814 }
3815
3816 #if 0
3817 /* Disable this - prevents ACL inheritance from the ACL editor. JRA. */
3818
3819 /****************************************************************************
3820  Take care of parent ACL inheritance.
3821 ****************************************************************************/
3822
3823 NTSTATUS append_parent_acl(files_struct *fsp,
3824                                 const struct security_descriptor *pcsd,
3825                                 struct security_descriptor **pp_new_sd)
3826 {
3827         struct smb_filename *smb_dname = NULL;
3828         struct security_descriptor *parent_sd = NULL;
3829         files_struct *parent_fsp = NULL;
3830         TALLOC_CTX *mem_ctx = talloc_tos();
3831         char *parent_name = NULL;
3832         struct security_ace *new_ace = NULL;
3833         unsigned int num_aces = pcsd->dacl->num_aces;
3834         NTSTATUS status;
3835         int info;
3836         unsigned int i, j;
3837         struct security_descriptor *psd = dup_sec_desc(talloc_tos(), pcsd);
3838         bool is_dacl_protected = (pcsd->type & SEC_DESC_DACL_PROTECTED);
3839
3840         if (psd == NULL) {
3841                 return NT_STATUS_NO_MEMORY;
3842         }
3843
3844         if (!parent_dirname(mem_ctx, fsp->fsp_name->base_name, &parent_name,
3845                             NULL)) {
3846                 return NT_STATUS_NO_MEMORY;
3847         }
3848
3849         status = create_synthetic_smb_fname(mem_ctx, parent_name, NULL, NULL,
3850                                             &smb_dname);
3851         if (!NT_STATUS_IS_OK(status)) {
3852                 goto fail;
3853         }
3854
3855         status = SMB_VFS_CREATE_FILE(
3856                 fsp->conn,                              /* conn */
3857                 NULL,                                   /* req */
3858                 0,                                      /* root_dir_fid */
3859                 smb_dname,                              /* fname */
3860                 FILE_READ_ATTRIBUTES,                   /* access_mask */
3861                 FILE_SHARE_NONE,                        /* share_access */
3862                 FILE_OPEN,                              /* create_disposition*/
3863                 FILE_DIRECTORY_FILE,                    /* create_options */
3864                 0,                                      /* file_attributes */
3865                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
3866                 0,                                      /* allocation_size */
3867                 NULL,                                   /* sd */
3868                 NULL,                                   /* ea_list */
3869                 &parent_fsp,                            /* result */
3870                 &info);                                 /* pinfo */
3871
3872         if (!NT_STATUS_IS_OK(status)) {
3873                 TALLOC_FREE(smb_dname);
3874                 return status;
3875         }
3876
3877         status = SMB_VFS_GET_NT_ACL(parent_fsp->conn, smb_dname->base_name,
3878                                     SECINFO_DACL, &parent_sd );
3879
3880         close_file(NULL, parent_fsp, NORMAL_CLOSE);
3881         TALLOC_FREE(smb_dname);
3882
3883         if (!NT_STATUS_IS_OK(status)) {
3884                 return status;
3885         }
3886
3887         /*
3888          * Make room for potentially all the ACLs from
3889          * the parent. We used to add the ugw triple here,
3890          * as we knew we were dealing with POSIX ACLs.
3891          * We no longer need to do so as we can guarentee
3892          * that a default ACL from the parent directory will
3893          * be well formed for POSIX ACLs if it came from a
3894          * POSIX ACL source, and if we're not writing to a
3895          * POSIX ACL sink then we don't care if it's not well
3896          * formed. JRA.
3897          */
3898
3899         num_aces += parent_sd->dacl->num_aces;
3900
3901         if((new_ace = talloc_zero_array(mem_ctx, struct security_ace,
3902                                         num_aces)) == NULL) {
3903                 return NT_STATUS_NO_MEMORY;
3904         }
3905
3906         /* Start by copying in all the given ACE entries. */
3907         for (i = 0; i < psd->dacl->num_aces; i++) {
3908                 sec_ace_copy(&new_ace[i], &psd->dacl->aces[i]);
3909         }
3910
3911         /*
3912          * Note that we're ignoring "inherit permissions" here
3913          * as that really only applies to newly created files. JRA.
3914          */
3915
3916         /* Finally append any inherited ACEs. */
3917         for (j = 0; j < parent_sd->dacl->num_aces; j++) {
3918                 struct security_ace *se = &parent_sd->dacl->aces[j];
3919
3920                 if (fsp->is_directory) {
3921                         if (!(se->flags & SEC_ACE_FLAG_CONTAINER_INHERIT)) {
3922                                 /* Doesn't apply to a directory - ignore. */
3923                                 DEBUG(10,("append_parent_acl: directory %s "
3924                                         "ignoring non container "
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                 } else {
3934                         if (!(se->flags & SEC_ACE_FLAG_OBJECT_INHERIT)) {
3935                                 /* Doesn't apply to a file - ignore. */
3936                                 DEBUG(10,("append_parent_acl: file %s "
3937                                         "ignoring non object "
3938                                         "inherit flags %u on ACE with sid %s "
3939                                         "from parent %s\n",
3940                                         fsp_str_dbg(fsp),
3941                                         (unsigned int)se->flags,
3942                                         sid_string_dbg(&se->trustee),
3943                                         parent_name));
3944                                 continue;
3945                         }
3946                 }
3947
3948                 if (is_dacl_protected) {
3949                         /* If the DACL is protected it means we must
3950                          * not overwrite an existing ACE entry with the
3951                          * same SID. This is order N^2. Ouch :-(. JRA. */
3952                         unsigned int k;
3953                         for (k = 0; k < psd->dacl->num_aces; k++) {
3954                                 if (dom_sid_equal(&psd->dacl->aces[k].trustee,
3955                                                 &se->trustee)) {
3956                                         break;
3957                                 }
3958                         }
3959                         if (k < psd->dacl->num_aces) {
3960                                 /* SID matched. Ignore. */
3961                                 DEBUG(10,("append_parent_acl: path %s "
3962                                         "ignoring ACE with protected sid %s "
3963                                         "from parent %s\n",
3964                                         fsp_str_dbg(fsp),
3965                                         sid_string_dbg(&se->trustee),
3966                                         parent_name));
3967                                 continue;
3968                         }
3969                 }
3970
3971                 sec_ace_copy(&new_ace[i], se);
3972                 if (se->flags & SEC_ACE_FLAG_NO_PROPAGATE_INHERIT) {
3973                         new_ace[i].flags &= ~(SEC_ACE_FLAG_VALID_INHERIT);
3974                 }
3975                 new_ace[i].flags |= SEC_ACE_FLAG_INHERITED_ACE;
3976
3977                 if (fsp->is_directory) {
3978                         /*
3979                          * Strip off any inherit only. It's applied.
3980                          */
3981                         new_ace[i].flags &= ~(SEC_ACE_FLAG_INHERIT_ONLY);
3982                         if (se->flags & SEC_ACE_FLAG_NO_PROPAGATE_INHERIT) {
3983                                 /* No further inheritance. */
3984                                 new_ace[i].flags &=
3985                                         ~(SEC_ACE_FLAG_CONTAINER_INHERIT|
3986                                         SEC_ACE_FLAG_OBJECT_INHERIT);
3987                         }
3988                 } else {
3989                         /*
3990                          * Strip off any container or inherit
3991                          * flags, they can't apply to objects.
3992                          */
3993                         new_ace[i].flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|
3994                                                 SEC_ACE_FLAG_INHERIT_ONLY|
3995                                                 SEC_ACE_FLAG_NO_PROPAGATE_INHERIT);
3996                 }
3997                 i++;
3998
3999                 DEBUG(10,("append_parent_acl: path %s "
4000                         "inheriting ACE with sid %s "
4001                         "from parent %s\n",
4002                         fsp_str_dbg(fsp),
4003                         sid_string_dbg(&se->trustee),
4004                         parent_name));
4005         }
4006
4007         psd->dacl->aces = new_ace;
4008         psd->dacl->num_aces = i;
4009         psd->type &= ~(SEC_DESC_DACL_AUTO_INHERITED|
4010                          SEC_DESC_DACL_AUTO_INHERIT_REQ);
4011
4012         *pp_new_sd = psd;
4013         return status;
4014 }
4015 #endif
4016
4017 /****************************************************************************
4018  Reply to set a security descriptor on an fsp. security_info_sent is the
4019  description of the following NT ACL.
4020  This should be the only external function needed for the UNIX style set ACL.
4021  We make a copy of psd_orig as internal functions modify the elements inside
4022  it, even though it's a const pointer.
4023 ****************************************************************************/
4024
4025 NTSTATUS set_nt_acl(files_struct *fsp, uint32 security_info_sent, const struct security_descriptor *psd_orig)
4026 {
4027         connection_struct *conn = fsp->conn;
4028         uid_t user = (uid_t)-1;
4029         gid_t grp = (gid_t)-1;
4030         struct dom_sid file_owner_sid;
4031         struct dom_sid file_grp_sid;
4032         canon_ace *file_ace_list = NULL;
4033         canon_ace *dir_ace_list = NULL;
4034         bool acl_perms = False;
4035         mode_t orig_mode = (mode_t)0;
4036         NTSTATUS status;
4037         bool set_acl_as_root = false;
4038         bool acl_set_support = false;
4039         bool ret = false;
4040         struct security_descriptor *psd = NULL;
4041
4042         DEBUG(10,("set_nt_acl: called for file %s\n",
4043                   fsp_str_dbg(fsp)));
4044
4045         if (!CAN_WRITE(conn)) {
4046                 DEBUG(10,("set acl rejected on read-only share\n"));
4047                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
4048         }
4049
4050         if (!psd_orig) {
4051                 return NT_STATUS_INVALID_PARAMETER;
4052         }
4053
4054         psd = dup_sec_desc(talloc_tos(), psd_orig);
4055         if (!psd) {
4056                 return NT_STATUS_NO_MEMORY;
4057         }
4058
4059         /*
4060          * Get the current state of the file.
4061          */
4062
4063         status = vfs_stat_fsp(fsp);
4064         if (!NT_STATUS_IS_OK(status)) {
4065                 return status;
4066         }
4067
4068         /* Save the original element we check against. */
4069         orig_mode = fsp->fsp_name->st.st_ex_mode;
4070
4071         /*
4072          * Unpack the user/group/world id's.
4073          */
4074
4075         /* POSIX can't cope with missing owner/group. */
4076         if ((security_info_sent & SECINFO_OWNER) && (psd->owner_sid == NULL)) {
4077                 security_info_sent &= ~SECINFO_OWNER;
4078         }
4079         if ((security_info_sent & SECINFO_GROUP) && (psd->group_sid == NULL)) {
4080                 security_info_sent &= ~SECINFO_GROUP;
4081         }
4082
4083         status = unpack_nt_owners( conn, &user, &grp, security_info_sent, psd);
4084         if (!NT_STATUS_IS_OK(status)) {
4085                 return status;
4086         }
4087
4088         /*
4089          * Do we need to chown ? If so this must be done first as the incoming
4090          * CREATOR_OWNER acl will be relative to the *new* owner, not the old.
4091          * Noticed by Simo.
4092          */
4093
4094         if (((user != (uid_t)-1) && (fsp->fsp_name->st.st_ex_uid != user)) ||
4095             (( grp != (gid_t)-1) && (fsp->fsp_name->st.st_ex_gid != grp))) {
4096
4097                 DEBUG(3,("set_nt_acl: chown %s. uid = %u, gid = %u.\n",
4098                          fsp_str_dbg(fsp), (unsigned int)user,
4099                          (unsigned int)grp));
4100
4101                 status = try_chown(fsp, user, grp);
4102                 if(!NT_STATUS_IS_OK(status)) {
4103                         DEBUG(3,("set_nt_acl: chown %s, %u, %u failed. Error "
4104                                 "= %s.\n", fsp_str_dbg(fsp),
4105                                 (unsigned int)user,
4106                                 (unsigned int)grp,
4107                                 nt_errstr(status)));
4108                         return status;
4109                 }
4110
4111                 /*
4112                  * Recheck the current state of the file, which may have changed.
4113                  * (suid/sgid bits, for instance)
4114                  */
4115
4116                 status = vfs_stat_fsp(fsp);
4117                 if (!NT_STATUS_IS_OK(status)) {
4118                         return status;
4119                 }
4120
4121                 /* Save the original element we check against. */
4122                 orig_mode = fsp->fsp_name->st.st_ex_mode;
4123
4124                 /* If we successfully chowned, we know we must
4125                  * be able to set the acl, so do it as root.
4126                  */
4127                 set_acl_as_root = true;
4128         }
4129
4130         create_file_sids(&fsp->fsp_name->st, &file_owner_sid, &file_grp_sid);
4131
4132         if((security_info_sent & SECINFO_DACL) &&
4133                         (psd->type & SEC_DESC_DACL_PRESENT) &&
4134                         (psd->dacl == NULL)) {
4135                 struct security_ace ace[3];
4136
4137                 /* We can't have NULL DACL in POSIX.
4138                    Use owner/group/Everyone -> full access. */
4139
4140                 init_sec_ace(&ace[0],
4141                                 &file_owner_sid,
4142                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
4143                                 GENERIC_ALL_ACCESS,
4144                                 0);
4145                 init_sec_ace(&ace[1],
4146                                 &file_grp_sid,
4147                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
4148                                 GENERIC_ALL_ACCESS,
4149                                 0);
4150                 init_sec_ace(&ace[2],
4151                                 &global_sid_World,
4152                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
4153                                 GENERIC_ALL_ACCESS,
4154                                 0);
4155                 psd->dacl = make_sec_acl(talloc_tos(),
4156                                         NT4_ACL_REVISION,
4157                                         3,
4158                                         ace);
4159                 if (psd->dacl == NULL) {
4160                         return NT_STATUS_NO_MEMORY;
4161                 }
4162                 security_acl_map_generic(psd->dacl, &file_generic_mapping);
4163         }
4164
4165         acl_perms = unpack_canon_ace(fsp, &fsp->fsp_name->st, &file_owner_sid,
4166                                      &file_grp_sid, &file_ace_list,
4167                                      &dir_ace_list, security_info_sent, psd);
4168
4169         /* Ignore W2K traverse DACL set. */
4170         if (!file_ace_list && !dir_ace_list) {
4171                 return NT_STATUS_OK;
4172         }
4173
4174         if (!acl_perms) {
4175                 DEBUG(3,("set_nt_acl: cannot set permissions\n"));
4176                 free_canon_ace_list(file_ace_list);
4177                 free_canon_ace_list(dir_ace_list);
4178                 return NT_STATUS_ACCESS_DENIED;
4179         }
4180
4181         /*
4182          * Only change security if we got a DACL.
4183          */
4184
4185         if(!(security_info_sent & SECINFO_DACL) || (psd->dacl == NULL)) {
4186                 free_canon_ace_list(file_ace_list);
4187                 free_canon_ace_list(dir_ace_list);
4188                 return NT_STATUS_OK;
4189         }
4190
4191         /*
4192          * Try using the POSIX ACL set first. Fall back to chmod if
4193          * we have no ACL support on this filesystem.
4194          */
4195
4196         if (acl_perms && file_ace_list) {
4197                 if (set_acl_as_root) {
4198                         become_root();
4199                 }
4200                 ret = set_canon_ace_list(fsp, file_ace_list, false,
4201                                          &fsp->fsp_name->st, &acl_set_support);
4202                 if (set_acl_as_root) {
4203                         unbecome_root();
4204                 }
4205                 if (acl_set_support && ret == false) {
4206                         DEBUG(3,("set_nt_acl: failed to set file acl on file "
4207                                  "%s (%s).\n", fsp_str_dbg(fsp),
4208                                  strerror(errno)));
4209                         free_canon_ace_list(file_ace_list);
4210                         free_canon_ace_list(dir_ace_list);
4211                         return map_nt_error_from_unix(errno);
4212                 }
4213         }
4214
4215         if (acl_perms && acl_set_support && fsp->is_directory) {
4216                 if (dir_ace_list) {
4217                         if (set_acl_as_root) {
4218                                 become_root();
4219                         }
4220                         ret = set_canon_ace_list(fsp, dir_ace_list, true,
4221                                                  &fsp->fsp_name->st,
4222                                                  &acl_set_support);
4223                         if (set_acl_as_root) {
4224                                 unbecome_root();
4225                         }
4226                         if (ret == false) {
4227                                 DEBUG(3,("set_nt_acl: failed to set default "
4228                                          "acl on directory %s (%s).\n",
4229                                          fsp_str_dbg(fsp), strerror(errno)));
4230                                 free_canon_ace_list(file_ace_list);
4231                                 free_canon_ace_list(dir_ace_list);
4232                                 return map_nt_error_from_unix(errno);
4233                         }
4234                 } else {
4235                         int sret = -1;
4236
4237                         /*
4238                          * No default ACL - delete one if it exists.
4239                          */
4240
4241                         if (set_acl_as_root) {
4242                                 become_root();
4243                         }
4244                         sret = SMB_VFS_SYS_ACL_DELETE_DEF_FILE(conn,
4245                             fsp->fsp_name->base_name);
4246                         if (set_acl_as_root) {
4247                                 unbecome_root();
4248                         }
4249                         if (sret == -1) {
4250                                 if (acl_group_override(conn, fsp->fsp_name)) {
4251                                         DEBUG(5,("set_nt_acl: acl group "
4252                                                  "control on and current user "
4253                                                  "in file %s primary group. "
4254                                                  "Override delete_def_acl\n",
4255                                                  fsp_str_dbg(fsp)));
4256
4257                                         become_root();
4258                                         sret =
4259                                             SMB_VFS_SYS_ACL_DELETE_DEF_FILE(
4260                                                     conn,
4261                                                     fsp->fsp_name->base_name);
4262                                         unbecome_root();
4263                                 }
4264
4265                                 if (sret == -1) {
4266                                         DEBUG(3,("set_nt_acl: sys_acl_delete_def_file failed (%s)\n", strerror(errno)));
4267                                         free_canon_ace_list(file_ace_list);
4268                                         free_canon_ace_list(dir_ace_list);
4269                                         return map_nt_error_from_unix(errno);
4270                                 }
4271                         }
4272                 }
4273         }
4274
4275         if (acl_set_support) {
4276                 if (set_acl_as_root) {
4277                         become_root();
4278                 }
4279                 store_inheritance_attributes(fsp,
4280                                 file_ace_list,
4281                                 dir_ace_list,
4282                                 psd->type);
4283                 if (set_acl_as_root) {
4284                         unbecome_root();
4285                 }
4286         }
4287
4288         /*
4289          * If we cannot set using POSIX ACLs we fall back to checking if we need to chmod.
4290          */
4291
4292         if(!acl_set_support && acl_perms) {
4293                 mode_t posix_perms;
4294
4295                 if (!convert_canon_ace_to_posix_perms( fsp, file_ace_list, &posix_perms)) {
4296                         free_canon_ace_list(file_ace_list);
4297                         free_canon_ace_list(dir_ace_list);
4298                         DEBUG(3,("set_nt_acl: failed to convert file acl to "
4299                                  "posix permissions for file %s.\n",
4300                                  fsp_str_dbg(fsp)));
4301                         return NT_STATUS_ACCESS_DENIED;
4302                 }
4303
4304                 if (orig_mode != posix_perms) {
4305                         int sret = -1;
4306
4307                         DEBUG(3,("set_nt_acl: chmod %s. perms = 0%o.\n",
4308                                  fsp_str_dbg(fsp), (unsigned int)posix_perms));
4309
4310                         if (set_acl_as_root) {
4311                                 become_root();
4312                         }
4313                         sret = SMB_VFS_CHMOD(conn, fsp->fsp_name->base_name,
4314                                              posix_perms);
4315                         if (set_acl_as_root) {
4316                                 unbecome_root();
4317                         }
4318                         if(sret == -1) {
4319                                 if (acl_group_override(conn, fsp->fsp_name)) {
4320                                         DEBUG(5,("set_nt_acl: acl group "
4321                                                  "control on and current user "
4322                                                  "in file %s primary group. "
4323                                                  "Override chmod\n",
4324                                                  fsp_str_dbg(fsp)));
4325
4326                                         become_root();
4327                                         sret = SMB_VFS_CHMOD(conn,
4328                                             fsp->fsp_name->base_name,
4329                                             posix_perms);
4330                                         unbecome_root();
4331                                 }
4332
4333                                 if (sret == -1) {
4334                                         DEBUG(3,("set_nt_acl: chmod %s, 0%o "
4335                                                  "failed. Error = %s.\n",
4336                                                  fsp_str_dbg(fsp),
4337                                                  (unsigned int)posix_perms,
4338                                                  strerror(errno)));
4339                                         free_canon_ace_list(file_ace_list);
4340                                         free_canon_ace_list(dir_ace_list);
4341                                         return map_nt_error_from_unix(errno);
4342                                 }
4343                         }
4344                 }
4345         }
4346
4347         free_canon_ace_list(file_ace_list);
4348         free_canon_ace_list(dir_ace_list);
4349
4350         /* Ensure the stat struct in the fsp is correct. */
4351         status = vfs_stat_fsp(fsp);
4352
4353         return NT_STATUS_OK;
4354 }
4355
4356 /****************************************************************************
4357  Get the actual group bits stored on a file with an ACL. Has no effect if
4358  the file has no ACL. Needed in dosmode code where the stat() will return
4359  the mask bits, not the real group bits, for a file with an ACL.
4360 ****************************************************************************/
4361
4362 int get_acl_group_bits( connection_struct *conn, const char *fname, mode_t *mode )
4363 {
4364         int entry_id = SMB_ACL_FIRST_ENTRY;
4365         SMB_ACL_ENTRY_T entry;
4366         SMB_ACL_T posix_acl;
4367         int result = -1;
4368
4369         posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, fname, SMB_ACL_TYPE_ACCESS);
4370         if (posix_acl == (SMB_ACL_T)NULL)
4371                 return -1;
4372
4373         while (sys_acl_get_entry(posix_acl, entry_id, &entry) == 1) {
4374                 SMB_ACL_TAG_T tagtype;
4375                 SMB_ACL_PERMSET_T permset;
4376
4377                 entry_id = SMB_ACL_NEXT_ENTRY;
4378
4379                 if (sys_acl_get_tag_type(entry, &tagtype) ==-1)
4380                         break;
4381
4382                 if (tagtype == SMB_ACL_GROUP_OBJ) {
4383                         if (sys_acl_get_permset(entry, &permset) == -1) {
4384                                 break;
4385                         } else {
4386                                 *mode &= ~(S_IRGRP|S_IWGRP|S_IXGRP);
4387                                 *mode |= (sys_acl_get_perm(permset, SMB_ACL_READ) ? S_IRGRP : 0);
4388                                 *mode |= (sys_acl_get_perm(permset, SMB_ACL_WRITE) ? S_IWGRP : 0);
4389                                 *mode |= (sys_acl_get_perm(permset, SMB_ACL_EXECUTE) ? S_IXGRP : 0);
4390                                 result = 0;
4391                                 break;
4392                         }
4393                 }
4394         }
4395         TALLOC_FREE(posix_acl);
4396         return result;
4397 }
4398
4399 /****************************************************************************
4400  Do a chmod by setting the ACL USER_OBJ, GROUP_OBJ and OTHER bits in an ACL
4401  and set the mask to rwx. Needed to preserve complex ACLs set by NT.
4402 ****************************************************************************/
4403
4404 static int chmod_acl_internals( connection_struct *conn, SMB_ACL_T posix_acl, mode_t mode)
4405 {
4406         int entry_id = SMB_ACL_FIRST_ENTRY;
4407         SMB_ACL_ENTRY_T entry;
4408         int num_entries = 0;
4409
4410         while ( sys_acl_get_entry(posix_acl, entry_id, &entry) == 1) {
4411                 SMB_ACL_TAG_T tagtype;
4412                 SMB_ACL_PERMSET_T permset;
4413                 mode_t perms;
4414
4415                 entry_id = SMB_ACL_NEXT_ENTRY;
4416
4417                 if (sys_acl_get_tag_type(entry, &tagtype) == -1)
4418                         return -1;
4419
4420                 if (sys_acl_get_permset(entry, &permset) == -1)
4421                         return -1;
4422
4423                 num_entries++;
4424
4425                 switch(tagtype) {
4426                         case SMB_ACL_USER_OBJ:
4427                                 perms = unix_perms_to_acl_perms(mode, S_IRUSR, S_IWUSR, S_IXUSR);
4428                                 break;
4429                         case SMB_ACL_GROUP_OBJ:
4430                                 perms = unix_perms_to_acl_perms(mode, S_IRGRP, S_IWGRP, S_IXGRP);
4431                                 break;
4432                         case SMB_ACL_MASK:
4433                                 /*
4434                                  * FIXME: The ACL_MASK entry permissions should really be set to
4435                                  * the union of the permissions of all ACL_USER,
4436                                  * ACL_GROUP_OBJ, and ACL_GROUP entries. That's what
4437                                  * acl_calc_mask() does, but Samba ACLs doesn't provide it.
4438                                  */
4439                                 perms = S_IRUSR|S_IWUSR|S_IXUSR;
4440                                 break;
4441                         case SMB_ACL_OTHER:
4442                                 perms = unix_perms_to_acl_perms(mode, S_IROTH, S_IWOTH, S_IXOTH);
4443                                 break;
4444                         default:
4445                                 continue;
4446                 }
4447
4448                 if (map_acl_perms_to_permset(conn, perms, &permset) == -1)
4449                         return -1;
4450
4451                 if (sys_acl_set_permset(entry, permset) == -1)
4452                         return -1;
4453         }
4454
4455         /*
4456          * If this is a simple 3 element ACL or no elements then it's a standard
4457          * UNIX permission set. Just use chmod...       
4458          */
4459
4460         if ((num_entries == 3) || (num_entries == 0))
4461                 return -1;
4462
4463         return 0;
4464 }
4465
4466 /****************************************************************************
4467  Get the access ACL of FROM, do a chmod by setting the ACL USER_OBJ,
4468  GROUP_OBJ and OTHER bits in an ACL and set the mask to rwx. Set the
4469  resulting ACL on TO.  Note that name is in UNIX character set.
4470 ****************************************************************************/
4471
4472 static int copy_access_posix_acl(connection_struct *conn, const char *from, const char *to, mode_t mode)
4473 {
4474         SMB_ACL_T posix_acl = NULL;
4475         int ret = -1;
4476
4477         if ((posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, from, SMB_ACL_TYPE_ACCESS)) == NULL)
4478                 return -1;
4479
4480         if ((ret = chmod_acl_internals(conn, posix_acl, mode)) == -1)
4481                 goto done;
4482
4483         ret = SMB_VFS_SYS_ACL_SET_FILE(conn, to, SMB_ACL_TYPE_ACCESS, posix_acl);
4484
4485  done:
4486
4487         TALLOC_FREE(posix_acl);
4488         return ret;
4489 }
4490
4491 /****************************************************************************
4492  Do a chmod by setting the ACL USER_OBJ, GROUP_OBJ and OTHER bits in an ACL
4493  and set the mask to rwx. Needed to preserve complex ACLs set by NT.
4494  Note that name is in UNIX character set.
4495 ****************************************************************************/
4496
4497 int chmod_acl(connection_struct *conn, const char *name, mode_t mode)
4498 {
4499         return copy_access_posix_acl(conn, name, name, mode);
4500 }
4501
4502 /****************************************************************************
4503  Check for an existing default POSIX ACL on a directory.
4504 ****************************************************************************/
4505
4506 static bool directory_has_default_posix_acl(connection_struct *conn, const char *fname)
4507 {
4508         SMB_ACL_T def_acl = SMB_VFS_SYS_ACL_GET_FILE( conn, fname, SMB_ACL_TYPE_DEFAULT);
4509         bool has_acl = False;
4510         SMB_ACL_ENTRY_T entry;
4511
4512         if (def_acl != NULL && (sys_acl_get_entry(def_acl, SMB_ACL_FIRST_ENTRY, &entry) == 1)) {
4513                 has_acl = True;
4514         }
4515
4516         if (def_acl) {
4517                 TALLOC_FREE(def_acl);
4518         }
4519         return has_acl;
4520 }
4521
4522 /****************************************************************************
4523  If the parent directory has no default ACL but it does have an Access ACL,
4524  inherit this Access ACL to file name.
4525 ****************************************************************************/
4526
4527 int inherit_access_posix_acl(connection_struct *conn, const char *inherit_from_dir,
4528                        const char *name, mode_t mode)
4529 {
4530         if (directory_has_default_posix_acl(conn, inherit_from_dir))
4531                 return 0;
4532
4533         return copy_access_posix_acl(conn, inherit_from_dir, name, mode);
4534 }
4535
4536 /****************************************************************************
4537  Do an fchmod by setting the ACL USER_OBJ, GROUP_OBJ and OTHER bits in an ACL
4538  and set the mask to rwx. Needed to preserve complex ACLs set by NT.
4539 ****************************************************************************/
4540
4541 int fchmod_acl(files_struct *fsp, mode_t mode)
4542 {
4543         connection_struct *conn = fsp->conn;
4544         SMB_ACL_T posix_acl = NULL;
4545         int ret = -1;
4546
4547         if ((posix_acl = SMB_VFS_SYS_ACL_GET_FD(fsp)) == NULL)
4548                 return -1;
4549
4550         if ((ret = chmod_acl_internals(conn, posix_acl, mode)) == -1)
4551                 goto done;
4552
4553         ret = SMB_VFS_SYS_ACL_SET_FD(fsp, posix_acl);
4554
4555   done:
4556
4557         TALLOC_FREE(posix_acl);
4558         return ret;
4559 }
4560
4561 /****************************************************************************
4562  Map from wire type to permset.
4563 ****************************************************************************/
4564
4565 static bool unix_ex_wire_to_permset(connection_struct *conn, unsigned char wire_perm, SMB_ACL_PERMSET_T *p_permset)
4566 {
4567         if (wire_perm & ~(SMB_POSIX_ACL_READ|SMB_POSIX_ACL_WRITE|SMB_POSIX_ACL_EXECUTE)) {
4568                 return False;
4569         }
4570
4571         if (sys_acl_clear_perms(*p_permset) ==  -1) {
4572                 return False;
4573         }
4574
4575         if (wire_perm & SMB_POSIX_ACL_READ) {
4576                 if (sys_acl_add_perm(*p_permset, SMB_ACL_READ) == -1) {
4577                         return False;
4578                 }
4579         }
4580         if (wire_perm & SMB_POSIX_ACL_WRITE) {
4581                 if (sys_acl_add_perm(*p_permset, SMB_ACL_WRITE) == -1) {
4582                         return False;
4583                 }
4584         }
4585         if (wire_perm & SMB_POSIX_ACL_EXECUTE) {
4586                 if (sys_acl_add_perm(*p_permset, SMB_ACL_EXECUTE) == -1) {
4587                         return False;
4588                 }
4589         }
4590         return True;
4591 }
4592
4593 /****************************************************************************
4594  Map from wire type to tagtype.
4595 ****************************************************************************/
4596
4597 static bool unix_ex_wire_to_tagtype(unsigned char wire_tt, SMB_ACL_TAG_T *p_tt)
4598 {
4599         switch (wire_tt) {
4600                 case SMB_POSIX_ACL_USER_OBJ:
4601                         *p_tt = SMB_ACL_USER_OBJ;
4602                         break;
4603                 case SMB_POSIX_ACL_USER:
4604                         *p_tt = SMB_ACL_USER;
4605                         break;
4606                 case SMB_POSIX_ACL_GROUP_OBJ:
4607                         *p_tt = SMB_ACL_GROUP_OBJ;
4608                         break;
4609                 case SMB_POSIX_ACL_GROUP:
4610                         *p_tt = SMB_ACL_GROUP;
4611                         break;
4612                 case SMB_POSIX_ACL_MASK:
4613                         *p_tt = SMB_ACL_MASK;
4614                         break;
4615                 case SMB_POSIX_ACL_OTHER:
4616                         *p_tt = SMB_ACL_OTHER;
4617                         break;
4618                 default:
4619                         return False;
4620         }
4621         return True;
4622 }
4623
4624 /****************************************************************************
4625  Create a new POSIX acl from wire permissions.
4626  FIXME ! How does the share mask/mode fit into this.... ?
4627 ****************************************************************************/
4628
4629 static SMB_ACL_T create_posix_acl_from_wire(connection_struct *conn, uint16 num_acls, const char *pdata)
4630 {
4631         unsigned int i;
4632         SMB_ACL_T the_acl = sys_acl_init();
4633
4634         if (the_acl == NULL) {
4635                 return NULL;
4636         }
4637
4638         for (i = 0; i < num_acls; i++) {
4639                 SMB_ACL_ENTRY_T the_entry;
4640                 SMB_ACL_PERMSET_T the_permset;
4641                 SMB_ACL_TAG_T tag_type;
4642
4643                 if (sys_acl_create_entry(&the_acl, &the_entry) == -1) {
4644                         DEBUG(0,("create_posix_acl_from_wire: Failed to create entry %u. (%s)\n",
4645                                 i, strerror(errno) ));
4646                         goto fail;
4647                 }
4648
4649                 if (!unix_ex_wire_to_tagtype(CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)), &tag_type)) {
4650                         DEBUG(0,("create_posix_acl_from_wire: invalid wire tagtype %u on entry %u.\n",
4651                                 CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)), i ));
4652                         goto fail;
4653                 }
4654
4655                 if (sys_acl_set_tag_type(the_entry, tag_type) == -1) {
4656                         DEBUG(0,("create_posix_acl_from_wire: Failed to set tagtype on entry %u. (%s)\n",
4657                                 i, strerror(errno) ));
4658                         goto fail;
4659                 }
4660
4661                 /* Get the permset pointer from the new ACL entry. */
4662                 if (sys_acl_get_permset(the_entry, &the_permset) == -1) {
4663                         DEBUG(0,("create_posix_acl_from_wire: Failed to get permset on entry %u. (%s)\n",
4664                                 i, strerror(errno) ));
4665                         goto fail;
4666                 }
4667
4668                 /* Map from wire to permissions. */
4669                 if (!unix_ex_wire_to_permset(conn, CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)+1), &the_permset)) {
4670                         DEBUG(0,("create_posix_acl_from_wire: invalid permset %u on entry %u.\n",
4671                                 CVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE) + 1), i ));
4672                         goto fail;
4673                 }
4674
4675                 /* Now apply to the new ACL entry. */
4676                 if (sys_acl_set_permset(the_entry, the_permset) == -1) {
4677                         DEBUG(0,("create_posix_acl_from_wire: Failed to add permset on entry %u. (%s)\n",
4678                                 i, strerror(errno) ));
4679                         goto fail;
4680                 }
4681
4682                 if (tag_type == SMB_ACL_USER) {
4683                         uint32 uidval = IVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
4684                         uid_t uid = (uid_t)uidval;
4685                         if (sys_acl_set_qualifier(the_entry,(void *)&uid) == -1) {
4686                                 DEBUG(0,("create_posix_acl_from_wire: Failed to set uid %u on entry %u. (%s)\n",
4687                                         (unsigned int)uid, i, strerror(errno) ));
4688                                 goto fail;
4689                         }
4690                 }
4691
4692                 if (tag_type == SMB_ACL_GROUP) {
4693                         uint32 gidval = IVAL(pdata,(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
4694                         gid_t gid = (uid_t)gidval;
4695                         if (sys_acl_set_qualifier(the_entry,(void *)&gid) == -1) {
4696                                 DEBUG(0,("create_posix_acl_from_wire: Failed to set gid %u on entry %u. (%s)\n",
4697                                         (unsigned int)gid, i, strerror(errno) ));
4698                                 goto fail;
4699                         }
4700                 }
4701         }
4702
4703         return the_acl;
4704
4705  fail:
4706
4707         if (the_acl != NULL) {
4708                 TALLOC_FREE(the_acl);
4709         }
4710         return NULL;
4711 }
4712
4713 /****************************************************************************
4714  Calls from UNIX extensions - Default POSIX ACL set.
4715  If num_def_acls == 0 and not a directory just return. If it is a directory
4716  and num_def_acls == 0 then remove the default acl. Else set the default acl
4717  on the directory.
4718 ****************************************************************************/
4719
4720 bool set_unix_posix_default_acl(connection_struct *conn, const char *fname, const SMB_STRUCT_STAT *psbuf,
4721                                 uint16 num_def_acls, const char *pdata)
4722 {
4723         SMB_ACL_T def_acl = NULL;
4724
4725         if (!S_ISDIR(psbuf->st_ex_mode)) {
4726                 if (num_def_acls) {
4727                         DEBUG(5,("set_unix_posix_default_acl: Can't set default ACL on non-directory file %s\n", fname ));
4728                         errno = EISDIR;
4729                         return False;
4730                 } else {
4731                         return True;
4732                 }
4733         }
4734
4735         if (!num_def_acls) {
4736                 /* Remove the default ACL. */
4737                 if (SMB_VFS_SYS_ACL_DELETE_DEF_FILE(conn, fname) == -1) {
4738                         DEBUG(5,("set_unix_posix_default_acl: acl_delete_def_file failed on directory %s (%s)\n",
4739                                 fname, strerror(errno) ));
4740                         return False;
4741                 }
4742                 return True;
4743         }
4744
4745         if ((def_acl = create_posix_acl_from_wire(conn, num_def_acls, pdata)) == NULL) {
4746                 return False;
4747         }
4748
4749         if (SMB_VFS_SYS_ACL_SET_FILE(conn, fname, SMB_ACL_TYPE_DEFAULT, def_acl) == -1) {
4750                 DEBUG(5,("set_unix_posix_default_acl: acl_set_file failed on directory %s (%s)\n",
4751                         fname, strerror(errno) ));
4752                 TALLOC_FREE(def_acl);
4753                 return False;
4754         }
4755
4756         DEBUG(10,("set_unix_posix_default_acl: set default acl for file %s\n", fname ));
4757         TALLOC_FREE(def_acl);
4758         return True;
4759 }
4760
4761 /****************************************************************************
4762  Remove an ACL from a file. As we don't have acl_delete_entry() available
4763  we must read the current acl and copy all entries except MASK, USER and GROUP
4764  to a new acl, then set that. This (at least on Linux) causes any ACL to be
4765  removed.
4766  FIXME ! How does the share mask/mode fit into this.... ?
4767 ****************************************************************************/
4768
4769 static bool remove_posix_acl(connection_struct *conn, files_struct *fsp, const char *fname)
4770 {
4771         SMB_ACL_T file_acl = NULL;
4772         int entry_id = SMB_ACL_FIRST_ENTRY;
4773         SMB_ACL_ENTRY_T entry;
4774         bool ret = False;
4775         /* Create a new ACL with only 3 entries, u/g/w. */
4776         SMB_ACL_T new_file_acl = sys_acl_init();
4777         SMB_ACL_ENTRY_T user_ent = NULL;
4778         SMB_ACL_ENTRY_T group_ent = NULL;
4779         SMB_ACL_ENTRY_T other_ent = NULL;
4780
4781         if (new_file_acl == NULL) {
4782                 DEBUG(5,("remove_posix_acl: failed to init new ACL with 3 entries for file %s.\n", fname));
4783                 return False;
4784         }
4785
4786         /* Now create the u/g/w entries. */
4787         if (sys_acl_create_entry(&new_file_acl, &user_ent) == -1) {
4788                 DEBUG(5,("remove_posix_acl: Failed to create user entry for file %s. (%s)\n",
4789                         fname, strerror(errno) ));
4790                 goto done;
4791         }
4792         if (sys_acl_set_tag_type(user_ent, SMB_ACL_USER_OBJ) == -1) {
4793                 DEBUG(5,("remove_posix_acl: Failed to set user entry for file %s. (%s)\n",
4794                         fname, strerror(errno) ));
4795                 goto done;
4796         }
4797
4798         if (sys_acl_create_entry(&new_file_acl, &group_ent) == -1) {
4799                 DEBUG(5,("remove_posix_acl: Failed to create group entry for file %s. (%s)\n",
4800                         fname, strerror(errno) ));
4801                 goto done;
4802         }
4803         if (sys_acl_set_tag_type(group_ent, SMB_ACL_GROUP_OBJ) == -1) {
4804                 DEBUG(5,("remove_posix_acl: Failed to set group entry for file %s. (%s)\n",
4805                         fname, strerror(errno) ));
4806                 goto done;
4807         }
4808
4809         if (sys_acl_create_entry(&new_file_acl, &other_ent) == -1) {
4810                 DEBUG(5,("remove_posix_acl: Failed to create other entry for file %s. (%s)\n",
4811                         fname, strerror(errno) ));
4812                 goto done;
4813         }
4814         if (sys_acl_set_tag_type(other_ent, SMB_ACL_OTHER) == -1) {
4815                 DEBUG(5,("remove_posix_acl: Failed to set other entry for file %s. (%s)\n",
4816                         fname, strerror(errno) ));
4817                 goto done;
4818         }
4819
4820         /* Get the current file ACL. */
4821         if (fsp && fsp->fh->fd != -1) {
4822                 file_acl = SMB_VFS_SYS_ACL_GET_FD(fsp);
4823         } else {
4824                 file_acl = SMB_VFS_SYS_ACL_GET_FILE( conn, fname, SMB_ACL_TYPE_ACCESS);
4825         }
4826
4827         if (file_acl == NULL) {
4828                 /* This is only returned if an error occurred. Even for a file with
4829                    no acl a u/g/w acl should be returned. */
4830                 DEBUG(5,("remove_posix_acl: failed to get ACL from file %s (%s).\n",
4831                         fname, strerror(errno) ));
4832                 goto done;
4833         }
4834
4835         while ( sys_acl_get_entry(file_acl, entry_id, &entry) == 1) {
4836                 SMB_ACL_TAG_T tagtype;
4837                 SMB_ACL_PERMSET_T permset;
4838
4839                 entry_id = SMB_ACL_NEXT_ENTRY;
4840
4841                 if (sys_acl_get_tag_type(entry, &tagtype) == -1) {
4842                         DEBUG(5,("remove_posix_acl: failed to get tagtype from ACL on file %s (%s).\n",
4843                                 fname, strerror(errno) ));
4844                         goto done;
4845                 }
4846
4847                 if (sys_acl_get_permset(entry, &permset) == -1) {
4848                         DEBUG(5,("remove_posix_acl: failed to get permset from ACL on file %s (%s).\n",
4849                                 fname, strerror(errno) ));
4850                         goto done;
4851                 }
4852
4853                 if (tagtype == SMB_ACL_USER_OBJ) {
4854                         if (sys_acl_set_permset(user_ent, permset) == -1) {
4855                                 DEBUG(5,("remove_posix_acl: failed to set permset from ACL on file %s (%s).\n",
4856                                         fname, strerror(errno) ));
4857                         }
4858                 } else if (tagtype == SMB_ACL_GROUP_OBJ) {
4859                         if (sys_acl_set_permset(group_ent, permset) == -1) {
4860                                 DEBUG(5,("remove_posix_acl: failed to set permset from ACL on file %s (%s).\n",
4861                                         fname, strerror(errno) ));
4862                         }
4863                 } else if (tagtype == SMB_ACL_OTHER) {
4864                         if (sys_acl_set_permset(other_ent, permset) == -1) {
4865                                 DEBUG(5,("remove_posix_acl: failed to set permset from ACL on file %s (%s).\n",
4866                                         fname, strerror(errno) ));
4867                         }
4868                 }
4869         }
4870
4871         /* Set the new empty file ACL. */
4872         if (fsp && fsp->fh->fd != -1) {
4873                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, new_file_acl) == -1) {
4874                         DEBUG(5,("remove_posix_acl: acl_set_file failed on %s (%s)\n",
4875                                 fname, strerror(errno) ));
4876                         goto done;
4877                 }
4878         } else {
4879                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fname, SMB_ACL_TYPE_ACCESS, new_file_acl) == -1) {
4880                         DEBUG(5,("remove_posix_acl: acl_set_file failed on %s (%s)\n",
4881                                 fname, strerror(errno) ));
4882                         goto done;
4883                 }
4884         }
4885
4886         ret = True;
4887
4888  done:
4889
4890         if (file_acl) {
4891                 TALLOC_FREE(file_acl);
4892         }
4893         if (new_file_acl) {
4894                 TALLOC_FREE(new_file_acl);
4895         }
4896         return ret;
4897 }
4898
4899 /****************************************************************************
4900  Calls from UNIX extensions - POSIX ACL set.
4901  If num_def_acls == 0 then read/modify/write acl after removing all entries
4902  except SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER.
4903 ****************************************************************************/
4904
4905 bool set_unix_posix_acl(connection_struct *conn, files_struct *fsp, const char *fname, uint16 num_acls, const char *pdata)
4906 {
4907         SMB_ACL_T file_acl = NULL;
4908
4909         if (!num_acls) {
4910                 /* Remove the ACL from the file. */
4911                 return remove_posix_acl(conn, fsp, fname);
4912         }
4913
4914         if ((file_acl = create_posix_acl_from_wire(conn, num_acls, pdata)) == NULL) {
4915                 return False;
4916         }
4917
4918         if (fsp && fsp->fh->fd != -1) {
4919                 /* The preferred way - use an open fd. */
4920                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, file_acl) == -1) {
4921                         DEBUG(5,("set_unix_posix_acl: acl_set_file failed on %s (%s)\n",
4922                                 fname, strerror(errno) ));
4923                         TALLOC_FREE(file_acl);
4924                         return False;
4925                 }
4926         } else {
4927                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fname, SMB_ACL_TYPE_ACCESS, file_acl) == -1) {
4928                         DEBUG(5,("set_unix_posix_acl: acl_set_file failed on %s (%s)\n",
4929                                 fname, strerror(errno) ));
4930                         TALLOC_FREE(file_acl);
4931                         return False;
4932                 }
4933         }
4934
4935         DEBUG(10,("set_unix_posix_acl: set acl for file %s\n", fname ));
4936         TALLOC_FREE(file_acl);
4937         return True;
4938 }
4939
4940 /********************************************************************
4941  Pull the NT ACL from a file on disk or the OpenEventlog() access
4942  check.  Caller is responsible for freeing the returned security
4943  descriptor via TALLOC_FREE().  This is designed for dealing with 
4944  user space access checks in smbd outside of the VFS.  For example,
4945  checking access rights in OpenEventlog().
4946
4947  Assume we are dealing with files (for now)
4948 ********************************************************************/
4949
4950 struct security_descriptor *get_nt_acl_no_snum( TALLOC_CTX *ctx, const char *fname, uint32 security_info_wanted)
4951 {
4952         struct security_descriptor *psd, *ret_sd;
4953         connection_struct *conn;
4954         files_struct finfo;
4955         struct fd_handle fh;
4956         NTSTATUS status;
4957         TALLOC_CTX *frame = talloc_stackframe();
4958
4959         conn = talloc_zero(frame, connection_struct);
4960         if (conn == NULL) {
4961                 DEBUG(0, ("talloc failed\n"));
4962                 return NULL;
4963         }
4964
4965         if (!(conn->params = talloc(conn, struct share_params))) {
4966                 DEBUG(0,("get_nt_acl_no_snum: talloc() failed!\n"));
4967                 TALLOC_FREE(frame);
4968                 return NULL;
4969         }
4970
4971         conn->params->service = -1;
4972
4973         set_conn_connectpath(conn, "/");
4974
4975         if (!smbd_vfs_init(conn)) {
4976                 DEBUG(0,("get_nt_acl_no_snum: Unable to create a fake connection struct!\n"));
4977                 conn_free(conn);
4978                 TALLOC_FREE(frame);
4979                 return NULL;
4980         }
4981
4982         ZERO_STRUCT( finfo );
4983         ZERO_STRUCT( fh );
4984
4985         finfo.fnum = FNUM_FIELD_INVALID;
4986         finfo.conn = conn;
4987         finfo.fh = &fh;
4988         finfo.fh->fd = -1;
4989
4990         status = create_synthetic_smb_fname(frame, fname, NULL, NULL,
4991                                             &finfo.fsp_name);
4992         if (!NT_STATUS_IS_OK(status)) {
4993                 conn_free(conn);
4994                 TALLOC_FREE(frame);
4995                 return NULL;
4996         }
4997
4998         if (!NT_STATUS_IS_OK(SMB_VFS_FGET_NT_ACL( &finfo, security_info_wanted, &psd))) {
4999                 DEBUG(0,("get_nt_acl_no_snum: get_nt_acl returned zero.\n"));
5000                 TALLOC_FREE(finfo.fsp_name);
5001                 conn_free(conn);
5002                 TALLOC_FREE(frame);
5003                 return NULL;
5004         }
5005
5006         ret_sd = dup_sec_desc( ctx, psd );
5007
5008         TALLOC_FREE(finfo.fsp_name);
5009         conn_free(conn);
5010         TALLOC_FREE(frame);
5011
5012         return ret_sd;
5013 }
5014
5015 /* Stolen shamelessly from pvfs_default_acl() in source4 :-). */
5016
5017 NTSTATUS make_default_filesystem_acl(TALLOC_CTX *ctx,
5018                                         const char *name,
5019                                         SMB_STRUCT_STAT *psbuf,
5020                                         struct security_descriptor **ppdesc)
5021 {
5022         struct dom_sid owner_sid, group_sid;
5023         size_t size = 0;
5024         struct security_ace aces[4];
5025         uint32_t access_mask = 0;
5026         mode_t mode = psbuf->st_ex_mode;
5027         struct security_acl *new_dacl = NULL;
5028         int idx = 0;
5029
5030         DEBUG(10,("make_default_filesystem_acl: file %s mode = 0%o\n",
5031                 name, (int)mode ));
5032
5033         uid_to_sid(&owner_sid, psbuf->st_ex_uid);
5034         gid_to_sid(&group_sid, psbuf->st_ex_gid);
5035
5036         /*
5037          We provide up to 4 ACEs
5038                 - Owner
5039                 - Group
5040                 - Everyone
5041                 - NT System
5042         */
5043
5044         if (mode & S_IRUSR) {
5045                 if (mode & S_IWUSR) {
5046                         access_mask |= SEC_RIGHTS_FILE_ALL;
5047                 } else {
5048                         access_mask |= SEC_RIGHTS_FILE_READ | SEC_FILE_EXECUTE;
5049                 }
5050         }
5051         if (mode & S_IWUSR) {
5052                 access_mask |= SEC_RIGHTS_FILE_WRITE | SEC_STD_DELETE;
5053         }
5054
5055         init_sec_ace(&aces[idx],
5056                         &owner_sid,
5057                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5058                         access_mask,
5059                         0);
5060         idx++;
5061
5062         access_mask = 0;
5063         if (mode & S_IRGRP) {
5064                 access_mask |= SEC_RIGHTS_FILE_READ | SEC_FILE_EXECUTE;
5065         }
5066         if (mode & S_IWGRP) {
5067                 /* note that delete is not granted - this matches posix behaviour */
5068                 access_mask |= SEC_RIGHTS_FILE_WRITE;
5069         }
5070         if (access_mask) {
5071                 init_sec_ace(&aces[idx],
5072                         &group_sid,
5073                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5074                         access_mask,
5075                         0);
5076                 idx++;
5077         }
5078
5079         access_mask = 0;
5080         if (mode & S_IROTH) {
5081                 access_mask |= SEC_RIGHTS_FILE_READ | SEC_FILE_EXECUTE;
5082         }
5083         if (mode & S_IWOTH) {
5084                 access_mask |= SEC_RIGHTS_FILE_WRITE;
5085         }
5086         if (access_mask) {
5087                 init_sec_ace(&aces[idx],
5088                         &global_sid_World,
5089                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5090                         access_mask,
5091                         0);
5092                 idx++;
5093         }
5094
5095         init_sec_ace(&aces[idx],
5096                         &global_sid_System,
5097                         SEC_ACE_TYPE_ACCESS_ALLOWED,
5098                         SEC_RIGHTS_FILE_ALL,
5099                         0);
5100         idx++;
5101
5102         new_dacl = make_sec_acl(ctx,
5103                         NT4_ACL_REVISION,
5104                         idx,
5105                         aces);
5106
5107         if (!new_dacl) {
5108                 return NT_STATUS_NO_MEMORY;
5109         }
5110
5111         *ppdesc = make_sec_desc(ctx,
5112                         SECURITY_DESCRIPTOR_REVISION_1,
5113                         SEC_DESC_SELF_RELATIVE|SEC_DESC_DACL_PRESENT,
5114                         &owner_sid,
5115                         &group_sid,
5116                         NULL,
5117                         new_dacl,
5118                         &size);
5119         if (!*ppdesc) {
5120                 return NT_STATUS_NO_MEMORY;
5121         }
5122         return NT_STATUS_OK;
5123 }