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