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