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