437112c751d5cc6916c0e19e0f7e4162326db55b
[ira/wip.git] / source3 / smbd / posix_acls.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB NT Security Descriptor / Unix permission conversion.
4    Copyright (C) Jeremy Allison 1994-2009.
5    Copyright (C) Andreas Gruenbacher 2002.
6    Copyright (C) Simo Sorce <idra@samba.org> 2009.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23
24 extern struct current_user current_user;
25 extern const struct generic_mapping file_generic_mapping;
26
27 #undef  DBGC_CLASS
28 #define DBGC_CLASS DBGC_ACLS
29
30 /****************************************************************************
31  Data structures representing the internal ACE format.
32 ****************************************************************************/
33
34 enum ace_owner {UID_ACE, GID_ACE, WORLD_ACE};
35 enum ace_attribute {ALLOW_ACE, DENY_ACE}; /* Used for incoming NT ACLS. */
36
37 typedef union posix_id {
38                 uid_t uid;
39                 gid_t gid;
40                 int world;
41 } posix_id;
42
43 typedef struct canon_ace {
44         struct canon_ace *next, *prev;
45         SMB_ACL_TAG_T type;
46         mode_t perms; /* Only use S_I(R|W|X)USR mode bits here. */
47         DOM_SID trustee;
48         enum ace_owner owner_type;
49         enum ace_attribute attr;
50         posix_id unix_ug;
51         uint8_t ace_flags; /* From windows ACE entry. */
52 } canon_ace;
53
54 #define ALL_ACE_PERMS (S_IRUSR|S_IWUSR|S_IXUSR)
55
56 /*
57  * EA format of user.SAMBA_PAI (Samba_Posix_Acl_Interitance)
58  * attribute on disk - version 1.
59  * All values are little endian.
60  *
61  * |  1   |  1   |   2         |         2           |  ....
62  * +------+------+-------------+---------------------+-------------+--------------------+
63  * | vers | flag | num_entries | num_default_entries | ..entries.. | default_entries... |
64  * +------+------+-------------+---------------------+-------------+--------------------+
65  *
66  * Entry format is :
67  *
68  * |  1   |       4           |
69  * +------+-------------------+
70  * | value|  uid/gid or world |
71  * | type |  value            |
72  * +------+-------------------+
73  *
74  * Version 2 format. Stores extra Windows metadata about an ACL.
75  *
76  * |  1   |  2       |   2         |         2           |  ....
77  * +------+----------+-------------+---------------------+-------------+--------------------+
78  * | vers | ace      | num_entries | num_default_entries | ..entries.. | default_entries... |
79  * |   2  |  type    |             |                     |             |                    |
80  * +------+----------+-------------+---------------------+-------------+--------------------+
81  *
82  * Entry format is :
83  *
84  * |  1   |  1   |       4           |
85  * +------+------+-------------------+
86  * | ace  | value|  uid/gid or world |
87  * | flag | type |  value            |
88  * +------+-------------------+------+
89  *
90  */
91
92 #define PAI_VERSION_OFFSET                      0
93
94 #define PAI_V1_FLAG_OFFSET                      1
95 #define PAI_V1_NUM_ENTRIES_OFFSET               2
96 #define PAI_V1_NUM_DEFAULT_ENTRIES_OFFSET       4
97 #define PAI_V1_ENTRIES_BASE                     6
98 #define PAI_V1_ACL_FLAG_PROTECTED               0x1
99 #define PAI_V1_ENTRY_LENGTH                     5
100
101 #define PAI_V1_VERSION                          1
102
103 #define PAI_V2_TYPE_OFFSET                      1
104 #define PAI_V2_NUM_ENTRIES_OFFSET               3
105 #define PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET       5
106 #define PAI_V2_ENTRIES_BASE                     7
107 #define PAI_V2_ENTRY_LENGTH                     6
108
109 #define PAI_V2_VERSION                          2
110
111 /*
112  * In memory format of user.SAMBA_PAI attribute.
113  */
114
115 struct pai_entry {
116         struct pai_entry *next, *prev;
117         uint8_t ace_flags;
118         enum ace_owner owner_type;
119         posix_id unix_ug;
120 };
121
122 struct pai_val {
123         uint16_t sd_type;
124         unsigned int num_entries;
125         struct pai_entry *entry_list;
126         unsigned int num_def_entries;
127         struct pai_entry *def_entry_list;
128 };
129
130 /************************************************************************
131  Return a uint32 of the pai_entry principal.
132 ************************************************************************/
133
134 static uint32_t get_pai_entry_val(struct pai_entry *paie)
135 {
136         switch (paie->owner_type) {
137                 case UID_ACE:
138                         DEBUG(10,("get_pai_entry_val: uid = %u\n", (unsigned int)paie->unix_ug.uid ));
139                         return (uint32_t)paie->unix_ug.uid;
140                 case GID_ACE:
141                         DEBUG(10,("get_pai_entry_val: gid = %u\n", (unsigned int)paie->unix_ug.gid ));
142                         return (uint32_t)paie->unix_ug.gid;
143                 case WORLD_ACE:
144                 default:
145                         DEBUG(10,("get_pai_entry_val: world ace\n"));
146                         return (uint32_t)-1;
147         }
148 }
149
150 /************************************************************************
151  Return a uint32 of the entry principal.
152 ************************************************************************/
153
154 static uint32_t get_entry_val(canon_ace *ace_entry)
155 {
156         switch (ace_entry->owner_type) {
157                 case UID_ACE:
158                         DEBUG(10,("get_entry_val: uid = %u\n", (unsigned int)ace_entry->unix_ug.uid ));
159                         return (uint32_t)ace_entry->unix_ug.uid;
160                 case GID_ACE:
161                         DEBUG(10,("get_entry_val: gid = %u\n", (unsigned int)ace_entry->unix_ug.gid ));
162                         return (uint32_t)ace_entry->unix_ug.gid;
163                 case WORLD_ACE:
164                 default:
165                         DEBUG(10,("get_entry_val: world ace\n"));
166                         return (uint32_t)-1;
167         }
168 }
169
170 /************************************************************************
171  Create the on-disk format (always v2 now). Caller must free.
172 ************************************************************************/
173
174 static char *create_pai_buf_v2(canon_ace *file_ace_list,
175                                 canon_ace *dir_ace_list,
176                                 uint16_t sd_type,
177                                 size_t *store_size)
178 {
179         char *pai_buf = NULL;
180         canon_ace *ace_list = NULL;
181         char *entry_offset = NULL;
182         unsigned int num_entries = 0;
183         unsigned int num_def_entries = 0;
184
185         for (ace_list = file_ace_list; ace_list; ace_list = ace_list->next) {
186                 num_entries++;
187         }
188
189         for (ace_list = dir_ace_list; ace_list; ace_list = ace_list->next) {
190                 num_def_entries++;
191         }
192
193         DEBUG(10,("create_pai_buf_v2: num_entries = %u, num_def_entries = %u\n", num_entries, num_def_entries ));
194
195         *store_size = PAI_V2_ENTRIES_BASE +
196                 ((num_entries + num_def_entries)*PAI_V2_ENTRY_LENGTH);
197
198         pai_buf = (char *)SMB_MALLOC(*store_size);
199         if (!pai_buf) {
200                 return NULL;
201         }
202
203         /* Set up the header. */
204         memset(pai_buf, '\0', PAI_V2_ENTRIES_BASE);
205         SCVAL(pai_buf,PAI_VERSION_OFFSET,PAI_V2_VERSION);
206         SSVAL(pai_buf,PAI_V2_TYPE_OFFSET, sd_type);
207         SSVAL(pai_buf,PAI_V2_NUM_ENTRIES_OFFSET,num_entries);
208         SSVAL(pai_buf,PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET,num_def_entries);
209
210         entry_offset = pai_buf + PAI_V2_ENTRIES_BASE;
211
212         for (ace_list = file_ace_list; ace_list; ace_list = ace_list->next) {
213                 uint8_t type_val = (uint8_t)ace_list->owner_type;
214                 uint32_t entry_val = get_entry_val(ace_list);
215
216                 SCVAL(entry_offset,0,ace_list->ace_flags);
217                 SCVAL(entry_offset,1,type_val);
218                 SIVAL(entry_offset,2,entry_val);
219                 entry_offset += PAI_V2_ENTRY_LENGTH;
220         }
221
222         for (ace_list = dir_ace_list; ace_list; ace_list = ace_list->next) {
223                 uint8_t type_val = (uint8_t)ace_list->owner_type;
224                 uint32_t entry_val = get_entry_val(ace_list);
225
226                 SCVAL(entry_offset,0,ace_list->ace_flags);
227                 SCVAL(entry_offset,1,type_val);
228                 SIVAL(entry_offset,2,entry_val);
229                 entry_offset += PAI_V2_ENTRY_LENGTH;
230         }
231
232         return pai_buf;
233 }
234
235 /************************************************************************
236  Store the user.SAMBA_PAI attribute on disk.
237 ************************************************************************/
238
239 static void store_inheritance_attributes(files_struct *fsp,
240                                         canon_ace *file_ace_list,
241                                         canon_ace *dir_ace_list,
242                                         uint16_t sd_type)
243 {
244         int ret;
245         size_t store_size;
246         char *pai_buf;
247
248         if (!lp_map_acl_inherit(SNUM(fsp->conn))) {
249                 return;
250         }
251
252         pai_buf = create_pai_buf_v2(file_ace_list, dir_ace_list,
253                                 sd_type, &store_size);
254
255         if (fsp->fh->fd != -1) {
256                 ret = SMB_VFS_FSETXATTR(fsp, SAMBA_POSIX_INHERITANCE_EA_NAME,
257                                 pai_buf, store_size, 0);
258         } else {
259                 ret = SMB_VFS_SETXATTR(fsp->conn,fsp->fsp_name, SAMBA_POSIX_INHERITANCE_EA_NAME,
260                                 pai_buf, store_size, 0);
261         }
262
263         SAFE_FREE(pai_buf);
264
265         DEBUG(10,("store_inheritance_attribute: type 0x%x for file %s\n",
266                 (unsigned int)sd_type,
267                 fsp->fsp_name));
268
269         if (ret == -1 && !no_acl_syscall_error(errno)) {
270                 DEBUG(1,("store_inheritance_attribute: Error %s\n", strerror(errno) ));
271         }
272 }
273
274 /************************************************************************
275  Delete the in memory inheritance info.
276 ************************************************************************/
277
278 static void free_inherited_info(struct pai_val *pal)
279 {
280         if (pal) {
281                 struct pai_entry *paie, *paie_next;
282                 for (paie = pal->entry_list; paie; paie = paie_next) {
283                         paie_next = paie->next;
284                         SAFE_FREE(paie);
285                 }
286                 for (paie = pal->def_entry_list; paie; paie = paie_next) {
287                         paie_next = paie->next;
288                         SAFE_FREE(paie);
289                 }
290                 SAFE_FREE(pal);
291         }
292 }
293
294 /************************************************************************
295  Get any stored ACE flags.
296 ************************************************************************/
297
298 static uint16_t get_pai_flags(struct pai_val *pal, canon_ace *ace_entry, bool default_ace)
299 {
300         struct pai_entry *paie;
301
302         if (!pal) {
303                 return 0;
304         }
305
306         /* If the entry exists it is inherited. */
307         for (paie = (default_ace ? pal->def_entry_list : pal->entry_list); paie; paie = paie->next) {
308                 if (ace_entry->owner_type == paie->owner_type &&
309                                 get_entry_val(ace_entry) == get_pai_entry_val(paie))
310                         return paie->ace_flags;
311         }
312         return 0;
313 }
314
315 /************************************************************************
316  Ensure an attribute just read is valid - v1.
317 ************************************************************************/
318
319 static bool check_pai_ok_v1(const char *pai_buf, size_t pai_buf_data_size)
320 {
321         uint16 num_entries;
322         uint16 num_def_entries;
323
324         if (pai_buf_data_size < PAI_V1_ENTRIES_BASE) {
325                 /* Corrupted - too small. */
326                 return false;
327         }
328
329         if (CVAL(pai_buf,PAI_VERSION_OFFSET) != PAI_V1_VERSION) {
330                 return false;
331         }
332
333         num_entries = SVAL(pai_buf,PAI_V1_NUM_ENTRIES_OFFSET);
334         num_def_entries = SVAL(pai_buf,PAI_V1_NUM_DEFAULT_ENTRIES_OFFSET);
335
336         /* Check the entry lists match. */
337         /* Each entry is 5 bytes (type plus 4 bytes of uid or gid). */
338
339         if (((num_entries + num_def_entries)*PAI_V1_ENTRY_LENGTH) +
340                         PAI_V1_ENTRIES_BASE != pai_buf_data_size) {
341                 return false;
342         }
343
344         return true;
345 }
346
347 /************************************************************************
348  Ensure an attribute just read is valid - v2.
349 ************************************************************************/
350
351 static bool check_pai_ok_v2(const char *pai_buf, size_t pai_buf_data_size)
352 {
353         uint16 num_entries;
354         uint16 num_def_entries;
355
356         if (pai_buf_data_size < PAI_V2_ENTRIES_BASE) {
357                 /* Corrupted - too small. */
358                 return false;
359         }
360
361         if (CVAL(pai_buf,PAI_VERSION_OFFSET) != PAI_V2_VERSION) {
362                 return false;
363         }
364
365         num_entries = SVAL(pai_buf,PAI_V2_NUM_ENTRIES_OFFSET);
366         num_def_entries = SVAL(pai_buf,PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET);
367
368         /* Check the entry lists match. */
369         /* Each entry is 6 bytes (flags + type + 4 bytes of uid or gid). */
370
371         if (((num_entries + num_def_entries)*PAI_V2_ENTRY_LENGTH) +
372                         PAI_V2_ENTRIES_BASE != pai_buf_data_size) {
373                 return false;
374         }
375
376         return true;
377 }
378
379 /************************************************************************
380  Decode the owner.
381 ************************************************************************/
382
383 static bool get_pai_owner_type(struct pai_entry *paie, const char *entry_offset)
384 {
385         paie->owner_type = (enum ace_owner)CVAL(entry_offset,0);
386         switch( paie->owner_type) {
387                 case UID_ACE:
388                         paie->unix_ug.uid = (uid_t)IVAL(entry_offset,1);
389                         DEBUG(10,("get_pai_owner_type: uid = %u\n",
390                                 (unsigned int)paie->unix_ug.uid ));
391                         break;
392                 case GID_ACE:
393                         paie->unix_ug.gid = (gid_t)IVAL(entry_offset,1);
394                         DEBUG(10,("get_pai_owner_type: gid = %u\n",
395                                 (unsigned int)paie->unix_ug.gid ));
396                         break;
397                 case WORLD_ACE:
398                         paie->unix_ug.world = -1;
399                         DEBUG(10,("get_pai_owner_type: world ace\n"));
400                         break;
401                 default:
402                         return false;
403         }
404         return true;
405 }
406
407 /************************************************************************
408  Process v2 entries.
409 ************************************************************************/
410
411 static const char *create_pai_v1_entries(struct pai_val *paiv,
412                                 const char *entry_offset,
413                                 bool def_entry)
414 {
415         int i;
416
417         for (i = 0; i < paiv->num_entries; i++) {
418                 struct pai_entry *paie = SMB_MALLOC_P(struct pai_entry);
419                 if (!paie) {
420                         return NULL;
421                 }
422
423                 paie->ace_flags = SEC_ACE_FLAG_INHERITED_ACE;
424                 if (!get_pai_owner_type(paie, entry_offset)) {
425                         return NULL;
426                 }
427
428                 if (!def_entry) {
429                         DLIST_ADD(paiv->entry_list, paie);
430                 } else {
431                         DLIST_ADD(paiv->def_entry_list, paie);
432                 }
433                 entry_offset += PAI_V1_ENTRY_LENGTH;
434         }
435         return entry_offset;
436 }
437
438 /************************************************************************
439  Convert to in-memory format from version 1.
440 ************************************************************************/
441
442 static struct pai_val *create_pai_val_v1(const char *buf, size_t size)
443 {
444         const char *entry_offset;
445         struct pai_val *paiv = NULL;
446
447         if (!check_pai_ok_v1(buf, size)) {
448                 return NULL;
449         }
450
451         paiv = SMB_MALLOC_P(struct pai_val);
452         if (!paiv) {
453                 return NULL;
454         }
455
456         memset(paiv, '\0', sizeof(struct pai_val));
457
458         paiv->sd_type = (CVAL(buf,PAI_V1_FLAG_OFFSET) == PAI_V1_ACL_FLAG_PROTECTED) ?
459                         SE_DESC_DACL_PROTECTED : 0;
460
461         paiv->num_entries = SVAL(buf,PAI_V1_NUM_ENTRIES_OFFSET);
462         paiv->num_def_entries = SVAL(buf,PAI_V1_NUM_DEFAULT_ENTRIES_OFFSET);
463
464         entry_offset = buf + PAI_V1_ENTRIES_BASE;
465
466         DEBUG(10,("create_pai_val: num_entries = %u, num_def_entries = %u\n",
467                         paiv->num_entries, paiv->num_def_entries ));
468
469         entry_offset = create_pai_v1_entries(paiv, entry_offset, false);
470         if (entry_offset == NULL) {
471                 free_inherited_info(paiv);
472                 return NULL;
473         }
474         entry_offset = create_pai_v1_entries(paiv, entry_offset, true);
475         if (entry_offset == NULL) {
476                 free_inherited_info(paiv);
477                 return NULL;
478         }
479
480         return paiv;
481 }
482
483 /************************************************************************
484  Process v2 entries.
485 ************************************************************************/
486
487 static const char *create_pai_v2_entries(struct pai_val *paiv,
488                                 const char *entry_offset,
489                                 bool def_entry)
490 {
491         int i;
492
493         for (i = 0; i < paiv->num_entries; i++) {
494                 struct pai_entry *paie = SMB_MALLOC_P(struct pai_entry);
495                 if (!paie) {
496                         return NULL;
497                 }
498
499                 paie->ace_flags = CVAL(entry_offset,0);
500
501                 entry_offset++;
502
503                 if (!get_pai_owner_type(paie, entry_offset)) {
504                         return NULL;
505                 }
506                 if (!def_entry) {
507                         DLIST_ADD(paiv->entry_list, paie);
508                 } else {
509                         DLIST_ADD(paiv->def_entry_list, paie);
510                 }
511                 entry_offset += PAI_V2_ENTRY_LENGTH;
512         }
513         return entry_offset;
514 }
515
516 /************************************************************************
517  Convert to in-memory format from version 2.
518 ************************************************************************/
519
520 static struct pai_val *create_pai_val_v2(const char *buf, size_t size)
521 {
522         const char *entry_offset;
523         struct pai_val *paiv = NULL;
524
525         if (!check_pai_ok_v2(buf, size)) {
526                 return NULL;
527         }
528
529         paiv = SMB_MALLOC_P(struct pai_val);
530         if (!paiv) {
531                 return NULL;
532         }
533
534         memset(paiv, '\0', sizeof(struct pai_val));
535
536         paiv->sd_type = SVAL(buf,PAI_V2_TYPE_OFFSET);
537
538         paiv->num_entries = SVAL(buf,PAI_V2_NUM_ENTRIES_OFFSET);
539         paiv->num_def_entries = SVAL(buf,PAI_V2_NUM_DEFAULT_ENTRIES_OFFSET);
540
541         entry_offset = buf + PAI_V2_ENTRIES_BASE;
542
543         DEBUG(10,("create_pai_val_v2: num_entries = %u, num_def_entries = %u\n",
544                         paiv->num_entries, paiv->num_def_entries ));
545
546         entry_offset = create_pai_v2_entries(paiv, entry_offset, false);
547         if (entry_offset == NULL) {
548                 free_inherited_info(paiv);
549                 return NULL;
550         }
551         entry_offset = create_pai_v2_entries(paiv, entry_offset, true);
552         if (entry_offset == NULL) {
553                 free_inherited_info(paiv);
554                 return NULL;
555         }
556
557         return paiv;
558 }
559
560 /************************************************************************
561  Convert to in-memory format - from either version 1 or 2.
562 ************************************************************************/
563
564 static struct pai_val *create_pai_val(const char *buf, size_t size)
565 {
566         if (size < 1) {
567                 return NULL;
568         }
569         if (CVAL(buf,PAI_VERSION_OFFSET) == PAI_V1_VERSION) {
570                 return create_pai_val_v1(buf, size);
571         } else if (CVAL(buf,PAI_VERSION_OFFSET) == PAI_V2_VERSION) {
572                 return create_pai_val_v2(buf, size);
573         } else {
574                 return NULL;
575         }
576 }
577
578 /************************************************************************
579  Load the user.SAMBA_PAI attribute.
580 ************************************************************************/
581
582 static struct pai_val *fload_inherited_info(files_struct *fsp)
583 {
584         char *pai_buf;
585         size_t pai_buf_size = 1024;
586         struct pai_val *paiv = NULL;
587         ssize_t ret;
588
589         if (!lp_map_acl_inherit(SNUM(fsp->conn))) {
590                 return NULL;
591         }
592
593         if ((pai_buf = (char *)SMB_MALLOC(pai_buf_size)) == NULL) {
594                 return NULL;
595         }
596
597         do {
598                 if (fsp->fh->fd != -1) {
599                         ret = SMB_VFS_FGETXATTR(fsp, SAMBA_POSIX_INHERITANCE_EA_NAME,
600                                         pai_buf, pai_buf_size);
601                 } else {
602                         ret = SMB_VFS_GETXATTR(fsp->conn,fsp->fsp_name,SAMBA_POSIX_INHERITANCE_EA_NAME,
603                                         pai_buf, pai_buf_size);
604                 }
605
606                 if (ret == -1) {
607                         if (errno != ERANGE) {
608                                 break;
609                         }
610                         /* Buffer too small - enlarge it. */
611                         pai_buf_size *= 2;
612                         SAFE_FREE(pai_buf);
613                         if (pai_buf_size > 1024*1024) {
614                                 return NULL; /* Limit malloc to 1mb. */
615                         }
616                         if ((pai_buf = (char *)SMB_MALLOC(pai_buf_size)) == NULL)
617                                 return NULL;
618                 }
619         } while (ret == -1);
620
621         DEBUG(10,("load_inherited_info: ret = %lu for file %s\n", (unsigned long)ret, fsp->fsp_name));
622
623         if (ret == -1) {
624                 /* No attribute or not supported. */
625 #if defined(ENOATTR)
626                 if (errno != ENOATTR)
627                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
628 #else
629                 if (errno != ENOSYS)
630                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
631 #endif
632                 SAFE_FREE(pai_buf);
633                 return NULL;
634         }
635
636         paiv = create_pai_val(pai_buf, ret);
637
638         if (paiv) {
639                 DEBUG(10,("load_inherited_info: ACL type is 0x%x for file %s\n",
640                         (unsigned int)paiv->sd_type,
641                         fsp->fsp_name));
642         }
643
644         SAFE_FREE(pai_buf);
645         return paiv;
646 }
647
648 /************************************************************************
649  Load the user.SAMBA_PAI attribute.
650 ************************************************************************/
651
652 static struct pai_val *load_inherited_info(const struct connection_struct *conn,
653                                            const char *fname)
654 {
655         char *pai_buf;
656         size_t pai_buf_size = 1024;
657         struct pai_val *paiv = NULL;
658         ssize_t ret;
659
660         if (!lp_map_acl_inherit(SNUM(conn))) {
661                 return NULL;
662         }
663
664         if ((pai_buf = (char *)SMB_MALLOC(pai_buf_size)) == NULL) {
665                 return NULL;
666         }
667
668         do {
669                 ret = SMB_VFS_GETXATTR(conn, fname,
670                                        SAMBA_POSIX_INHERITANCE_EA_NAME,
671                                        pai_buf, pai_buf_size);
672
673                 if (ret == -1) {
674                         if (errno != ERANGE) {
675                                 break;
676                         }
677                         /* Buffer too small - enlarge it. */
678                         pai_buf_size *= 2;
679                         SAFE_FREE(pai_buf);
680                         if (pai_buf_size > 1024*1024) {
681                                 return NULL; /* Limit malloc to 1mb. */
682                         }
683                         if ((pai_buf = (char *)SMB_MALLOC(pai_buf_size)) == NULL)
684                                 return NULL;
685                 }
686         } while (ret == -1);
687
688         DEBUG(10,("load_inherited_info: ret = %lu for file %s\n", (unsigned long)ret, fname));
689
690         if (ret == -1) {
691                 /* No attribute or not supported. */
692 #if defined(ENOATTR)
693                 if (errno != ENOATTR)
694                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
695 #else
696                 if (errno != ENOSYS)
697                         DEBUG(10,("load_inherited_info: Error %s\n", strerror(errno) ));
698 #endif
699                 SAFE_FREE(pai_buf);
700                 return NULL;
701         }
702
703         paiv = create_pai_val(pai_buf, ret);
704
705         if (paiv) {
706                 DEBUG(10,("load_inherited_info: ACL type 0x%x for file %s\n",
707                         (unsigned int)paiv->sd_type,
708                         fname));
709         }
710
711         SAFE_FREE(pai_buf);
712         return paiv;
713 }
714
715 /****************************************************************************
716  Functions to manipulate the internal ACE format.
717 ****************************************************************************/
718
719 /****************************************************************************
720  Count a linked list of canonical ACE entries.
721 ****************************************************************************/
722
723 static size_t count_canon_ace_list( canon_ace *l_head )
724 {
725         size_t count = 0;
726         canon_ace *ace;
727
728         for (ace = l_head; ace; ace = ace->next)
729                 count++;
730
731         return count;
732 }
733
734 /****************************************************************************
735  Free a linked list of canonical ACE entries.
736 ****************************************************************************/
737
738 static void free_canon_ace_list( canon_ace *l_head )
739 {
740         canon_ace *list, *next;
741
742         for (list = l_head; list; list = next) {
743                 next = list->next;
744                 DLIST_REMOVE(l_head, list);
745                 SAFE_FREE(list);
746         }
747 }
748
749 /****************************************************************************
750  Function to duplicate a canon_ace entry.
751 ****************************************************************************/
752
753 static canon_ace *dup_canon_ace( canon_ace *src_ace)
754 {
755         canon_ace *dst_ace = SMB_MALLOC_P(canon_ace);
756
757         if (dst_ace == NULL)
758                 return NULL;
759
760         *dst_ace = *src_ace;
761         dst_ace->prev = dst_ace->next = NULL;
762         return dst_ace;
763 }
764
765 /****************************************************************************
766  Print out a canon ace.
767 ****************************************************************************/
768
769 static void print_canon_ace(canon_ace *pace, int num)
770 {
771         dbgtext( "canon_ace index %d. Type = %s ", num, pace->attr == ALLOW_ACE ? "allow" : "deny" );
772         dbgtext( "SID = %s ", sid_string_dbg(&pace->trustee));
773         if (pace->owner_type == UID_ACE) {
774                 const char *u_name = uidtoname(pace->unix_ug.uid);
775                 dbgtext( "uid %u (%s) ", (unsigned int)pace->unix_ug.uid, u_name );
776         } else if (pace->owner_type == GID_ACE) {
777                 char *g_name = gidtoname(pace->unix_ug.gid);
778                 dbgtext( "gid %u (%s) ", (unsigned int)pace->unix_ug.gid, g_name );
779         } else
780                 dbgtext( "other ");
781         switch (pace->type) {
782                 case SMB_ACL_USER:
783                         dbgtext( "SMB_ACL_USER ");
784                         break;
785                 case SMB_ACL_USER_OBJ:
786                         dbgtext( "SMB_ACL_USER_OBJ ");
787                         break;
788                 case SMB_ACL_GROUP:
789                         dbgtext( "SMB_ACL_GROUP ");
790                         break;
791                 case SMB_ACL_GROUP_OBJ:
792                         dbgtext( "SMB_ACL_GROUP_OBJ ");
793                         break;
794                 case SMB_ACL_OTHER:
795                         dbgtext( "SMB_ACL_OTHER ");
796                         break;
797                 default:
798                         dbgtext( "MASK " );
799                         break;
800         }
801
802         dbgtext( "ace_flags = 0x%x ", (unsigned int)pace->ace_flags);
803         dbgtext( "perms ");
804         dbgtext( "%c", pace->perms & S_IRUSR ? 'r' : '-');
805         dbgtext( "%c", pace->perms & S_IWUSR ? 'w' : '-');
806         dbgtext( "%c\n", pace->perms & S_IXUSR ? 'x' : '-');
807 }
808
809 /****************************************************************************
810  Print out a canon ace list.
811 ****************************************************************************/
812
813 static void print_canon_ace_list(const char *name, canon_ace *ace_list)
814 {
815         int count = 0;
816
817         if( DEBUGLVL( 10 )) {
818                 dbgtext( "print_canon_ace_list: %s\n", name );
819                 for (;ace_list; ace_list = ace_list->next, count++)
820                         print_canon_ace(ace_list, count );
821         }
822 }
823
824 /****************************************************************************
825  Map POSIX ACL perms to canon_ace permissions (a mode_t containing only S_(R|W|X)USR bits).
826 ****************************************************************************/
827
828 static mode_t convert_permset_to_mode_t(connection_struct *conn, SMB_ACL_PERMSET_T permset)
829 {
830         mode_t ret = 0;
831
832         ret |= (SMB_VFS_SYS_ACL_GET_PERM(conn, permset, SMB_ACL_READ) ? S_IRUSR : 0);
833         ret |= (SMB_VFS_SYS_ACL_GET_PERM(conn, permset, SMB_ACL_WRITE) ? S_IWUSR : 0);
834         ret |= (SMB_VFS_SYS_ACL_GET_PERM(conn, permset, SMB_ACL_EXECUTE) ? S_IXUSR : 0);
835
836         return ret;
837 }
838
839 /****************************************************************************
840  Map generic UNIX permissions to canon_ace permissions (a mode_t containing only S_(R|W|X)USR bits).
841 ****************************************************************************/
842
843 static mode_t unix_perms_to_acl_perms(mode_t mode, int r_mask, int w_mask, int x_mask)
844 {
845         mode_t ret = 0;
846
847         if (mode & r_mask)
848                 ret |= S_IRUSR;
849         if (mode & w_mask)
850                 ret |= S_IWUSR;
851         if (mode & x_mask)
852                 ret |= S_IXUSR;
853
854         return ret;
855 }
856
857 /****************************************************************************
858  Map canon_ace permissions (a mode_t containing only S_(R|W|X)USR bits) to
859  an SMB_ACL_PERMSET_T.
860 ****************************************************************************/
861
862 static int map_acl_perms_to_permset(connection_struct *conn, mode_t mode, SMB_ACL_PERMSET_T *p_permset)
863 {
864         if (SMB_VFS_SYS_ACL_CLEAR_PERMS(conn, *p_permset) ==  -1)
865                 return -1;
866         if (mode & S_IRUSR) {
867                 if (SMB_VFS_SYS_ACL_ADD_PERM(conn, *p_permset, SMB_ACL_READ) == -1)
868                         return -1;
869         }
870         if (mode & S_IWUSR) {
871                 if (SMB_VFS_SYS_ACL_ADD_PERM(conn, *p_permset, SMB_ACL_WRITE) == -1)
872                         return -1;
873         }
874         if (mode & S_IXUSR) {
875                 if (SMB_VFS_SYS_ACL_ADD_PERM(conn, *p_permset, SMB_ACL_EXECUTE) == -1)
876                         return -1;
877         }
878         return 0;
879 }
880
881 /****************************************************************************
882  Function to create owner and group SIDs from a SMB_STRUCT_STAT.
883 ****************************************************************************/
884
885 void create_file_sids(const SMB_STRUCT_STAT *psbuf, DOM_SID *powner_sid, DOM_SID *pgroup_sid)
886 {
887         uid_to_sid( powner_sid, psbuf->st_ex_uid );
888         gid_to_sid( pgroup_sid, psbuf->st_ex_gid );
889 }
890
891 /****************************************************************************
892  Is the identity in two ACEs equal ? Check both SID and uid/gid.
893 ****************************************************************************/
894
895 static bool identity_in_ace_equal(canon_ace *ace1, canon_ace *ace2)
896 {
897         if (sid_equal(&ace1->trustee, &ace2->trustee)) {
898                 return True;
899         }
900         if (ace1->owner_type == ace2->owner_type) {
901                 if (ace1->owner_type == UID_ACE &&
902                                 ace1->unix_ug.uid == ace2->unix_ug.uid) {
903                         return True;
904                 } else if (ace1->owner_type == GID_ACE &&
905                                 ace1->unix_ug.gid == ace2->unix_ug.gid) {
906                         return True;
907                 }
908         }
909         return False;
910 }
911
912 /****************************************************************************
913  Merge aces with a common sid - if both are allow or deny, OR the permissions together and
914  delete the second one. If the first is deny, mask the permissions off and delete the allow
915  if the permissions become zero, delete the deny if the permissions are non zero.
916 ****************************************************************************/
917
918 static void merge_aces( canon_ace **pp_list_head )
919 {
920         canon_ace *l_head = *pp_list_head;
921         canon_ace *curr_ace_outer;
922         canon_ace *curr_ace_outer_next;
923
924         /*
925          * First, merge allow entries with identical SIDs, and deny entries
926          * with identical SIDs.
927          */
928
929         for (curr_ace_outer = l_head; curr_ace_outer; curr_ace_outer = curr_ace_outer_next) {
930                 canon_ace *curr_ace;
931                 canon_ace *curr_ace_next;
932
933                 curr_ace_outer_next = curr_ace_outer->next; /* Save the link in case we delete. */
934
935                 for (curr_ace = curr_ace_outer->next; curr_ace; curr_ace = curr_ace_next) {
936
937                         curr_ace_next = curr_ace->next; /* Save the link in case of delete. */
938
939                         if (identity_in_ace_equal(curr_ace, curr_ace_outer) &&
940                                 (curr_ace->attr == curr_ace_outer->attr)) {
941
942                                 if( DEBUGLVL( 10 )) {
943                                         dbgtext("merge_aces: Merging ACE's\n");
944                                         print_canon_ace( curr_ace_outer, 0);
945                                         print_canon_ace( curr_ace, 0);
946                                 }
947
948                                 /* Merge two allow or two deny ACE's. */
949
950                                 curr_ace_outer->perms |= curr_ace->perms;
951                                 DLIST_REMOVE(l_head, curr_ace);
952                                 SAFE_FREE(curr_ace);
953                                 curr_ace_outer_next = curr_ace_outer->next; /* We may have deleted the link. */
954                         }
955                 }
956         }
957
958         /*
959          * Now go through and mask off allow permissions with deny permissions.
960          * We can delete either the allow or deny here as we know that each SID
961          * appears only once in the list.
962          */
963
964         for (curr_ace_outer = l_head; curr_ace_outer; curr_ace_outer = curr_ace_outer_next) {
965                 canon_ace *curr_ace;
966                 canon_ace *curr_ace_next;
967
968                 curr_ace_outer_next = curr_ace_outer->next; /* Save the link in case we delete. */
969
970                 for (curr_ace = curr_ace_outer->next; curr_ace; curr_ace = curr_ace_next) {
971
972                         curr_ace_next = curr_ace->next; /* Save the link in case of delete. */
973
974                         /*
975                          * Subtract ACE's with different entries. Due to the ordering constraints
976                          * we've put on the ACL, we know the deny must be the first one.
977                          */
978
979                         if (identity_in_ace_equal(curr_ace, curr_ace_outer) &&
980                                 (curr_ace_outer->attr == DENY_ACE) && (curr_ace->attr == ALLOW_ACE)) {
981
982                                 if( DEBUGLVL( 10 )) {
983                                         dbgtext("merge_aces: Masking ACE's\n");
984                                         print_canon_ace( curr_ace_outer, 0);
985                                         print_canon_ace( curr_ace, 0);
986                                 }
987
988                                 curr_ace->perms &= ~curr_ace_outer->perms;
989
990                                 if (curr_ace->perms == 0) {
991
992                                         /*
993                                          * The deny overrides the allow. Remove the allow.
994                                          */
995
996                                         DLIST_REMOVE(l_head, curr_ace);
997                                         SAFE_FREE(curr_ace);
998                                         curr_ace_outer_next = curr_ace_outer->next; /* We may have deleted the link. */
999
1000                                 } else {
1001
1002                                         /*
1003                                          * Even after removing permissions, there
1004                                          * are still allow permissions - delete the deny.
1005                                          * It is safe to delete the deny here,
1006                                          * as we are guarenteed by the deny first
1007                                          * ordering that all the deny entries for
1008                                          * this SID have already been merged into one
1009                                          * before we can get to an allow ace.
1010                                          */
1011
1012                                         DLIST_REMOVE(l_head, curr_ace_outer);
1013                                         SAFE_FREE(curr_ace_outer);
1014                                         break;
1015                                 }
1016                         }
1017
1018                 } /* end for curr_ace */
1019         } /* end for curr_ace_outer */
1020
1021         /* We may have modified the list. */
1022
1023         *pp_list_head = l_head;
1024 }
1025
1026 /****************************************************************************
1027  Check if we need to return NT4.x compatible ACL entries.
1028 ****************************************************************************/
1029
1030 bool nt4_compatible_acls(void)
1031 {
1032         int compat = lp_acl_compatibility();
1033
1034         if (compat == ACL_COMPAT_AUTO) {
1035                 enum remote_arch_types ra_type = get_remote_arch();
1036
1037                 /* Automatically adapt to client */
1038                 return (ra_type <= RA_WINNT);
1039         } else
1040                 return (compat == ACL_COMPAT_WINNT);
1041 }
1042
1043
1044 /****************************************************************************
1045  Map canon_ace perms to permission bits NT.
1046  The attr element is not used here - we only process deny entries on set,
1047  not get. Deny entries are implicit on get with ace->perms = 0.
1048 ****************************************************************************/
1049
1050 static uint32_t map_canon_ace_perms(int snum,
1051                                 enum security_ace_type *pacl_type,
1052                                 mode_t perms,
1053                                 bool directory_ace)
1054 {
1055         uint32_t nt_mask = 0;
1056
1057         *pacl_type = SEC_ACE_TYPE_ACCESS_ALLOWED;
1058
1059         if (lp_acl_map_full_control(snum) && ((perms & ALL_ACE_PERMS) == ALL_ACE_PERMS)) {
1060                 if (directory_ace) {
1061                         nt_mask = UNIX_DIRECTORY_ACCESS_RWX;
1062                 } else {
1063                         nt_mask = (UNIX_ACCESS_RWX & ~DELETE_ACCESS);
1064                 }
1065         } else if ((perms & ALL_ACE_PERMS) == (mode_t)0) {
1066                 /*
1067                  * Windows NT refuses to display ACEs with no permissions in them (but
1068                  * they are perfectly legal with Windows 2000). If the ACE has empty
1069                  * permissions we cannot use 0, so we use the otherwise unused
1070                  * WRITE_OWNER permission, which we ignore when we set an ACL.
1071                  * We abstract this into a #define of UNIX_ACCESS_NONE to allow this
1072                  * to be changed in the future.
1073                  */
1074
1075                 if (nt4_compatible_acls())
1076                         nt_mask = UNIX_ACCESS_NONE;
1077                 else
1078                         nt_mask = 0;
1079         } else {
1080                 if (directory_ace) {
1081                         nt_mask |= ((perms & S_IRUSR) ? UNIX_DIRECTORY_ACCESS_R : 0 );
1082                         nt_mask |= ((perms & S_IWUSR) ? UNIX_DIRECTORY_ACCESS_W : 0 );
1083                         nt_mask |= ((perms & S_IXUSR) ? UNIX_DIRECTORY_ACCESS_X : 0 );
1084                 } else {
1085                         nt_mask |= ((perms & S_IRUSR) ? UNIX_ACCESS_R : 0 );
1086                         nt_mask |= ((perms & S_IWUSR) ? UNIX_ACCESS_W : 0 );
1087                         nt_mask |= ((perms & S_IXUSR) ? UNIX_ACCESS_X : 0 );
1088                 }
1089         }
1090
1091         DEBUG(10,("map_canon_ace_perms: Mapped (UNIX) %x to (NT) %x\n",
1092                         (unsigned int)perms, (unsigned int)nt_mask ));
1093
1094         return nt_mask;
1095 }
1096
1097 /****************************************************************************
1098  Map NT perms to a UNIX mode_t.
1099 ****************************************************************************/
1100
1101 #define FILE_SPECIFIC_READ_BITS (FILE_READ_DATA|FILE_READ_EA|FILE_READ_ATTRIBUTES)
1102 #define FILE_SPECIFIC_WRITE_BITS (FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_WRITE_EA|FILE_WRITE_ATTRIBUTES)
1103 #define FILE_SPECIFIC_EXECUTE_BITS (FILE_EXECUTE)
1104
1105 static mode_t map_nt_perms( uint32 *mask, int type)
1106 {
1107         mode_t mode = 0;
1108
1109         switch(type) {
1110         case S_IRUSR:
1111                 if((*mask) & GENERIC_ALL_ACCESS)
1112                         mode = S_IRUSR|S_IWUSR|S_IXUSR;
1113                 else {
1114                         mode |= ((*mask) & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IRUSR : 0;
1115                         mode |= ((*mask) & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWUSR : 0;
1116                         mode |= ((*mask) & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXUSR : 0;
1117                 }
1118                 break;
1119         case S_IRGRP:
1120                 if((*mask) & GENERIC_ALL_ACCESS)
1121                         mode = S_IRGRP|S_IWGRP|S_IXGRP;
1122                 else {
1123                         mode |= ((*mask) & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IRGRP : 0;
1124                         mode |= ((*mask) & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWGRP : 0;
1125                         mode |= ((*mask) & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXGRP : 0;
1126                 }
1127                 break;
1128         case S_IROTH:
1129                 if((*mask) & GENERIC_ALL_ACCESS)
1130                         mode = S_IROTH|S_IWOTH|S_IXOTH;
1131                 else {
1132                         mode |= ((*mask) & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IROTH : 0;
1133                         mode |= ((*mask) & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWOTH : 0;
1134                         mode |= ((*mask) & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXOTH : 0;
1135                 }
1136                 break;
1137         }
1138
1139         return mode;
1140 }
1141
1142 /****************************************************************************
1143  Unpack a SEC_DESC into a UNIX owner and group.
1144 ****************************************************************************/
1145
1146 NTSTATUS unpack_nt_owners(int snum, uid_t *puser, gid_t *pgrp, uint32 security_info_sent, const SEC_DESC *psd)
1147 {
1148         DOM_SID owner_sid;
1149         DOM_SID grp_sid;
1150
1151         *puser = (uid_t)-1;
1152         *pgrp = (gid_t)-1;
1153
1154         if(security_info_sent == 0) {
1155                 DEBUG(0,("unpack_nt_owners: no security info sent !\n"));
1156                 return NT_STATUS_OK;
1157         }
1158
1159         /*
1160          * Validate the owner and group SID's.
1161          */
1162
1163         memset(&owner_sid, '\0', sizeof(owner_sid));
1164         memset(&grp_sid, '\0', sizeof(grp_sid));
1165
1166         DEBUG(5,("unpack_nt_owners: validating owner_sids.\n"));
1167
1168         /*
1169          * Don't immediately fail if the owner sid cannot be validated.
1170          * This may be a group chown only set.
1171          */
1172
1173         if (security_info_sent & OWNER_SECURITY_INFORMATION) {
1174                 sid_copy(&owner_sid, psd->owner_sid);
1175                 if (!sid_to_uid(&owner_sid, puser)) {
1176                         if (lp_force_unknown_acl_user(snum)) {
1177                                 /* this allows take ownership to work
1178                                  * reasonably */
1179                                 *puser = current_user.ut.uid;
1180                         } else {
1181                                 DEBUG(3,("unpack_nt_owners: unable to validate"
1182                                          " owner sid for %s\n",
1183                                          sid_string_dbg(&owner_sid)));
1184                                 return NT_STATUS_INVALID_OWNER;
1185                         }
1186                 }
1187                 DEBUG(3,("unpack_nt_owners: owner sid mapped to uid %u\n",
1188                          (unsigned int)*puser ));
1189         }
1190
1191         /*
1192          * Don't immediately fail if the group sid cannot be validated.
1193          * This may be an owner chown only set.
1194          */
1195
1196         if (security_info_sent & GROUP_SECURITY_INFORMATION) {
1197                 sid_copy(&grp_sid, psd->group_sid);
1198                 if (!sid_to_gid( &grp_sid, pgrp)) {
1199                         if (lp_force_unknown_acl_user(snum)) {
1200                                 /* this allows take group ownership to work
1201                                  * reasonably */
1202                                 *pgrp = current_user.ut.gid;
1203                         } else {
1204                                 DEBUG(3,("unpack_nt_owners: unable to validate"
1205                                          " group sid.\n"));
1206                                 return NT_STATUS_INVALID_OWNER;
1207                         }
1208                 }
1209                 DEBUG(3,("unpack_nt_owners: group sid mapped to gid %u\n",
1210                          (unsigned int)*pgrp));
1211         }
1212
1213         DEBUG(5,("unpack_nt_owners: owner_sids validated.\n"));
1214
1215         return NT_STATUS_OK;
1216 }
1217
1218 /****************************************************************************
1219  Ensure the enforced permissions for this share apply.
1220 ****************************************************************************/
1221
1222 static void apply_default_perms(const struct share_params *params,
1223                                 const bool is_directory, canon_ace *pace,
1224                                 mode_t type)
1225 {
1226         mode_t and_bits = (mode_t)0;
1227         mode_t or_bits = (mode_t)0;
1228
1229         /* Get the initial bits to apply. */
1230
1231         if (is_directory) {
1232                 and_bits = lp_dir_security_mask(params->service);
1233                 or_bits = lp_force_dir_security_mode(params->service);
1234         } else {
1235                 and_bits = lp_security_mask(params->service);
1236                 or_bits = lp_force_security_mode(params->service);
1237         }
1238
1239         /* Now bounce them into the S_USR space. */     
1240         switch(type) {
1241         case S_IRUSR:
1242                 /* Ensure owner has read access. */
1243                 pace->perms |= S_IRUSR;
1244                 if (is_directory)
1245                         pace->perms |= (S_IWUSR|S_IXUSR);
1246                 and_bits = unix_perms_to_acl_perms(and_bits, S_IRUSR, S_IWUSR, S_IXUSR);
1247                 or_bits = unix_perms_to_acl_perms(or_bits, S_IRUSR, S_IWUSR, S_IXUSR);
1248                 break;
1249         case S_IRGRP:
1250                 and_bits = unix_perms_to_acl_perms(and_bits, S_IRGRP, S_IWGRP, S_IXGRP);
1251                 or_bits = unix_perms_to_acl_perms(or_bits, S_IRGRP, S_IWGRP, S_IXGRP);
1252                 break;
1253         case S_IROTH:
1254                 and_bits = unix_perms_to_acl_perms(and_bits, S_IROTH, S_IWOTH, S_IXOTH);
1255                 or_bits = unix_perms_to_acl_perms(or_bits, S_IROTH, S_IWOTH, S_IXOTH);
1256                 break;
1257         }
1258
1259         pace->perms = ((pace->perms & and_bits)|or_bits);
1260 }
1261
1262 /****************************************************************************
1263  Check if a given uid/SID is in a group gid/SID. This is probably very
1264  expensive and will need optimisation. A *lot* of optimisation :-). JRA.
1265 ****************************************************************************/
1266
1267 static bool uid_entry_in_group( canon_ace *uid_ace, canon_ace *group_ace )
1268 {
1269         const char *u_name = NULL;
1270
1271         /* "Everyone" always matches every uid. */
1272
1273         if (sid_equal(&group_ace->trustee, &global_sid_World))
1274                 return True;
1275
1276         /*
1277          * if it's the current user, we already have the unix token
1278          * and don't need to do the complex user_in_group_sid() call
1279          */
1280         if (uid_ace->unix_ug.uid == current_user.ut.uid) {
1281                 size_t i;
1282
1283                 if (group_ace->unix_ug.gid == current_user.ut.gid) {
1284                         return True;
1285                 }
1286
1287                 for (i=0; i < current_user.ut.ngroups; i++) {
1288                         if (group_ace->unix_ug.gid == current_user.ut.groups[i]) {
1289                                 return True;
1290                         }
1291                 }
1292         }
1293
1294         /* u_name talloc'ed off tos. */
1295         u_name = uidtoname(uid_ace->unix_ug.uid);
1296         if (!u_name) {
1297                 return False;
1298         }
1299
1300         /*
1301          * user_in_group_sid() uses create_token_from_username()
1302          * which creates an artificial NT token given just a username,
1303          * so this is not reliable for users from foreign domains
1304          * exported by winbindd!
1305          */
1306         return user_in_group_sid(u_name, &group_ace->trustee);
1307 }
1308
1309 /****************************************************************************
1310  A well formed POSIX file or default ACL has at least 3 entries, a 
1311  SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER_OBJ.
1312  In addition, the owner must always have at least read access.
1313  When using this call on get_acl, the pst struct is valid and contains
1314  the mode of the file. When using this call on set_acl, the pst struct has
1315  been modified to have a mode containing the default for this file or directory
1316  type.
1317 ****************************************************************************/
1318
1319 static bool ensure_canon_entry_valid(canon_ace **pp_ace,
1320                                      const struct share_params *params,
1321                                      const bool is_directory,
1322                                                         const DOM_SID *pfile_owner_sid,
1323                                                         const DOM_SID *pfile_grp_sid,
1324                                                         const SMB_STRUCT_STAT *pst,
1325                                                         bool setting_acl)
1326 {
1327         canon_ace *pace;
1328         bool got_user = False;
1329         bool got_grp = False;
1330         bool got_other = False;
1331         canon_ace *pace_other = NULL;
1332
1333         for (pace = *pp_ace; pace; pace = pace->next) {
1334                 if (pace->type == SMB_ACL_USER_OBJ) {
1335
1336                         if (setting_acl)
1337                                 apply_default_perms(params, is_directory, pace, S_IRUSR);
1338                         got_user = True;
1339
1340                 } else if (pace->type == SMB_ACL_GROUP_OBJ) {
1341
1342                         /*
1343                          * Ensure create mask/force create mode is respected on set.
1344                          */
1345
1346                         if (setting_acl)
1347                                 apply_default_perms(params, is_directory, pace, S_IRGRP);
1348                         got_grp = True;
1349
1350                 } else if (pace->type == SMB_ACL_OTHER) {
1351
1352                         /*
1353                          * Ensure create mask/force create mode is respected on set.
1354                          */
1355
1356                         if (setting_acl)
1357                                 apply_default_perms(params, is_directory, pace, S_IROTH);
1358                         got_other = True;
1359                         pace_other = pace;
1360                 }
1361         }
1362
1363         if (!got_user) {
1364                 if ((pace = SMB_MALLOC_P(canon_ace)) == NULL) {
1365                         DEBUG(0,("ensure_canon_entry_valid: malloc fail.\n"));
1366                         return False;
1367                 }
1368
1369                 ZERO_STRUCTP(pace);
1370                 pace->type = SMB_ACL_USER_OBJ;
1371                 pace->owner_type = UID_ACE;
1372                 pace->unix_ug.uid = pst->st_ex_uid;
1373                 pace->trustee = *pfile_owner_sid;
1374                 pace->attr = ALLOW_ACE;
1375
1376                 if (setting_acl) {
1377                         /* See if the owning user is in any of the other groups in
1378                            the ACE. If so, OR in the permissions from that group. */
1379
1380                         bool group_matched = False;
1381                         canon_ace *pace_iter;
1382
1383                         for (pace_iter = *pp_ace; pace_iter; pace_iter = pace_iter->next) {
1384                                 if (pace_iter->type == SMB_ACL_GROUP_OBJ || pace_iter->type == SMB_ACL_GROUP) {
1385                                         if (uid_entry_in_group(pace, pace_iter)) {
1386                                                 pace->perms |= pace_iter->perms;
1387                                                 group_matched = True;
1388                                         }
1389                                 }
1390                         }
1391
1392                         /* If we only got an "everyone" perm, just use that. */
1393                         if (!group_matched) {
1394                                 if (got_other)
1395                                         pace->perms = pace_other->perms;
1396                                 else
1397                                         pace->perms = 0;
1398                         }
1399
1400                         apply_default_perms(params, is_directory, pace, S_IRUSR);
1401                 } else {
1402                         pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRUSR, S_IWUSR, S_IXUSR);
1403                 }
1404
1405                 DLIST_ADD(*pp_ace, pace);
1406         }
1407
1408         if (!got_grp) {
1409                 if ((pace = SMB_MALLOC_P(canon_ace)) == NULL) {
1410                         DEBUG(0,("ensure_canon_entry_valid: malloc fail.\n"));
1411                         return False;
1412                 }
1413
1414                 ZERO_STRUCTP(pace);
1415                 pace->type = SMB_ACL_GROUP_OBJ;
1416                 pace->owner_type = GID_ACE;
1417                 pace->unix_ug.uid = pst->st_ex_gid;
1418                 pace->trustee = *pfile_grp_sid;
1419                 pace->attr = ALLOW_ACE;
1420                 if (setting_acl) {
1421                         /* If we only got an "everyone" perm, just use that. */
1422                         if (got_other)
1423                                 pace->perms = pace_other->perms;
1424                         else
1425                                 pace->perms = 0;
1426                         apply_default_perms(params, is_directory, pace, S_IRGRP);
1427                 } else {
1428                         pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IRGRP, S_IWGRP, S_IXGRP);
1429                 }
1430
1431                 DLIST_ADD(*pp_ace, pace);
1432         }
1433
1434         if (!got_other) {
1435                 if ((pace = SMB_MALLOC_P(canon_ace)) == NULL) {
1436                         DEBUG(0,("ensure_canon_entry_valid: malloc fail.\n"));
1437                         return False;
1438                 }
1439
1440                 ZERO_STRUCTP(pace);
1441                 pace->type = SMB_ACL_OTHER;
1442                 pace->owner_type = WORLD_ACE;
1443                 pace->unix_ug.world = -1;
1444                 pace->trustee = global_sid_World;
1445                 pace->attr = ALLOW_ACE;
1446                 if (setting_acl) {
1447                         pace->perms = 0;
1448                         apply_default_perms(params, is_directory, pace, S_IROTH);
1449                 } else
1450                         pace->perms = unix_perms_to_acl_perms(pst->st_ex_mode, S_IROTH, S_IWOTH, S_IXOTH);
1451
1452                 DLIST_ADD(*pp_ace, pace);
1453         }
1454
1455         return True;
1456 }
1457
1458 /****************************************************************************
1459  Check if a POSIX ACL has the required SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ entries.
1460  If it does not have them, check if there are any entries where the trustee is the
1461  file owner or the owning group, and map these to SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ.
1462 ****************************************************************************/
1463
1464 static void check_owning_objs(canon_ace *ace, DOM_SID *pfile_owner_sid, DOM_SID *pfile_grp_sid)
1465 {
1466         bool got_user_obj, got_group_obj;
1467         canon_ace *current_ace;
1468         int i, entries;
1469
1470         entries = count_canon_ace_list(ace);
1471         got_user_obj = False;
1472         got_group_obj = False;
1473
1474         for (i=0, current_ace = ace; i < entries; i++, current_ace = current_ace->next) {
1475                 if (current_ace->type == SMB_ACL_USER_OBJ)
1476                         got_user_obj = True;
1477                 else if (current_ace->type == SMB_ACL_GROUP_OBJ)
1478                         got_group_obj = True;
1479         }
1480         if (got_user_obj && got_group_obj) {
1481                 DEBUG(10,("check_owning_objs: ACL had owning user/group entries.\n"));
1482                 return;
1483         }
1484
1485         for (i=0, current_ace = ace; i < entries; i++, current_ace = current_ace->next) {
1486                 if (!got_user_obj && current_ace->owner_type == UID_ACE &&
1487                                 sid_equal(&current_ace->trustee, pfile_owner_sid)) {
1488                         current_ace->type = SMB_ACL_USER_OBJ;
1489                         got_user_obj = True;
1490                 }
1491                 if (!got_group_obj && current_ace->owner_type == GID_ACE &&
1492                                 sid_equal(&current_ace->trustee, pfile_grp_sid)) {
1493                         current_ace->type = SMB_ACL_GROUP_OBJ;
1494                         got_group_obj = True;
1495                 }
1496         }
1497         if (!got_user_obj)
1498                 DEBUG(10,("check_owning_objs: ACL is missing an owner entry.\n"));
1499         if (!got_group_obj)
1500                 DEBUG(10,("check_owning_objs: ACL is missing an owning group entry.\n"));
1501 }
1502
1503 /****************************************************************************
1504  Unpack a SEC_DESC into two canonical ace lists.
1505 ****************************************************************************/
1506
1507 static bool create_canon_ace_lists(files_struct *fsp,
1508                                         SMB_STRUCT_STAT *pst,
1509                                         DOM_SID *pfile_owner_sid,
1510                                         DOM_SID *pfile_grp_sid,
1511                                         canon_ace **ppfile_ace,
1512                                         canon_ace **ppdir_ace,
1513                                         const SEC_ACL *dacl)
1514 {
1515         bool all_aces_are_inherit_only = (fsp->is_directory ? True : False);
1516         canon_ace *file_ace = NULL;
1517         canon_ace *dir_ace = NULL;
1518         canon_ace *current_ace = NULL;
1519         bool got_dir_allow = False;
1520         bool got_file_allow = False;
1521         int i, j;
1522
1523         *ppfile_ace = NULL;
1524         *ppdir_ace = NULL;
1525
1526         /*
1527          * Convert the incoming ACL into a more regular form.
1528          */
1529
1530         for(i = 0; i < dacl->num_aces; i++) {
1531                 SEC_ACE *psa = &dacl->aces[i];
1532
1533                 if((psa->type != SEC_ACE_TYPE_ACCESS_ALLOWED) && (psa->type != SEC_ACE_TYPE_ACCESS_DENIED)) {
1534                         DEBUG(3,("create_canon_ace_lists: unable to set anything but an ALLOW or DENY ACE.\n"));
1535                         return False;
1536                 }
1537
1538                 if (nt4_compatible_acls()) {
1539                         /*
1540                          * The security mask may be UNIX_ACCESS_NONE which should map into
1541                          * no permissions (we overload the WRITE_OWNER bit for this) or it
1542                          * should be one of the ALL/EXECUTE/READ/WRITE bits. Arrange for this
1543                          * to be so. Any other bits override the UNIX_ACCESS_NONE bit.
1544                          */
1545
1546                         /*
1547                          * Convert GENERIC bits to specific bits.
1548                          */
1549  
1550                         se_map_generic(&psa->access_mask, &file_generic_mapping);
1551
1552                         psa->access_mask &= (UNIX_ACCESS_NONE|FILE_ALL_ACCESS);
1553
1554                         if(psa->access_mask != UNIX_ACCESS_NONE)
1555                                 psa->access_mask &= ~UNIX_ACCESS_NONE;
1556                 }
1557         }
1558
1559         /*
1560          * Deal with the fact that NT 4.x re-writes the canonical format
1561          * that we return for default ACLs. If a directory ACE is identical
1562          * to a inherited directory ACE then NT changes the bits so that the
1563          * first ACE is set to OI|IO and the second ACE for this SID is set
1564          * to CI. We need to repair this. JRA.
1565          */
1566
1567         for(i = 0; i < dacl->num_aces; i++) {
1568                 SEC_ACE *psa1 = &dacl->aces[i];
1569
1570                 for (j = i + 1; j < dacl->num_aces; j++) {
1571                         SEC_ACE *psa2 = &dacl->aces[j];
1572
1573                         if (psa1->access_mask != psa2->access_mask)
1574                                 continue;
1575
1576                         if (!sid_equal(&psa1->trustee, &psa2->trustee))
1577                                 continue;
1578
1579                         /*
1580                          * Ok - permission bits and SIDs are equal.
1581                          * Check if flags were re-written.
1582                          */
1583
1584                         if (psa1->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
1585
1586                                 psa1->flags |= (psa2->flags & (SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT));
1587                                 psa2->flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT);
1588
1589                         } else if (psa2->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
1590
1591                                 psa2->flags |= (psa1->flags & (SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT));
1592                                 psa1->flags &= ~(SEC_ACE_FLAG_CONTAINER_INHERIT|SEC_ACE_FLAG_OBJECT_INHERIT);
1593
1594                         }
1595                 }
1596         }
1597
1598         for(i = 0; i < dacl->num_aces; i++) {
1599                 SEC_ACE *psa = &dacl->aces[i];
1600
1601                 /*
1602                  * Create a cannon_ace entry representing this NT DACL ACE.
1603                  */
1604
1605                 if ((current_ace = SMB_MALLOC_P(canon_ace)) == NULL) {
1606                         free_canon_ace_list(file_ace);
1607                         free_canon_ace_list(dir_ace);
1608                         DEBUG(0,("create_canon_ace_lists: malloc fail.\n"));
1609                         return False;
1610                 }
1611
1612                 ZERO_STRUCTP(current_ace);
1613
1614                 sid_copy(&current_ace->trustee, &psa->trustee);
1615
1616                 /*
1617                  * Try and work out if the SID is a user or group
1618                  * as we need to flag these differently for POSIX.
1619                  * Note what kind of a POSIX ACL this should map to.
1620                  */
1621
1622                 if( sid_equal(&current_ace->trustee, &global_sid_World)) {
1623                         current_ace->owner_type = WORLD_ACE;
1624                         current_ace->unix_ug.world = -1;
1625                         current_ace->type = SMB_ACL_OTHER;
1626                 } else if (sid_equal(&current_ace->trustee, &global_sid_Creator_Owner)) {
1627                         current_ace->owner_type = UID_ACE;
1628                         current_ace->unix_ug.uid = pst->st_ex_uid;
1629                         current_ace->type = SMB_ACL_USER_OBJ;
1630
1631                         /*
1632                          * The Creator Owner entry only specifies inheritable permissions,
1633                          * never access permissions. WinNT doesn't always set the ACE to
1634                          *INHERIT_ONLY, though.
1635                          */
1636
1637                         if (nt4_compatible_acls())
1638                                 psa->flags |= SEC_ACE_FLAG_INHERIT_ONLY;
1639                 } else if (sid_equal(&current_ace->trustee, &global_sid_Creator_Group)) {
1640                         current_ace->owner_type = GID_ACE;
1641                         current_ace->unix_ug.gid = pst->st_ex_gid;
1642                         current_ace->type = SMB_ACL_GROUP_OBJ;
1643
1644                         /*
1645                          * The Creator Group entry only specifies inheritable permissions,
1646                          * never access permissions. WinNT doesn't always set the ACE to
1647                          *INHERIT_ONLY, though.
1648                          */
1649                         if (nt4_compatible_acls())
1650                                 psa->flags |= SEC_ACE_FLAG_INHERIT_ONLY;
1651
1652                 } else if (sid_to_uid( &current_ace->trustee, &current_ace->unix_ug.uid)) {
1653                         current_ace->owner_type = UID_ACE;
1654                         /* If it's the owning user, this is a user_obj, not
1655                          * a user. */
1656                         if (current_ace->unix_ug.uid == pst->st_ex_uid) {
1657                                 current_ace->type = SMB_ACL_USER_OBJ;
1658                         } else {
1659                                 current_ace->type = SMB_ACL_USER;
1660                         }
1661                 } else if (sid_to_gid( &current_ace->trustee, &current_ace->unix_ug.gid)) {
1662                         current_ace->owner_type = GID_ACE;
1663                         /* If it's the primary group, this is a group_obj, not
1664                          * a group. */
1665                         if (current_ace->unix_ug.gid == pst->st_ex_gid) {
1666                                 current_ace->type = SMB_ACL_GROUP_OBJ;
1667                         } else {
1668                                 current_ace->type = SMB_ACL_GROUP;
1669                         }
1670                 } else {
1671                         /*
1672                          * Silently ignore map failures in non-mappable SIDs (NT Authority, BUILTIN etc).
1673                          */
1674
1675                         if (non_mappable_sid(&psa->trustee)) {
1676                                 DEBUG(10, ("create_canon_ace_lists: ignoring "
1677                                            "non-mappable SID %s\n",
1678                                            sid_string_dbg(&psa->trustee)));
1679                                 SAFE_FREE(current_ace);
1680                                 continue;
1681                         }
1682
1683                         free_canon_ace_list(file_ace);
1684                         free_canon_ace_list(dir_ace);
1685                         DEBUG(0, ("create_canon_ace_lists: unable to map SID "
1686                                   "%s to uid or gid.\n",
1687                                   sid_string_dbg(&current_ace->trustee)));
1688                         SAFE_FREE(current_ace);
1689                         return False;
1690                 }
1691
1692                 /*
1693                  * Map the given NT permissions into a UNIX mode_t containing only
1694                  * S_I(R|W|X)USR bits.
1695                  */
1696
1697                 current_ace->perms |= map_nt_perms( &psa->access_mask, S_IRUSR);
1698                 current_ace->attr = (psa->type == SEC_ACE_TYPE_ACCESS_ALLOWED) ? ALLOW_ACE : DENY_ACE;
1699
1700                 /* Store the ace_flag. */
1701                 current_ace->ace_flags = psa->flags;
1702
1703                 /*
1704                  * Now add the created ace to either the file list, the directory
1705                  * list, or both. We *MUST* preserve the order here (hence we use
1706                  * DLIST_ADD_END) as NT ACLs are order dependent.
1707                  */
1708
1709                 if (fsp->is_directory) {
1710
1711                         /*
1712                          * We can only add to the default POSIX ACE list if the ACE is
1713                          * designed to be inherited by both files and directories.
1714                          */
1715
1716                         if ((psa->flags & (SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT)) ==
1717                                 (SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT)) {
1718
1719                                 DLIST_ADD_END(dir_ace, current_ace, canon_ace *);
1720
1721                                 /*
1722                                  * Note if this was an allow ace. We can't process
1723                                  * any further deny ace's after this.
1724                                  */
1725
1726                                 if (current_ace->attr == ALLOW_ACE)
1727                                         got_dir_allow = True;
1728
1729                                 if ((current_ace->attr == DENY_ACE) && got_dir_allow) {
1730                                         DEBUG(0,("create_canon_ace_lists: malformed ACL in inheritable ACL ! \
1731 Deny entry after Allow entry. Failing to set on file %s.\n", fsp->fsp_name ));
1732                                         free_canon_ace_list(file_ace);
1733                                         free_canon_ace_list(dir_ace);
1734                                         return False;
1735                                 }       
1736
1737                                 if( DEBUGLVL( 10 )) {
1738                                         dbgtext("create_canon_ace_lists: adding dir ACL:\n");
1739                                         print_canon_ace( current_ace, 0);
1740                                 }
1741
1742                                 /*
1743                                  * If this is not an inherit only ACE we need to add a duplicate
1744                                  * to the file acl.
1745                                  */
1746
1747                                 if (!(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY)) {
1748                                         canon_ace *dup_ace = dup_canon_ace(current_ace);
1749
1750                                         if (!dup_ace) {
1751                                                 DEBUG(0,("create_canon_ace_lists: malloc fail !\n"));
1752                                                 free_canon_ace_list(file_ace);
1753                                                 free_canon_ace_list(dir_ace);
1754                                                 return False;
1755                                         }
1756
1757                                         /*
1758                                          * We must not free current_ace here as its
1759                                          * pointer is now owned by the dir_ace list.
1760                                          */
1761                                         current_ace = dup_ace;
1762                                 } else {
1763                                         /*
1764                                          * We must not free current_ace here as its
1765                                          * pointer is now owned by the dir_ace list.
1766                                          */
1767                                         current_ace = NULL;
1768                                 }
1769                         }
1770                 }
1771
1772                 /*
1773                  * Only add to the file ACL if not inherit only.
1774                  */
1775
1776                 if (current_ace && !(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY)) {
1777                         DLIST_ADD_END(file_ace, current_ace, canon_ace *);
1778
1779                         /*
1780                          * Note if this was an allow ace. We can't process
1781                          * any further deny ace's after this.
1782                          */
1783
1784                         if (current_ace->attr == ALLOW_ACE)
1785                                 got_file_allow = True;
1786
1787                         if ((current_ace->attr == DENY_ACE) && got_file_allow) {
1788                                 DEBUG(0,("create_canon_ace_lists: malformed ACL in file ACL ! \
1789 Deny entry after Allow entry. Failing to set on file %s.\n", fsp->fsp_name ));
1790                                 free_canon_ace_list(file_ace);
1791                                 free_canon_ace_list(dir_ace);
1792                                 return False;
1793                         }       
1794
1795                         if( DEBUGLVL( 10 )) {
1796                                 dbgtext("create_canon_ace_lists: adding file ACL:\n");
1797                                 print_canon_ace( current_ace, 0);
1798                         }
1799                         all_aces_are_inherit_only = False;
1800                         /*
1801                          * We must not free current_ace here as its
1802                          * pointer is now owned by the file_ace list.
1803                          */
1804                         current_ace = NULL;
1805                 }
1806
1807                 /*
1808                  * Free if ACE was not added.
1809                  */
1810
1811                 SAFE_FREE(current_ace);
1812         }
1813
1814         if (fsp->is_directory && all_aces_are_inherit_only) {
1815                 /*
1816                  * Windows 2000 is doing one of these weird 'inherit acl'
1817                  * traverses to conserve NTFS ACL resources. Just pretend
1818                  * there was no DACL sent. JRA.
1819                  */
1820
1821                 DEBUG(10,("create_canon_ace_lists: Win2k inherit acl traverse. Ignoring DACL.\n"));
1822                 free_canon_ace_list(file_ace);
1823                 free_canon_ace_list(dir_ace);
1824                 file_ace = NULL;
1825                 dir_ace = NULL;
1826         } else {
1827                 /*
1828                  * Check if we have SMB_ACL_USER_OBJ and SMB_ACL_GROUP_OBJ entries in each
1829                  * ACL. If we don't have them, check if any SMB_ACL_USER/SMB_ACL_GROUP
1830                  * entries can be converted to *_OBJ. Usually we will already have these
1831                  * entries in the Default ACL, and the Access ACL will not have them.
1832                  */
1833                 if (file_ace) {
1834                         check_owning_objs(file_ace, pfile_owner_sid, pfile_grp_sid);
1835                 }
1836                 if (dir_ace) {
1837                         check_owning_objs(dir_ace, pfile_owner_sid, pfile_grp_sid);
1838                 }
1839         }
1840
1841         *ppfile_ace = file_ace;
1842         *ppdir_ace = dir_ace;
1843
1844         return True;
1845 }
1846
1847 /****************************************************************************
1848  ASCII art time again... JRA :-).
1849
1850  We have 4 cases to process when moving from an NT ACL to a POSIX ACL. Firstly,
1851  we insist the ACL is in canonical form (ie. all DENY entries preceede ALLOW
1852  entries). Secondly, the merge code has ensured that all duplicate SID entries for
1853  allow or deny have been merged, so the same SID can only appear once in the deny
1854  list or once in the allow list.
1855
1856  We then process as follows :
1857
1858  ---------------------------------------------------------------------------
1859  First pass - look for a Everyone DENY entry.
1860
1861  If it is deny all (rwx) trunate the list at this point.
1862  Else, walk the list from this point and use the deny permissions of this
1863  entry as a mask on all following allow entries. Finally, delete
1864  the Everyone DENY entry (we have applied it to everything possible).
1865
1866  In addition, in this pass we remove any DENY entries that have 
1867  no permissions (ie. they are a DENY nothing).
1868  ---------------------------------------------------------------------------
1869  Second pass - only deal with deny user entries.
1870
1871  DENY user1 (perms XXX)
1872
1873  new_perms = 0
1874  for all following allow group entries where user1 is in group
1875         new_perms |= group_perms;
1876
1877  user1 entry perms = new_perms & ~ XXX;
1878
1879  Convert the deny entry to an allow entry with the new perms and
1880  push to the end of the list. Note if the user was in no groups
1881  this maps to a specific allow nothing entry for this user.
1882
1883  The common case from the NT ACL choser (userX deny all) is
1884  optimised so we don't do the group lookup - we just map to
1885  an allow nothing entry.
1886
1887  What we're doing here is inferring the allow permissions the
1888  person setting the ACE on user1 wanted by looking at the allow
1889  permissions on the groups the user is currently in. This will
1890  be a snapshot, depending on group membership but is the best
1891  we can do and has the advantage of failing closed rather than
1892  open.
1893  ---------------------------------------------------------------------------
1894  Third pass - only deal with deny group entries.
1895
1896  DENY group1 (perms XXX)
1897
1898  for all following allow user entries where user is in group1
1899    user entry perms = user entry perms & ~ XXX;
1900
1901  If there is a group Everyone allow entry with permissions YYY,
1902  convert the group1 entry to an allow entry and modify its
1903  permissions to be :
1904
1905  new_perms = YYY & ~ XXX
1906
1907  and push to the end of the list.
1908
1909  If there is no group Everyone allow entry then convert the
1910  group1 entry to a allow nothing entry and push to the end of the list.
1911
1912  Note that the common case from the NT ACL choser (groupX deny all)
1913  cannot be optimised here as we need to modify user entries who are
1914  in the group to change them to a deny all also.
1915
1916  What we're doing here is modifying the allow permissions of
1917  user entries (which are more specific in POSIX ACLs) to mask
1918  out the explicit deny set on the group they are in. This will
1919  be a snapshot depending on current group membership but is the
1920  best we can do and has the advantage of failing closed rather
1921  than open.
1922  ---------------------------------------------------------------------------
1923  Fourth pass - cope with cumulative permissions.
1924
1925  for all allow user entries, if there exists an allow group entry with
1926  more permissive permissions, and the user is in that group, rewrite the
1927  allow user permissions to contain both sets of permissions.
1928
1929  Currently the code for this is #ifdef'ed out as these semantics make
1930  no sense to me. JRA.
1931  ---------------------------------------------------------------------------
1932
1933  Note we *MUST* do the deny user pass first as this will convert deny user
1934  entries into allow user entries which can then be processed by the deny
1935  group pass.
1936
1937  The above algorithm took a *lot* of thinking about - hence this
1938  explaination :-). JRA.
1939 ****************************************************************************/
1940
1941 /****************************************************************************
1942  Process a canon_ace list entries. This is very complex code. We need
1943  to go through and remove the "deny" permissions from any allow entry that matches
1944  the id of this entry. We have already refused any NT ACL that wasn't in correct
1945  order (DENY followed by ALLOW). If any allow entry ends up with zero permissions,
1946  we just remove it (to fail safe). We have already removed any duplicate ace
1947  entries. Treat an "Everyone" DENY_ACE as a special case - use it to mask all
1948  allow entries.
1949 ****************************************************************************/
1950
1951 static void process_deny_list( canon_ace **pp_ace_list )
1952 {
1953         canon_ace *ace_list = *pp_ace_list;
1954         canon_ace *curr_ace = NULL;
1955         canon_ace *curr_ace_next = NULL;
1956
1957         /* Pass 1 above - look for an Everyone, deny entry. */
1958
1959         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
1960                 canon_ace *allow_ace_p;
1961
1962                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
1963
1964                 if (curr_ace->attr != DENY_ACE)
1965                         continue;
1966
1967                 if (curr_ace->perms == (mode_t)0) {
1968
1969                         /* Deny nothing entry - delete. */
1970
1971                         DLIST_REMOVE(ace_list, curr_ace);
1972                         continue;
1973                 }
1974
1975                 if (!sid_equal(&curr_ace->trustee, &global_sid_World))
1976                         continue;
1977
1978                 /* JRATEST - assert. */
1979                 SMB_ASSERT(curr_ace->owner_type == WORLD_ACE);
1980
1981                 if (curr_ace->perms == ALL_ACE_PERMS) {
1982
1983                         /*
1984                          * Optimisation. This is a DENY_ALL to Everyone. Truncate the
1985                          * list at this point including this entry.
1986                          */
1987
1988                         canon_ace *prev_entry = curr_ace->prev;
1989
1990                         free_canon_ace_list( curr_ace );
1991                         if (prev_entry)
1992                                 prev_entry->next = NULL;
1993                         else {
1994                                 /* We deleted the entire list. */
1995                                 ace_list = NULL;
1996                         }
1997                         break;
1998                 }
1999
2000                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2001
2002                         /* 
2003                          * Only mask off allow entries.
2004                          */
2005
2006                         if (allow_ace_p->attr != ALLOW_ACE)
2007                                 continue;
2008
2009                         allow_ace_p->perms &= ~curr_ace->perms;
2010                 }
2011
2012                 /*
2013                  * Now it's been applied, remove it.
2014                  */
2015
2016                 DLIST_REMOVE(ace_list, curr_ace);
2017         }
2018
2019         /* Pass 2 above - deal with deny user entries. */
2020
2021         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2022                 mode_t new_perms = (mode_t)0;
2023                 canon_ace *allow_ace_p;
2024
2025                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2026
2027                 if (curr_ace->attr != DENY_ACE)
2028                         continue;
2029
2030                 if (curr_ace->owner_type != UID_ACE)
2031                         continue;
2032
2033                 if (curr_ace->perms == ALL_ACE_PERMS) {
2034
2035                         /*
2036                          * Optimisation - this is a deny everything to this user.
2037                          * Convert to an allow nothing and push to the end of the list.
2038                          */
2039
2040                         curr_ace->attr = ALLOW_ACE;
2041                         curr_ace->perms = (mode_t)0;
2042                         DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2043                         continue;
2044                 }
2045
2046                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2047
2048                         if (allow_ace_p->attr != ALLOW_ACE)
2049                                 continue;
2050
2051                         /* We process GID_ACE and WORLD_ACE entries only. */
2052
2053                         if (allow_ace_p->owner_type == UID_ACE)
2054                                 continue;
2055
2056                         if (uid_entry_in_group( curr_ace, allow_ace_p))
2057                                 new_perms |= allow_ace_p->perms;
2058                 }
2059
2060                 /*
2061                  * Convert to a allow entry, modify the perms and push to the end
2062                  * of the list.
2063                  */
2064
2065                 curr_ace->attr = ALLOW_ACE;
2066                 curr_ace->perms = (new_perms & ~curr_ace->perms);
2067                 DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2068         }
2069
2070         /* Pass 3 above - deal with deny group entries. */
2071
2072         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2073                 canon_ace *allow_ace_p;
2074                 canon_ace *allow_everyone_p = NULL;
2075
2076                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2077
2078                 if (curr_ace->attr != DENY_ACE)
2079                         continue;
2080
2081                 if (curr_ace->owner_type != GID_ACE)
2082                         continue;
2083
2084                 for (allow_ace_p = curr_ace->next; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2085
2086                         if (allow_ace_p->attr != ALLOW_ACE)
2087                                 continue;
2088
2089                         /* Store a pointer to the Everyone allow, if it exists. */
2090                         if (allow_ace_p->owner_type == WORLD_ACE)
2091                                 allow_everyone_p = allow_ace_p;
2092
2093                         /* We process UID_ACE entries only. */
2094
2095                         if (allow_ace_p->owner_type != UID_ACE)
2096                                 continue;
2097
2098                         /* Mask off the deny group perms. */
2099
2100                         if (uid_entry_in_group( allow_ace_p, curr_ace))
2101                                 allow_ace_p->perms &= ~curr_ace->perms;
2102                 }
2103
2104                 /*
2105                  * Convert the deny to an allow with the correct perms and
2106                  * push to the end of the list.
2107                  */
2108
2109                 curr_ace->attr = ALLOW_ACE;
2110                 if (allow_everyone_p)
2111                         curr_ace->perms = allow_everyone_p->perms & ~curr_ace->perms;
2112                 else
2113                         curr_ace->perms = (mode_t)0;
2114                 DLIST_DEMOTE(ace_list, curr_ace, canon_ace *);
2115         }
2116
2117         /* Doing this fourth pass allows Windows semantics to be layered
2118          * on top of POSIX semantics. I'm not sure if this is desirable.
2119          * For example, in W2K ACLs there is no way to say, "Group X no
2120          * access, user Y full access" if user Y is a member of group X.
2121          * This seems completely broken semantics to me.... JRA.
2122          */
2123
2124 #if 0
2125         /* Pass 4 above - deal with allow entries. */
2126
2127         for (curr_ace = ace_list; curr_ace; curr_ace = curr_ace_next) {
2128                 canon_ace *allow_ace_p;
2129
2130                 curr_ace_next = curr_ace->next; /* So we can't lose the link. */
2131
2132                 if (curr_ace->attr != ALLOW_ACE)
2133                         continue;
2134
2135                 if (curr_ace->owner_type != UID_ACE)
2136                         continue;
2137
2138                 for (allow_ace_p = ace_list; allow_ace_p; allow_ace_p = allow_ace_p->next) {
2139
2140                         if (allow_ace_p->attr != ALLOW_ACE)
2141                                 continue;
2142
2143                         /* We process GID_ACE entries only. */
2144
2145                         if (allow_ace_p->owner_type != GID_ACE)
2146                                 continue;
2147
2148                         /* OR in the group perms. */
2149
2150                         if (uid_entry_in_group( curr_ace, allow_ace_p))
2151                                 curr_ace->perms |= allow_ace_p->perms;
2152                 }
2153         }
2154 #endif
2155
2156         *pp_ace_list = ace_list;
2157 }
2158
2159 /****************************************************************************
2160  Create a default mode that will be used if a security descriptor entry has
2161  no user/group/world entries.
2162 ****************************************************************************/
2163
2164 static mode_t create_default_mode(files_struct *fsp, bool interitable_mode)
2165 {
2166         int snum = SNUM(fsp->conn);
2167         mode_t and_bits = (mode_t)0;
2168         mode_t or_bits = (mode_t)0;
2169         mode_t mode = interitable_mode
2170                 ? unix_mode( fsp->conn, FILE_ATTRIBUTE_ARCHIVE, fsp->fsp_name,
2171                              NULL )
2172                 : S_IRUSR;
2173
2174         if (fsp->is_directory)
2175                 mode |= (S_IWUSR|S_IXUSR);
2176
2177         /*
2178          * Now AND with the create mode/directory mode bits then OR with the
2179          * force create mode/force directory mode bits.
2180          */
2181
2182         if (fsp->is_directory) {
2183                 and_bits = lp_dir_security_mask(snum);
2184                 or_bits = lp_force_dir_security_mode(snum);
2185         } else {
2186                 and_bits = lp_security_mask(snum);
2187                 or_bits = lp_force_security_mode(snum);
2188         }
2189
2190         return ((mode & and_bits)|or_bits);
2191 }
2192
2193 /****************************************************************************
2194  Unpack a SEC_DESC into two canonical ace lists. We don't depend on this
2195  succeeding.
2196 ****************************************************************************/
2197
2198 static bool unpack_canon_ace(files_struct *fsp,
2199                                 SMB_STRUCT_STAT *pst,
2200                                 DOM_SID *pfile_owner_sid,
2201                                 DOM_SID *pfile_grp_sid,
2202                                 canon_ace **ppfile_ace,
2203                                 canon_ace **ppdir_ace,
2204                                 uint32 security_info_sent,
2205                                 const SEC_DESC *psd)
2206 {
2207         canon_ace *file_ace = NULL;
2208         canon_ace *dir_ace = NULL;
2209
2210         *ppfile_ace = NULL;
2211         *ppdir_ace = NULL;
2212
2213         if(security_info_sent == 0) {
2214                 DEBUG(0,("unpack_canon_ace: no security info sent !\n"));
2215                 return False;
2216         }
2217
2218         /*
2219          * If no DACL then this is a chown only security descriptor.
2220          */
2221
2222         if(!(security_info_sent & DACL_SECURITY_INFORMATION) || !psd->dacl)
2223                 return True;
2224
2225         /*
2226          * Now go through the DACL and create the canon_ace lists.
2227          */
2228
2229         if (!create_canon_ace_lists( fsp, pst, pfile_owner_sid, pfile_grp_sid,
2230                                                                 &file_ace, &dir_ace, psd->dacl))
2231                 return False;
2232
2233         if ((file_ace == NULL) && (dir_ace == NULL)) {
2234                 /* W2K traverse DACL set - ignore. */
2235                 return True;
2236         }
2237
2238         /*
2239          * Go through the canon_ace list and merge entries
2240          * belonging to identical users of identical allow or deny type.
2241          * We can do this as all deny entries come first, followed by
2242          * all allow entries (we have mandated this before accepting this acl).
2243          */
2244
2245         print_canon_ace_list( "file ace - before merge", file_ace);
2246         merge_aces( &file_ace );
2247
2248         print_canon_ace_list( "dir ace - before merge", dir_ace);
2249         merge_aces( &dir_ace );
2250
2251         /*
2252          * NT ACLs are order dependent. Go through the acl lists and
2253          * process DENY entries by masking the allow entries.
2254          */
2255
2256         print_canon_ace_list( "file ace - before deny", file_ace);
2257         process_deny_list( &file_ace);
2258
2259         print_canon_ace_list( "dir ace - before deny", dir_ace);
2260         process_deny_list( &dir_ace);
2261
2262         /*
2263          * A well formed POSIX file or default ACL has at least 3 entries, a 
2264          * SMB_ACL_USER_OBJ, SMB_ACL_GROUP_OBJ, SMB_ACL_OTHER_OBJ
2265          * and optionally a mask entry. Ensure this is the case.
2266          */
2267
2268         print_canon_ace_list( "file ace - before valid", file_ace);
2269
2270         /*
2271          * A default 3 element mode entry for a file should be r-- --- ---.
2272          * A default 3 element mode entry for a directory should be rwx --- ---.
2273          */
2274
2275         pst->st_ex_mode = create_default_mode(fsp, False);
2276
2277         if (!ensure_canon_entry_valid(&file_ace, fsp->conn->params, fsp->is_directory, pfile_owner_sid, pfile_grp_sid, pst, True)) {
2278                 free_canon_ace_list(file_ace);
2279                 free_canon_ace_list(dir_ace);
2280                 return False;
2281         }
2282
2283         print_canon_ace_list( "dir ace - before valid", dir_ace);
2284
2285         /*
2286          * A default inheritable 3 element mode entry for a directory should be the
2287          * mode Samba will use to create a file within. Ensure user rwx bits are set if
2288          * it's a directory.
2289          */
2290
2291         pst->st_ex_mode = create_default_mode(fsp, True);
2292
2293         if (dir_ace && !ensure_canon_entry_valid(&dir_ace, fsp->conn->params, fsp->is_directory, pfile_owner_sid, pfile_grp_sid, pst, True)) {
2294                 free_canon_ace_list(file_ace);
2295                 free_canon_ace_list(dir_ace);
2296                 return False;
2297         }
2298
2299         print_canon_ace_list( "file ace - return", file_ace);
2300         print_canon_ace_list( "dir ace - return", dir_ace);
2301
2302         *ppfile_ace = file_ace;
2303         *ppdir_ace = dir_ace;
2304         return True;
2305
2306 }
2307
2308 /******************************************************************************
2309  When returning permissions, try and fit NT display
2310  semantics if possible. Note the the canon_entries here must have been malloced.
2311  The list format should be - first entry = owner, followed by group and other user
2312  entries, last entry = other.
2313
2314  Note that this doesn't exactly match the NT semantics for an ACL. As POSIX entries
2315  are not ordered, and match on the most specific entry rather than walking a list,
2316  then a simple POSIX permission of rw-r--r-- should really map to 5 entries,
2317
2318  Entry 0: owner : deny all except read and write.
2319  Entry 1: owner : allow read and write.
2320  Entry 2: group : deny all except read.
2321  Entry 3: group : allow read.
2322  Entry 4: Everyone : allow read.
2323
2324  But NT cannot display this in their ACL editor !
2325 ********************************************************************************/
2326
2327 static void arrange_posix_perms(const char *filename, canon_ace **pp_list_head)
2328 {
2329         canon_ace *l_head = *pp_list_head;
2330         canon_ace *owner_ace = NULL;
2331         canon_ace *other_ace = NULL;
2332         canon_ace *ace = NULL;
2333
2334         for (ace = l_head; ace; ace = ace->next) {
2335                 if (ace->type == SMB_ACL_USER_OBJ)
2336                         owner_ace = ace;
2337                 else if (ace->type == SMB_ACL_OTHER) {
2338                         /* Last ace - this is "other" */
2339                         other_ace = ace;
2340                 }
2341         }
2342
2343         if (!owner_ace || !other_ace) {
2344                 DEBUG(0,("arrange_posix_perms: Invalid POSIX permissions for file %s, missing owner or other.\n",
2345                         filename ));
2346                 return;
2347         }
2348
2349         /*
2350          * The POSIX algorithm applies to owner first, and other last,
2351          * so ensure they are arranged in this order.
2352          */
2353
2354         if (owner_ace) {
2355                 DLIST_PROMOTE(l_head, owner_ace);
2356         }
2357
2358         if (other_ace) {
2359                 DLIST_DEMOTE(l_head, other_ace, canon_ace *);
2360         }
2361
2362         /* We have probably changed the head of the list. */
2363
2364         *pp_list_head = l_head;
2365 }
2366
2367 /****************************************************************************
2368  Create a linked list of canonical ACE entries.
2369 ****************************************************************************/
2370
2371 static canon_ace *canonicalise_acl(struct connection_struct *conn,
2372                                    const char *fname, SMB_ACL_T posix_acl,
2373                                    const SMB_STRUCT_STAT *psbuf,
2374                                    const DOM_SID *powner, const DOM_SID *pgroup, struct pai_val *pal, SMB_ACL_TYPE_T the_acl_type)
2375 {
2376         mode_t acl_mask = (S_IRUSR|S_IWUSR|S_IXUSR);
2377         canon_ace *l_head = NULL;
2378         canon_ace *ace = NULL;
2379         canon_ace *next_ace = NULL;
2380         int entry_id = SMB_ACL_FIRST_ENTRY;
2381         SMB_ACL_ENTRY_T entry;
2382         size_t ace_count;
2383
2384         while ( posix_acl && (SMB_VFS_SYS_ACL_GET_ENTRY(conn, posix_acl, entry_id, &entry) == 1)) {
2385                 SMB_ACL_TAG_T tagtype;
2386                 SMB_ACL_PERMSET_T permset;
2387                 DOM_SID sid;
2388                 posix_id unix_ug;
2389                 enum ace_owner owner_type;
2390
2391                 entry_id = SMB_ACL_NEXT_ENTRY;
2392
2393                 /* Is this a MASK entry ? */
2394                 if (SMB_VFS_SYS_ACL_GET_TAG_TYPE(conn, entry, &tagtype) == -1)
2395                         continue;
2396
2397                 if (SMB_VFS_SYS_ACL_GET_PERMSET(conn, entry, &permset) == -1)
2398                         continue;
2399
2400                 /* Decide which SID to use based on the ACL type. */
2401                 switch(tagtype) {
2402                         case SMB_ACL_USER_OBJ:
2403                                 /* Get the SID from the owner. */
2404                                 sid_copy(&sid, powner);
2405                                 unix_ug.uid = psbuf->st_ex_uid;
2406                                 owner_type = UID_ACE;
2407                                 break;
2408                         case SMB_ACL_USER:
2409                                 {
2410                                         uid_t *puid = (uid_t *)SMB_VFS_SYS_ACL_GET_QUALIFIER(conn, entry);
2411                                         if (puid == NULL) {
2412                                                 DEBUG(0,("canonicalise_acl: Failed to get uid.\n"));
2413                                                 continue;
2414                                         }
2415                                         /*
2416                                          * A SMB_ACL_USER entry for the owner is shadowed by the
2417                                          * SMB_ACL_USER_OBJ entry and Windows also cannot represent
2418                                          * that entry, so we ignore it. We also don't create such
2419                                          * entries out of the blue when setting ACLs, so a get/set
2420                                          * cycle will drop them.
2421                                          */
2422                                         if (the_acl_type == SMB_ACL_TYPE_ACCESS && *puid == psbuf->st_ex_uid) {
2423                                                 SMB_VFS_SYS_ACL_FREE_QUALIFIER(conn, (void *)puid,tagtype);
2424                                                 continue;
2425                                         }
2426                                         uid_to_sid( &sid, *puid);
2427                                         unix_ug.uid = *puid;
2428                                         owner_type = UID_ACE;
2429                                         SMB_VFS_SYS_ACL_FREE_QUALIFIER(conn, (void *)puid,tagtype);
2430                                         break;
2431                                 }
2432                         case SMB_ACL_GROUP_OBJ:
2433                                 /* Get the SID from the owning group. */
2434                                 sid_copy(&sid, pgroup);
2435                                 unix_ug.gid = psbuf->st_ex_gid;
2436                                 owner_type = GID_ACE;
2437                                 break;
2438                         case SMB_ACL_GROUP:
2439                                 {
2440                                         gid_t *pgid = (gid_t *)SMB_VFS_SYS_ACL_GET_QUALIFIER(conn, entry);
2441                                         if (pgid == NULL) {
2442                                                 DEBUG(0,("canonicalise_acl: Failed to get gid.\n"));
2443                                                 continue;
2444                                         }
2445                                         gid_to_sid( &sid, *pgid);
2446                                         unix_ug.gid = *pgid;
2447                                         owner_type = GID_ACE;
2448                                         SMB_VFS_SYS_ACL_FREE_QUALIFIER(conn, (void *)pgid,tagtype);
2449                                         break;
2450                                 }
2451                         case SMB_ACL_MASK:
2452                                 acl_mask = convert_permset_to_mode_t(conn, permset);
2453                                 continue; /* Don't count the mask as an entry. */
2454                         case SMB_ACL_OTHER:
2455                                 /* Use the Everyone SID */
2456                                 sid = global_sid_World;
2457                                 unix_ug.world = -1;
2458                                 owner_type = WORLD_ACE;
2459                                 break;
2460                         default:
2461                                 DEBUG(0,("canonicalise_acl: Unknown tagtype %u\n", (unsigned int)tagtype));
2462                                 continue;
2463                 }
2464
2465                 /*
2466                  * Add this entry to the list.
2467                  */
2468
2469                 if ((ace = SMB_MALLOC_P(canon_ace)) == NULL)
2470                         goto fail;
2471
2472                 ZERO_STRUCTP(ace);
2473                 ace->type = tagtype;
2474                 ace->perms = convert_permset_to_mode_t(conn, permset);
2475                 ace->attr = ALLOW_ACE;
2476                 ace->trustee = sid;
2477                 ace->unix_ug = unix_ug;
2478                 ace->owner_type = owner_type;
2479                 ace->ace_flags = get_pai_flags(pal, ace, (the_acl_type == SMB_ACL_TYPE_DEFAULT));
2480
2481                 DLIST_ADD(l_head, ace);
2482         }
2483
2484         /*
2485          * This next call will ensure we have at least a user/group/world set.
2486          */
2487
2488         if (!ensure_canon_entry_valid(&l_head, conn->params,
2489                                       S_ISDIR(psbuf->st_ex_mode), powner, pgroup,
2490                                       psbuf, False))
2491                 goto fail;
2492
2493         /*
2494          * Now go through the list, masking the permissions with the
2495          * acl_mask. Ensure all DENY Entries are at the start of the list.
2496          */
2497
2498         DEBUG(10,("canonicalise_acl: %s ace entries before arrange :\n", the_acl_type == SMB_ACL_TYPE_ACCESS ? "Access" : "Default" ));
2499
2500         for ( ace_count = 0, ace = l_head; ace; ace = next_ace, ace_count++) {
2501                 next_ace = ace->next;
2502
2503                 /* Masks are only applied to entries other than USER_OBJ and OTHER. */
2504                 if (ace->type != SMB_ACL_OTHER && ace->type != SMB_ACL_USER_OBJ)
2505                         ace->perms &= acl_mask;
2506
2507                 if (ace->perms == 0) {
2508                         DLIST_PROMOTE(l_head, ace);
2509                 }
2510
2511                 if( DEBUGLVL( 10 ) ) {
2512                         print_canon_ace(ace, ace_count);
2513                 }
2514         }
2515
2516         arrange_posix_perms(fname,&l_head );
2517
2518         print_canon_ace_list( "canonicalise_acl: ace entries after arrange", l_head );
2519
2520         return l_head;
2521
2522   fail:
2523
2524         free_canon_ace_list(l_head);
2525         return NULL;
2526 }
2527
2528 /****************************************************************************
2529  Check if the current user group list contains a given group.
2530 ****************************************************************************/
2531
2532 static bool current_user_in_group(gid_t gid)
2533 {
2534         int i;
2535
2536         for (i = 0; i < current_user.ut.ngroups; i++) {
2537                 if (current_user.ut.groups[i] == gid) {
2538                         return True;
2539                 }
2540         }
2541
2542         return False;
2543 }
2544
2545 /****************************************************************************
2546  Should we override a deny ? Check 'acl group control' and 'dos filemode'.
2547 ****************************************************************************/
2548
2549 static bool acl_group_override(connection_struct *conn,
2550                                 const SMB_STRUCT_STAT *psbuf,
2551                                 const char *fname)
2552 {
2553         if ((errno != EPERM) && (errno != EACCES)) {
2554                 return false;
2555         }
2556
2557         /* file primary group == user primary or supplementary group */
2558         if (lp_acl_group_control(SNUM(conn)) &&
2559                         current_user_in_group(psbuf->st_ex_gid)) {
2560                 return true;
2561         }
2562
2563         /* user has writeable permission */
2564         if (lp_dos_filemode(SNUM(conn)) &&
2565                         can_write_to_file(conn, fname, psbuf)) {
2566                 return true;
2567         }
2568
2569         return false;
2570 }
2571
2572 /****************************************************************************
2573  Attempt to apply an ACL to a file or directory.
2574 ****************************************************************************/
2575
2576 static bool set_canon_ace_list(files_struct *fsp,
2577                                 canon_ace *the_ace,
2578                                 bool default_ace,
2579                                 const SMB_STRUCT_STAT *psbuf,
2580                                 bool *pacl_set_support)
2581 {
2582         connection_struct *conn = fsp->conn;
2583         bool ret = False;
2584         SMB_ACL_T the_acl = SMB_VFS_SYS_ACL_INIT(conn, (int)count_canon_ace_list(the_ace) + 1);
2585         canon_ace *p_ace;
2586         int i;
2587         SMB_ACL_ENTRY_T mask_entry;
2588         bool got_mask_entry = False;
2589         SMB_ACL_PERMSET_T mask_permset;
2590         SMB_ACL_TYPE_T the_acl_type = (default_ace ? SMB_ACL_TYPE_DEFAULT : SMB_ACL_TYPE_ACCESS);
2591         bool needs_mask = False;
2592         mode_t mask_perms = 0;
2593
2594 #if defined(POSIX_ACL_NEEDS_MASK)
2595         /* HP-UX always wants to have a mask (called "class" there). */
2596         needs_mask = True;
2597 #endif
2598
2599         if (the_acl == NULL) {
2600
2601                 if (!no_acl_syscall_error(errno)) {
2602                         /*
2603                          * Only print this error message if we have some kind of ACL
2604                          * support that's not working. Otherwise we would always get this.
2605                          */
2606                         DEBUG(0,("set_canon_ace_list: Unable to init %s ACL. (%s)\n",
2607                                 default_ace ? "default" : "file", strerror(errno) ));
2608                 }
2609                 *pacl_set_support = False;
2610                 return False;
2611         }
2612
2613         if( DEBUGLVL( 10 )) {
2614                 dbgtext("set_canon_ace_list: setting ACL:\n");
2615                 for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) {
2616                         print_canon_ace( p_ace, i);
2617                 }
2618         }
2619
2620         for (i = 0, p_ace = the_ace; p_ace; p_ace = p_ace->next, i++ ) {
2621                 SMB_ACL_ENTRY_T the_entry;
2622                 SMB_ACL_PERMSET_T the_permset;
2623
2624                 /*
2625                  * ACLs only "need" an ACL_MASK entry if there are any named user or
2626                  * named group entries. But if there is an ACL_MASK entry, it applies
2627                  * to ACL_USER, ACL_GROUP, and ACL_GROUP_OBJ entries. Set the mask
2628                  * so that it doesn't deny (i.e., mask off) any permissions.
2629                  */
2630
2631                 if (p_ace->type == SMB_ACL_USER || p_ace->type == SMB_ACL_GROUP) {
2632                         needs_mask = True;
2633                         mask_perms |= p_ace->perms;
2634                 } else if (p_ace->type == SMB_ACL_GROUP_OBJ) {
2635                         mask_perms |= p_ace->perms;
2636                 }
2637
2638                 /*
2639                  * Get the entry for this ACE.
2640                  */
2641
2642                 if (SMB_VFS_SYS_ACL_CREATE_ENTRY(conn, &the_acl, &the_entry) == -1) {
2643                         DEBUG(0,("set_canon_ace_list: Failed to create entry %d. (%s)\n",
2644                                 i, strerror(errno) ));
2645                         goto fail;
2646                 }
2647
2648                 if (p_ace->type == SMB_ACL_MASK) {
2649                         mask_entry = the_entry;
2650                         got_mask_entry = True;
2651                 }
2652
2653                 /*
2654                  * Ok - we now know the ACL calls should be working, don't
2655                  * allow fallback to chmod.
2656                  */
2657
2658                 *pacl_set_support = True;
2659
2660                 /*
2661                  * Initialise the entry from the canon_ace.
2662                  */
2663
2664                 /*
2665                  * First tell the entry what type of ACE this is.
2666                  */
2667
2668                 if (SMB_VFS_SYS_ACL_SET_TAG_TYPE(conn, the_entry, p_ace->type) == -1) {
2669                         DEBUG(0,("set_canon_ace_list: Failed to set tag type on entry %d. (%s)\n",
2670                                 i, strerror(errno) ));
2671                         goto fail;
2672                 }
2673
2674                 /*
2675                  * Only set the qualifier (user or group id) if the entry is a user
2676                  * or group id ACE.
2677                  */
2678
2679                 if ((p_ace->type == SMB_ACL_USER) || (p_ace->type == SMB_ACL_GROUP)) {
2680                         if (SMB_VFS_SYS_ACL_SET_QUALIFIER(conn, the_entry,(void *)&p_ace->unix_ug.uid) == -1) {
2681                                 DEBUG(0,("set_canon_ace_list: Failed to set qualifier on entry %d. (%s)\n",
2682                                         i, strerror(errno) ));
2683                                 goto fail;
2684                         }
2685                 }
2686
2687                 /*
2688                  * Convert the mode_t perms in the canon_ace to a POSIX permset.
2689                  */
2690
2691                 if (SMB_VFS_SYS_ACL_GET_PERMSET(conn, the_entry, &the_permset) == -1) {
2692                         DEBUG(0,("set_canon_ace_list: Failed to get permset on entry %d. (%s)\n",
2693                                 i, strerror(errno) ));
2694                         goto fail;
2695                 }
2696
2697                 if (map_acl_perms_to_permset(conn, p_ace->perms, &the_permset) == -1) {
2698                         DEBUG(0,("set_canon_ace_list: Failed to create permset for mode (%u) on entry %d. (%s)\n",
2699                                 (unsigned int)p_ace->perms, i, strerror(errno) ));
2700                         goto fail;
2701                 }
2702
2703                 /*
2704                  * ..and apply them to the entry.
2705                  */
2706
2707                 if (SMB_VFS_SYS_ACL_SET_PERMSET(conn, the_entry, the_permset) == -1) {
2708                         DEBUG(0,("set_canon_ace_list: Failed to add permset on entry %d. (%s)\n",
2709                                 i, strerror(errno) ));
2710                         goto fail;
2711                 }
2712
2713                 if( DEBUGLVL( 10 ))
2714                         print_canon_ace( p_ace, i);
2715
2716         }
2717
2718         if (needs_mask && !got_mask_entry) {
2719                 if (SMB_VFS_SYS_ACL_CREATE_ENTRY(conn, &the_acl, &mask_entry) == -1) {
2720                         DEBUG(0,("set_canon_ace_list: Failed to create mask entry. (%s)\n", strerror(errno) ));
2721                         goto fail;
2722                 }
2723
2724                 if (SMB_VFS_SYS_ACL_SET_TAG_TYPE(conn, mask_entry, SMB_ACL_MASK) == -1) {
2725                         DEBUG(0,("set_canon_ace_list: Failed to set tag type on mask entry. (%s)\n",strerror(errno) ));
2726                         goto fail;
2727                 }
2728
2729                 if (SMB_VFS_SYS_ACL_GET_PERMSET(conn, mask_entry, &mask_permset) == -1) {
2730                         DEBUG(0,("set_canon_ace_list: Failed to get mask permset. (%s)\n", strerror(errno) ));
2731                         goto fail;
2732                 }
2733
2734                 if (map_acl_perms_to_permset(conn, S_IRUSR|S_IWUSR|S_IXUSR, &mask_permset) == -1) {
2735                         DEBUG(0,("set_canon_ace_list: Failed to create mask permset. (%s)\n", strerror(errno) ));
2736                         goto fail;
2737                 }
2738
2739                 if (SMB_VFS_SYS_ACL_SET_PERMSET(conn, mask_entry, mask_permset) == -1) {
2740                         DEBUG(0,("set_canon_ace_list: Failed to add mask permset. (%s)\n", strerror(errno) ));
2741                         goto fail;
2742                 }
2743         }
2744
2745         /*
2746          * Finally apply it to the file or directory.
2747          */
2748
2749         if(default_ace || fsp->is_directory || fsp->fh->fd == -1) {
2750                 if (SMB_VFS_SYS_ACL_SET_FILE(conn, fsp->fsp_name, the_acl_type, the_acl) == -1) {
2751                         /*
2752                          * Some systems allow all the above calls and only fail with no ACL support
2753                          * when attempting to apply the acl. HPUX with HFS is an example of this. JRA.
2754                          */
2755                         if (no_acl_syscall_error(errno)) {
2756                                 *pacl_set_support = False;
2757                         }
2758
2759                         if (acl_group_override(conn, psbuf, fsp->fsp_name)) {
2760                                 int sret;
2761
2762                                 DEBUG(5,("set_canon_ace_list: acl group control on and current user in file %s primary group.\n",
2763                                         fsp->fsp_name ));
2764
2765                                 become_root();
2766                                 sret = SMB_VFS_SYS_ACL_SET_FILE(conn, fsp->fsp_name, the_acl_type, the_acl);
2767                                 unbecome_root();
2768                                 if (sret == 0) {
2769                                         ret = True;     
2770                                 }
2771                         }
2772
2773                         if (ret == False) {
2774                                 DEBUG(2,("set_canon_ace_list: sys_acl_set_file type %s failed for file %s (%s).\n",
2775                                                 the_acl_type == SMB_ACL_TYPE_DEFAULT ? "directory default" : "file",
2776                                                 fsp->fsp_name, strerror(errno) ));
2777                                 goto fail;
2778                         }
2779                 }
2780         } else {
2781                 if (SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl) == -1) {
2782                         /*
2783                          * Some systems allow all the above calls and only fail with no ACL support
2784                          * when attempting to apply the acl. HPUX with HFS is an example of this. JRA.
2785                          */
2786                         if (no_acl_syscall_error(errno)) {
2787                                 *pacl_set_support = False;
2788                         }
2789
2790                         if (acl_group_override(conn, psbuf, fsp->fsp_name)) {
2791                                 int sret;
2792
2793                                 DEBUG(5,("set_canon_ace_list: acl group control on and current user in file %s primary group.\n",
2794                                         fsp->fsp_name ));
2795
2796                                 become_root();
2797                                 sret = SMB_VFS_SYS_ACL_SET_FD(fsp, the_acl);
2798                                 unbecome_root();
2799                                 if (sret == 0) {
2800                                         ret = True;
2801                                 }
2802                         }
2803
2804                         if (ret == False) {
2805                                 DEBUG(2,("set_canon_ace_list: sys_acl_set_file failed for file %s (%s).\n",
2806                                                 fsp->fsp_name, strerror(errno) ));
2807                                 goto fail;
2808                         }
2809                 }
2810         }
2811
2812         ret = True;
2813
2814   fail:
2815
2816         if (the_acl != NULL) {
2817                 SMB_VFS_SYS_ACL_FREE_ACL(conn, the_acl);
2818         }
2819
2820         return ret;
2821 }
2822
2823 /****************************************************************************
2824  Find a particular canon_ace entry.
2825 ****************************************************************************/
2826
2827 static struct canon_ace *canon_ace_entry_for(struct canon_ace *list, SMB_ACL_TAG_T type, posix_id *id)
2828 {
2829         while (list) {
2830                 if (list->type == type && ((type != SMB_ACL_USER && type != SMB_ACL_GROUP) ||
2831                                 (type == SMB_ACL_USER  && id && id->uid == list->unix_ug.uid) ||
2832                                 (type == SMB_ACL_GROUP && id && id->gid == list->unix_ug.gid)))
2833                         break;
2834                 list = list->next;
2835         }
2836         return list;
2837 }
2838
2839 /****************************************************************************
2840  
2841 ****************************************************************************/
2842
2843 SMB_ACL_T free_empty_sys_acl(connection_struct *conn, SMB_ACL_T the_acl)
2844 {
2845         SMB_ACL_ENTRY_T entry;
2846
2847         if (!the_acl)
2848                 return NULL;
2849         if (SMB_VFS_SYS_ACL_GET_ENTRY(conn, the_acl, SMB_ACL_FIRST_ENTRY, &entry) != 1) {
2850                 SMB_VFS_SYS_ACL_FREE_ACL(conn, the_acl);
2851                 return NULL;
2852         }
2853         return the_acl;
2854 }
2855
2856 /****************************************************************************
2857  Convert a canon_ace to a generic 3 element permission - if possible.
2858 ****************************************************************************/
2859
2860 #define MAP_PERM(p,mask,result) (((p) & (mask)) ? (result) : 0 )
2861
2862 static bool convert_canon_ace_to_posix_perms( files_struct *fsp, canon_ace *file_ace_list, mode_t *posix_perms)
2863 {
2864         int snum = SNUM(fsp->conn);
2865         size_t ace_count = count_canon_ace_list(file_ace_list);
2866         canon_ace *ace_p;
2867         canon_ace *owner_ace = NULL;
2868         canon_ace *group_ace = NULL;
2869         canon_ace *other_ace = NULL;
2870         mode_t and_bits;
2871         mode_t or_bits;
2872
2873         if (ace_count != 3) {
2874                 DEBUG(3,("convert_canon_ace_to_posix_perms: Too many ACE entries for file %s to convert to \
2875 posix perms.\n", fsp->fsp_name ));
2876                 return False;
2877         }
2878
2879         for (ace_p = file_ace_list; ace_p; ace_p = ace_p->next) {
2880                 if (ace_p->owner_type == UID_ACE)
2881                         owner_ace = ace_p;
2882                 else if (ace_p->owner_type == GID_ACE)
2883                         group_ace = ace_p;
2884                 else if (ace_p->owner_type == WORLD_ACE)
2885                         other_ace = ace_p;
2886         }
2887
2888         if (!owner_ace || !group_ace || !other_ace) {
2889                 DEBUG(3,("convert_canon_ace_to_posix_perms: Can't get standard entries for file %s.\n",
2890                                 fsp->fsp_name ));
2891                 return False;
2892         }
2893
2894         *posix_perms = (mode_t)0;
2895
2896         *posix_perms |= owner_ace->perms;
2897         *posix_perms |= MAP_PERM(group_ace->perms, S_IRUSR, S_IRGRP);
2898         *posix_perms |= MAP_PERM(group_ace->perms, S_IWUSR, S_IWGRP);
2899         *posix_perms |= MAP_PERM(group_ace->perms, S_IXUSR, S_IXGRP);
2900         *posix_perms |= MAP_PERM(other_ace->perms, S_IRUSR, S_IROTH);
2901         *posix_perms |= MAP_PERM(other_ace->perms, S_IWUSR, S_IWOTH);
2902         *posix_perms |= MAP_PERM(other_ace->perms, S_IXUSR, S_IXOTH);
2903
2904         /* The owner must have at least read access. */
2905
2906         *posix_perms |= S_IRUSR;
2907         if (fsp->is_directory)
2908                 *posix_perms |= (S_IWUSR|S_IXUSR);
2909
2910         /* If requested apply the masks. */
2911
2912         /* Get the initial bits to apply. */
2913
2914         if (fsp->is_directory) {
2915                 and_bits = lp_dir_security_mask(snum);
2916                 or_bits = lp_force_dir_security_mode(snum);
2917         } else {
2918                 and_bits = lp_security_mask(snum);
2919                 or_bits = lp_force_security_mode(snum);
2920         }
2921
2922         *posix_perms = (((*posix_perms) & and_bits)|or_bits);
2923
2924         DEBUG(10,("convert_canon_ace_to_posix_perms: converted u=%o,g=%o,w=%o to perm=0%o for file %s.\n",
2925                 (int)owner_ace->perms, (int)group_ace->perms, (int)other_ace->perms, (int)*posix_perms,
2926                 fsp->fsp_name ));
2927
2928         return True;
2929 }
2930
2931 /****************************************************************************
2932   Incoming NT ACLs on a directory can be split into a default POSIX acl (CI|OI|IO) and
2933   a normal POSIX acl. Win2k needs these split acls re-merging into one ACL
2934   with CI|OI set so it is inherited and also applies to the directory.
2935   Based on code from "Jim McDonough" <jmcd@us.ibm.com>.
2936 ****************************************************************************/
2937
2938 static size_t merge_default_aces( SEC_ACE *nt_ace_list, size_t num_aces)
2939 {
2940         size_t i, j;
2941
2942         for (i = 0; i < num_aces; i++) {
2943                 for (j = i+1; j < num_aces; j++) {
2944                         uint32 i_flags_ni = (nt_ace_list[i].flags & ~SEC_ACE_FLAG_INHERITED_ACE);
2945                         uint32 j_flags_ni = (nt_ace_list[j].flags & ~SEC_ACE_FLAG_INHERITED_ACE);
2946                         bool i_inh = (nt_ace_list[i].flags & SEC_ACE_FLAG_INHERITED_ACE) ? True : False;
2947                         bool j_inh = (nt_ace_list[j].flags & SEC_ACE_FLAG_INHERITED_ACE) ? True : False;
2948
2949                         /* We know the lower number ACE's are file entries. */
2950                         if ((nt_ace_list[i].type == nt_ace_list[j].type) &&
2951                                 (nt_ace_list[i].size == nt_ace_list[j].size) &&
2952                                 (nt_ace_list[i].access_mask == nt_ace_list[j].access_mask) &&
2953                                 sid_equal(&nt_ace_list[i].trustee, &nt_ace_list[j].trustee) &&
2954                                 (i_inh == j_inh) &&
2955                                 (i_flags_ni == 0) &&
2956                                 (j_flags_ni == (SEC_ACE_FLAG_OBJECT_INHERIT|
2957                                                   SEC_ACE_FLAG_CONTAINER_INHERIT|
2958                                                   SEC_ACE_FLAG_INHERIT_ONLY))) {
2959                                 /*
2960                                  * W2K wants to have access allowed zero access ACE's
2961                                  * at the end of the list. If the mask is zero, merge
2962                                  * the non-inherited ACE onto the inherited ACE.
2963                                  */
2964
2965                                 if (nt_ace_list[i].access_mask == 0) {
2966                                         nt_ace_list[j].flags = SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
2967                                                                 (i_inh ? SEC_ACE_FLAG_INHERITED_ACE : 0);
2968                                         if (num_aces - i - 1 > 0)
2969                                                 memmove(&nt_ace_list[i], &nt_ace_list[i+1], (num_aces-i-1) *
2970                                                                 sizeof(SEC_ACE));
2971
2972                                         DEBUG(10,("merge_default_aces: Merging zero access ACE %u onto ACE %u.\n",
2973                                                 (unsigned int)i, (unsigned int)j ));
2974                                 } else {
2975                                         /*
2976                                          * These are identical except for the flags.
2977                                          * Merge the inherited ACE onto the non-inherited ACE.
2978                                          */
2979
2980                                         nt_ace_list[i].flags = SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT|
2981                                                                 (i_inh ? SEC_ACE_FLAG_INHERITED_ACE : 0);
2982                                         if (num_aces - j - 1 > 0)
2983                                                 memmove(&nt_ace_list[j], &nt_ace_list[j+1], (num_aces-j-1) *
2984                                                                 sizeof(SEC_ACE));
2985
2986                                         DEBUG(10,("merge_default_aces: Merging ACE %u onto ACE %u.\n",
2987                                                 (unsigned int)j, (unsigned int)i ));
2988                                 }
2989                                 num_aces--;
2990                                 break;
2991                         }
2992                 }
2993         }
2994
2995         return num_aces;
2996 }
2997
2998 /*
2999  * Add or Replace ACE entry.
3000  * In some cases we need to add a specific ACE for compatibility reasons.
3001  * When doing that we must make sure we are not actually creating a duplicate
3002  * entry. So we need to search whether an ACE entry already exist and eventually
3003  * replacce the access mask, or add a completely new entry if none was found.
3004  *
3005  * This function assumes the array has enough space to add a new entry without
3006  * any reallocation of memory.
3007  */
3008
3009 static void add_or_replace_ace(SEC_ACE *nt_ace_list, size_t *num_aces,
3010                                 const DOM_SID *sid, enum security_ace_type type,
3011                                 uint32_t mask, uint8_t flags)
3012 {
3013         int i;
3014
3015         /* first search for a duplicate */
3016         for (i = 0; i < *num_aces; i++) {
3017                 if (sid_equal(&nt_ace_list[i].trustee, sid) &&
3018                     (nt_ace_list[i].flags == flags)) break;
3019         }
3020
3021         if (i < *num_aces) { /* found */
3022                 nt_ace_list[i].type = type;
3023                 nt_ace_list[i].access_mask = mask;
3024                 DEBUG(10, ("Replacing ACE %d with SID %s and flags %02x\n",
3025                            i, sid_string_dbg(sid), flags));
3026                 return;
3027         }
3028
3029         /* not found, append it */
3030         init_sec_ace(&nt_ace_list[(*num_aces)++], sid, type, mask, flags);
3031 }
3032
3033
3034 /****************************************************************************
3035  Reply to query a security descriptor from an fsp. If it succeeds it allocates
3036  the space for the return elements and returns the size needed to return the
3037  security descriptor. This should be the only external function needed for
3038  the UNIX style get ACL.
3039 ****************************************************************************/
3040
3041 static NTSTATUS posix_get_nt_acl_common(struct connection_struct *conn,
3042                                       const char *name,
3043                                       const SMB_STRUCT_STAT *sbuf,
3044                                       struct pai_val *pal,
3045                                       SMB_ACL_T posix_acl,
3046                                       SMB_ACL_T def_acl,
3047                                       uint32_t security_info,
3048                                       SEC_DESC **ppdesc)
3049 {
3050         DOM_SID owner_sid;
3051         DOM_SID group_sid;
3052         size_t sd_size = 0;
3053         SEC_ACL *psa = NULL;
3054         size_t num_acls = 0;
3055         size_t num_def_acls = 0;
3056         size_t num_aces = 0;
3057         canon_ace *file_ace = NULL;
3058         canon_ace *dir_ace = NULL;
3059         SEC_ACE *nt_ace_list = NULL;
3060         size_t num_profile_acls = 0;
3061         DOM_SID orig_owner_sid;
3062         SEC_DESC *psd = NULL;
3063         int i;
3064
3065         /*
3066          * Get the owner, group and world SIDs.
3067          */
3068
3069         create_file_sids(sbuf, &owner_sid, &group_sid);
3070
3071         if (lp_profile_acls(SNUM(conn))) {
3072                 /* For WXP SP1 the owner must be administrators. */
3073                 sid_copy(&orig_owner_sid, &owner_sid);
3074                 sid_copy(&owner_sid, &global_sid_Builtin_Administrators);
3075                 sid_copy(&group_sid, &global_sid_Builtin_Users);
3076                 num_profile_acls = 3;
3077         }
3078
3079         if ((security_info & DACL_SECURITY_INFORMATION) && !(security_info & PROTECTED_DACL_SECURITY_INFORMATION)) {
3080
3081                 /*
3082                  * In the optimum case Creator Owner and Creator Group would be used for
3083                  * the ACL_USER_OBJ and ACL_GROUP_OBJ entries, respectively, but this
3084                  * would lead to usability problems under Windows: The Creator entries
3085                  * are only available in browse lists of directories and not for files;
3086                  * additionally the identity of the owning group couldn't be determined.
3087                  * We therefore use those identities only for Default ACLs. 
3088                  */
3089
3090                 /* Create the canon_ace lists. */
3091                 file_ace = canonicalise_acl(conn, name, posix_acl, sbuf,
3092                                             &owner_sid, &group_sid, pal,
3093                                             SMB_ACL_TYPE_ACCESS);
3094
3095                 /* We must have *some* ACLS. */
3096         
3097                 if (count_canon_ace_list(file_ace) == 0) {
3098                         DEBUG(0,("get_nt_acl : No ACLs on file (%s) !\n", name));
3099                         goto done;
3100                 }
3101
3102                 if (S_ISDIR(sbuf->st_ex_mode) && def_acl) {
3103                         dir_ace = canonicalise_acl(conn, name, def_acl,
3104                                                    sbuf,
3105                                                    &global_sid_Creator_Owner,
3106                                                    &global_sid_Creator_Group,
3107                                                    pal, SMB_ACL_TYPE_DEFAULT);
3108                 }
3109
3110                 /*
3111                  * Create the NT ACE list from the canonical ace lists.
3112                  */
3113
3114                 {
3115                         canon_ace *ace;
3116                         enum security_ace_type nt_acl_type;
3117
3118                         if (nt4_compatible_acls() && dir_ace) {
3119                                 /*
3120                                  * NT 4 chokes if an ACL contains an INHERIT_ONLY entry
3121                                  * but no non-INHERIT_ONLY entry for one SID. So we only
3122                                  * remove entries from the Access ACL if the
3123                                  * corresponding Default ACL entries have also been
3124                                  * removed. ACEs for CREATOR-OWNER and CREATOR-GROUP
3125                                  * are exceptions. We can do nothing
3126                                  * intelligent if the Default ACL contains entries that
3127                                  * are not also contained in the Access ACL, so this
3128                                  * case will still fail under NT 4.
3129                                  */
3130
3131                                 ace = canon_ace_entry_for(dir_ace, SMB_ACL_OTHER, NULL);
3132                                 if (ace && !ace->perms) {
3133                                         DLIST_REMOVE(dir_ace, ace);
3134                                         SAFE_FREE(ace);
3135
3136                                         ace = canon_ace_entry_for(file_ace, SMB_ACL_OTHER, NULL);
3137                                         if (ace && !ace->perms) {
3138                                                 DLIST_REMOVE(file_ace, ace);
3139                                                 SAFE_FREE(ace);
3140                                         }
3141                                 }
3142
3143                                 /*
3144                                  * WinNT doesn't usually have Creator Group
3145                                  * in browse lists, so we send this entry to
3146                                  * WinNT even if it contains no relevant
3147                                  * permissions. Once we can add
3148                                  * Creator Group to browse lists we can
3149                                  * re-enable this.
3150                                  */
3151
3152 #if 0
3153                                 ace = canon_ace_entry_for(dir_ace, SMB_ACL_GROUP_OBJ, NULL);
3154                                 if (ace && !ace->perms) {
3155                                         DLIST_REMOVE(dir_ace, ace);
3156                                         SAFE_FREE(ace);
3157                                 }
3158 #endif
3159
3160                                 ace = canon_ace_entry_for(file_ace, SMB_ACL_GROUP_OBJ, NULL);
3161                                 if (ace && !ace->perms) {
3162                                         DLIST_REMOVE(file_ace, ace);
3163                                         SAFE_FREE(ace);
3164                                 }
3165                         }
3166
3167                         num_acls = count_canon_ace_list(file_ace);
3168                         num_def_acls = count_canon_ace_list(dir_ace);
3169
3170                         /* Allocate the ace list. */
3171                         if ((nt_ace_list = SMB_MALLOC_ARRAY(SEC_ACE,num_acls + num_profile_acls + num_def_acls)) == NULL) {
3172                                 DEBUG(0,("get_nt_acl: Unable to malloc space for nt_ace_list.\n"));
3173                                 goto done;
3174                         }
3175
3176                         memset(nt_ace_list, '\0', (num_acls + num_def_acls) * sizeof(SEC_ACE) );
3177
3178                         /*
3179                          * Create the NT ACE list from the canonical ace lists.
3180                          */
3181
3182                         for (ace = file_ace; ace != NULL; ace = ace->next) {
3183                                 uint32_t acc = map_canon_ace_perms(SNUM(conn),
3184                                                 &nt_acl_type,
3185                                                 ace->perms,
3186                                                 S_ISDIR(sbuf->st_ex_mode));
3187                                 init_sec_ace(&nt_ace_list[num_aces++],
3188                                         &ace->trustee,
3189                                         nt_acl_type,
3190                                         acc,
3191                                         ace->ace_flags);
3192                         }
3193
3194                         /* The User must have access to a profile share - even
3195                          * if we can't map the SID. */
3196                         if (lp_profile_acls(SNUM(conn))) {
3197                                 add_or_replace_ace(nt_ace_list, &num_aces,
3198                                                    &global_sid_Builtin_Users,
3199                                                    SEC_ACE_TYPE_ACCESS_ALLOWED,
3200                                                    FILE_GENERIC_ALL, 0);
3201                         }
3202
3203                         for (ace = dir_ace; ace != NULL; ace = ace->next) {
3204                                 uint32_t acc = map_canon_ace_perms(SNUM(conn),
3205                                                 &nt_acl_type,
3206                                                 ace->perms,
3207                                                 S_ISDIR(sbuf->st_ex_mode));
3208                                 init_sec_ace(&nt_ace_list[num_aces++],
3209                                         &ace->trustee,
3210                                         nt_acl_type,
3211                                         acc,
3212                                         ace->ace_flags |
3213                                         SEC_ACE_FLAG_OBJECT_INHERIT|
3214                                         SEC_ACE_FLAG_CONTAINER_INHERIT|
3215                                         SEC_ACE_FLAG_INHERIT_ONLY);
3216                         }
3217
3218                         /* The User must have access to a profile share - even
3219                          * if we can't map the SID. */
3220                         if (lp_profile_acls(SNUM(conn))) {
3221                                 add_or_replace_ace(nt_ace_list, &num_aces,
3222                                                 &global_sid_Builtin_Users,
3223                                                 SEC_ACE_TYPE_ACCESS_ALLOWED,
3224                                                 FILE_GENERIC_ALL,
3225                                                 SEC_ACE_FLAG_OBJECT_INHERIT |
3226                                                 SEC_ACE_FLAG_CONTAINER_INHERIT |
3227                                                 SEC_ACE_FLAG_INHERIT_ONLY);
3228                         }
3229
3230                         /*
3231                          * Merge POSIX default ACLs and normal ACLs into one NT ACE.
3232                          * Win2K needs this to get the inheritance correct when replacing ACLs
3233                          * on a directory tree. Based on work by Jim @ IBM.
3234                          */
3235
3236                         num_aces = merge_default_aces(nt_ace_list, num_aces);
3237
3238                         if (lp_profile_acls(SNUM(conn))) {
3239                                 for (i = 0; i < num_aces; i++) {
3240                                         if (sid_equal(&nt_ace_list[i].trustee, &owner_sid)) {
3241                                                 add_or_replace_ace(nt_ace_list, &num_aces,
3242                                                                    &orig_owner_sid,
3243                                                                    nt_ace_list[i].type,
3244                                                                    nt_ace_list[i].access_mask,
3245                                                                    nt_ace_list[i].flags);
3246                                                 break;
3247                                         }
3248                                 }
3249                         }
3250                 }
3251
3252                 if (num_aces) {
3253                         if((psa = make_sec_acl( talloc_tos(), NT4_ACL_REVISION, num_aces, nt_ace_list)) == NULL) {
3254                                 DEBUG(0,("get_nt_acl: Unable to malloc space for acl.\n"));
3255                                 goto done;
3256                         }
3257                 }
3258         } /* security_info & DACL_SECURITY_INFORMATION */
3259
3260         psd = make_standard_sec_desc( talloc_tos(),
3261                         (security_info & OWNER_SECURITY_INFORMATION) ? &owner_sid : NULL,
3262                         (security_info & GROUP_SECURITY_INFORMATION) ? &group_sid : NULL,
3263                         psa,
3264                         &sd_size);
3265
3266         if(!psd) {
3267                 DEBUG(0,("get_nt_acl: Unable to malloc space for security descriptor.\n"));
3268                 sd_size = 0;
3269                 goto done;
3270         }
3271
3272         /*
3273          * Windows 2000: The DACL_PROTECTED flag in the security
3274          * descriptor marks the ACL as non-inheriting, i.e., no
3275          * ACEs from higher level directories propagate to this
3276          * ACL. In the POSIX ACL model permissions are only
3277          * inherited at file create time, so ACLs never contain
3278          * any ACEs that are inherited dynamically. The DACL_PROTECTED
3279          * flag doesn't seem to bother Windows NT.
3280          * Always set this if map acl inherit is turned off.
3281          */
3282         if (pal == NULL || !lp_map_acl_inherit(SNUM(conn))) {
3283                 psd->type |= SEC_DESC_DACL_PROTECTED;
3284         } else {
3285                 psd->type |= pal->sd_type;
3286         }
3287
3288         if (psd->dacl) {
3289                 dacl_sort_into_canonical_order(psd->dacl->aces, (unsigned int)psd->dacl->num_aces);
3290         }
3291
3292         *ppdesc = psd;
3293
3294  done:
3295
3296         if (posix_acl) {
3297                 SMB_VFS_SYS_ACL_FREE_ACL(conn, posix_acl);
3298         }
3299         if (def_acl) {
3300                 SMB_VFS_SYS_ACL_FREE_ACL(conn, def_acl);
3301         }
3302         free_canon_ace_list(file_ace);
3303         free_canon_ace_list(dir_ace);
3304         free_inherited_info(pal);
3305         SAFE_FREE(nt_ace_list);
3306
3307         return NT_STATUS_OK;
3308 }
3309
3310 NTSTATUS posix_fget_nt_acl(struct files_struct *fsp, uint32_t security_info,
3311                            SEC_DESC **ppdesc)
3312 {
3313         SMB_STRUCT_STAT sbuf;
3314         SMB_ACL_T posix_acl = NULL;
3315         struct pai_val *pal;
3316
3317         *ppdesc = NULL;
3318
3319         DEBUG(10,("posix_fget_nt_acl: called for file %s\n", fsp->fsp_name ));
3320
3321         /* can it happen that fsp_name == NULL ? */
3322         if (fsp->is_directory ||  fsp->fh->fd == -1) {
3323                 return posix_get_nt_acl(fsp->conn, fsp->fsp_name,
3324                                         security_info, ppdesc);
3325         }
3326
3327         /* Get the stat struct for the owner info. */
3328         if(SMB_VFS_FSTAT(fsp, &sbuf) != 0) {
3329                 return map_nt_error_from_unix(errno);
3330         }
3331
3332         /* Get the ACL from the fd. */
3333         posix_acl = SMB_VFS_SYS_ACL_GET_FD(fsp);
3334
3335         pal = fload_inherited_info(fsp);
3336
3337         return posix_get_nt_acl_common(fsp->conn, fsp->fsp_name, &sbuf, pal,
3338                                        posix_acl, NULL, security_info, ppdesc);
3339 }
3340
3341 NTSTATUS posix_get_nt_acl(struct connection_struct *conn, const char *name,
3342                           uint32_t security_info, SEC_DESC **ppdesc)
3343 {
3344         SMB_STRUCT_STAT sbuf;
3345         SMB_ACL_T posix_acl = NULL;
3346         SMB_ACL_T def_acl = NULL;
3347         struct pai_val *pal;
3348
3349         *ppdesc = NULL;
3350
3351         DEBUG(10,("posix_get_nt_acl: called for file %s\n", name ));
3352
3353         /* Get the stat struct for the owner info. */
3354         if(vfs_stat_smb_fname(conn, name, &sbuf) != 0) {
3355                 return map_nt_error_from_unix(errno);
3356         }
3357
3358         /* Get the ACL from the path. */
3359         posix_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, name, SMB_ACL_TYPE_ACCESS);
3360
3361         /* If it's a directory get the default POSIX ACL. */
3362         if(S_ISDIR(sbuf.st_ex_mode)) {
3363                 def_acl = SMB_VFS_SYS_ACL_GET_FILE(conn, name, SMB_ACL_TYPE_DEFAULT);
3364                 def_acl = free_empty_sys_acl(conn, def_acl);
3365         }
3366
3367         pal = load_inherited_info(conn, name);
3368
3369         return posix_get_nt_acl_common(conn, name, &sbuf, pal, posix_acl,
3370                                        def_acl, security_info, ppdesc);
3371 }
3372
3373 /****************************************************************************
3374  Try to chown a file. We will be able to chown it under the following conditions.
3375
3376   1) If we have root privileges, then it will just work.
3377   2) If we have SeTakeOwnershipPrivilege we can change the user to the current user.
3378   3) If we have SeRestorePrivilege we can change the user to any other user. 
3379   4) If we have write permission to the file and dos_filemodes is set
3380      then allow chown to the currently authenticated user.
3381 ****************************************************************************/
3382
3383 int try_chown(connection_struct *conn, const char *fname, uid_t uid, gid_t gid)
3384 {
3385         int ret;
3386         files_struct *fsp;
3387         SMB_STRUCT_STAT st;
3388
3389         if(!CAN_WRITE(conn)) {
3390                 return -1;
3391         }
3392
3393         /* Case (1). */
3394         /* try the direct way first */
3395         ret = SMB_VFS_CHOWN(conn, fname, uid, gid);
3396         if (ret == 0)
3397                 return 0;
3398
3399         /* Case (2) / (3) */
3400         if (lp_enable_privileges()) {
3401
3402                 bool has_take_ownership_priv = user_has_privileges(current_user.nt_user_token,
3403                                                               &se_take_ownership);
3404                 bool has_restore_priv = user_has_privileges(current_user.nt_user_token,
3405                                                        &se_restore);
3406
3407                 /* Case (2) */
3408                 if ( ( has_take_ownership_priv && ( uid == current_user.ut.uid ) ) ||
3409                 /* Case (3) */
3410                      ( has_restore_priv ) ) {
3411
3412                         become_root();
3413                         /* Keep the current file gid the same - take ownership doesn't imply group change. */
3414                         ret = SMB_VFS_CHOWN(conn, fname, uid, (gid_t)-1);
3415                         unbecome_root();
3416                         return ret;
3417                 }
3418         }
3419
3420         /* Case (4). */
3421         if (!lp_dos_filemode(SNUM(conn))) {
3422                 errno = EPERM;
3423                 return -1;
3424         }
3425
3426         /* only allow chown to the current user. This is more secure,
3427            and also copes with the case where the SID in a take ownership ACL is
3428            a local SID on the users workstation
3429         */
3430         if (uid != current_user.ut.uid) {
3431                 errno = EPERM;
3432                 return -1;
3433         }
3434
3435         if (vfs_stat_smb_fname(conn,fname,&st)) {
3436                 return -1;
3437         }
3438
3439         if (!NT_STATUS_IS_OK(open_file_fchmod(NULL, conn, fname, &st, &fsp))) {
3440                 return -1;
3441         }
3442
3443         become_root();
3444         /* Keep the current file gid the same. */
3445         ret = SMB_VFS_FCHOWN(fsp, uid, (gid_t)-1);
3446         unbecome_root();
3447
3448         close_file_fchmod(NULL, fsp);
3449
3450         return ret;
3451 }
3452
3453 #if 0
3454 /* Disable this - prevents ACL inheritance from the ACL editor. JRA. */
3455
3456 /****************************************************************************
3457  Take care of parent ACL inheritance.
3458 ****************************************************************************/
3459
3460 NTSTATUS append_parent_acl(files_struct *fsp,
3461                                 const SEC_DESC *pcsd,
3462                                 SEC_DESC **pp_new_sd)
3463 {
3464         struct smb_filename *smb_dname = NULL;
3465         SEC_DESC *parent_sd = NULL;
3466         files_struct *parent_fsp = NULL;
3467         TALLOC_CTX *mem_ctx = talloc_tos();
3468         char *parent_name = NULL;
3469         SEC_ACE *new_ace = NULL;
3470         unsigned int num_aces = pcsd->dacl->num_aces;
3471         NTSTATUS status;
3472         int info;
3473         unsigned int i, j;
3474         SEC_DESC *psd = dup_sec_desc(talloc_tos(), pcsd);
3475         bool is_dacl_protected = (pcsd->type & SEC_DESC_DACL_PROTECTED);
3476
3477         if (psd == NULL) {
3478                 return NT_STATUS_NO_MEMORY;
3479         }
3480
3481         if (!parent_dirname(mem_ctx, fsp->fsp_name, &parent_name, NULL)) {
3482                 return NT_STATUS_NO_MEMORY;
3483         }
3484
3485         status = create_synthetic_smb_fname_split(mem_ctx, parent_name, NULL,
3486                                                   &smb_dname);
3487         if (!NT_STATUS_IS_OK(status)) {
3488                 goto fail;
3489         }
3490
3491         status = SMB_VFS_CREATE_FILE(
3492                 fsp->conn,                              /* conn */
3493                 NULL,                                   /* req */
3494                 0,                                      /* root_dir_fid */
3495                 smb_dname,                              /* fname */
3496                 FILE_READ_ATTRIBUTES,                   /* access_mask */
3497                 FILE_SHARE_NONE,                        /* share_access */
3498                 FILE_OPEN,                              /* create_disposition*/
3499                 FILE_DIRECTORY_FILE,                    /* create_options */
3500                 0,                                      /* file_attributes */
3501                 INTERNAL_OPEN_ONLY,                     /* oplock_request */
3502                 0,                                      /* allocation_size */
3503                 NULL,                                   /* sd */
3504                 NULL,                                   /* ea_list */
3505                 &parent_fsp,                            /* result */
3506                 &info);                                 /* pinfo */
3507
3508         TALLOC_FREE(smb_fname);
3509
3510         if (!NT_STATUS_IS_OK(status)) {
3511                 return status;
3512         }
3513
3514         status = SMB_VFS_GET_NT_ACL(parent_fsp->conn, parent_fsp->fsp_name,
3515                                     DACL_SECURITY_INFORMATION, &parent_sd );
3516
3517         close_file(NULL, parent_fsp, NORMAL_CLOSE);
3518
3519         if (!NT_STATUS_IS_OK(status)) {
3520                 return status;
3521         }
3522
3523         /*