File: FileAuthorizationModule.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (544 lines) | stat: -rw-r--r-- 24,482 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//------------------------------------------------------------------------------
// <copyright file="FileAuthorizationModule.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 * FileAclAuthorizationModule class
 *
 * Copyright (c) 1999 Microsoft Corporation
 */

namespace System.Web.Security {
    using System.Runtime.Serialization;
    using System.IO;
    using System.Web;
    using System.Web.Caching;
    using System.Web.Util;
    using System.Web.Configuration;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Security.Principal;
    using System.Globalization;
    using System.Security.Permissions;
    using System.Runtime.InteropServices;
    using System.Web.Management;
    using System.Web.Hosting;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;



    /// <devdoc>
    ///    <para>
    ///       Verifies that the remote user has NT permissions to access the
    ///       file requested.
    ///    </para>
    /// </devdoc>
    public sealed class FileAuthorizationModule : IHttpModule {


        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Web.Security.FileAuthorizationModule'/>
        ///       class.
        ///     </para>
        /// </devdoc>
        [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
        public FileAuthorizationModule() {
        }

        private static bool s_EnabledDetermined;
        private static bool s_Enabled;


        [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
        public static bool CheckFileAccessForUser(String virtualPath, IntPtr token, string verb) {
            if (virtualPath == null)
                throw new ArgumentNullException("virtualPath");
            if (token == IntPtr.Zero)
                throw new ArgumentNullException("token");
            if (verb == null)
                throw new ArgumentNullException("verb");
            VirtualPath vPath = VirtualPath.Create(virtualPath);

            if (!vPath.IsWithinAppRoot)
                throw new ArgumentException(SR.GetString(SR.Virtual_path_outside_application_not_supported), "virtualPath");

            if (!s_EnabledDetermined) {
                if (HttpRuntime.UseIntegratedPipeline) {
                    s_Enabled = true; // always enabled in Integrated Mode
                }
                else {
                    HttpModulesSection modulesSection = RuntimeConfig.GetConfig().HttpModules;
                    int len = modulesSection.Modules.Count;
                    for (int iter = 0; iter < len; iter++) {
                        HttpModuleAction module = modulesSection.Modules[iter];
                        if (Type.GetType(module.Type, false) == typeof(FileAuthorizationModule)) {
                            s_Enabled = true;
                            break;
                        }
                    }
                }
                s_EnabledDetermined = true;
            }
            if (!s_Enabled)
                return true;
            ////////////////////////////////////////////////////////////
            // Step 3: Check the cache for the file-security-descriptor
            //        for the requested file
            bool freeDescriptor;
            FileSecurityDescriptorWrapper oSecDesc = GetFileSecurityDescriptorWrapper(vPath.MapPath(), out freeDescriptor);

            ////////////////////////////////////////////////////////////
            // Step 4: Check if access is allowed
            int iAccess = 3;
            if (verb == "GET" || verb == "POST" || verb == "HEAD" || verb == "OPTIONS")
                iAccess = 1;
            bool fAllowed = oSecDesc.IsAccessAllowed(token, iAccess);

            ////////////////////////////////////////////////////////////
            // Step 5: Free the security descriptor if adding to cache failed
            if (freeDescriptor)
                oSecDesc.FreeSecurityDescriptor();
            return fAllowed;
        }



        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void Init(HttpApplication app) {
            app.AuthorizeRequest += new EventHandler(this.OnEnter);
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void Dispose() {
        }

        void OnEnter(Object source, EventArgs eventArgs) {
            if (HttpRuntime.IsOnUNCShareInternal)
                return; // don't check on UNC shares -- the user token is bogus anyway
            HttpApplication app;
            HttpContext context;

            app = (HttpApplication)source;
            context = app.Context;

            if (!IsUserAllowedToFile(context, null)) {
                context.Response.SetStatusCode(401, subStatus: 3);
                WriteErrorMessage(context);
                app.CompleteRequest();
            }
        }

        internal static bool IsWindowsIdentity(HttpContext context) {
            return context.User != null &&
                 context.User.Identity != null &&
                 context.User.Identity is WindowsIdentity;
        }

        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method is not dangerous.")]
        private static bool IsUserAllowedToFile(HttpContext context, string fileName) {
            ////////////////////////////////////////////////////////////
            // Step 1: Check if this is WindowsLogin
            // It's not a windows authenticated user: allow access
            if (!IsWindowsIdentity(context)) {
                return true;
            }

            if (fileName == null) {
                fileName = context.Request.PhysicalPathInternal;
            }

            bool           isAnonymousUser = (context.User == null || !context.User.Identity.IsAuthenticated);
            CachedPathData pathData        = null;
            int            iAccess         = 3;
            HttpVerb       verb            = context.Request.HttpVerb;

            if (verb == HttpVerb.GET
                || verb == HttpVerb.POST
                || verb == HttpVerb.HEAD
                || context.Request.HttpMethod  == "OPTIONS")
            {
                iAccess = 1;

                ////////////////////////////////////////////////////////////
                // iff it's a GET or POST or HEAD or OPTIONs verb, we can use the cached result
                if (!CachedPathData.DoNotCacheUrlMetadata) {
                    pathData = context.GetConfigurationPathData();
                    // as a perf optimization, we cache results for annoymous access
                    //  to CachedPathData.PhysicalPath, and avoid doing the full check
                    if (!StringUtil.EqualsIgnoreCase(fileName, pathData.PhysicalPath)) {
                        // set to null so we don't attempt to update it after the full check below
                        pathData = null;
                    }
                    else {
                        if (pathData.AnonymousAccessAllowed) { // fast path when everyone has access
                            Debug.Trace("FAM", "IsUserAllowedToFile: pathData.AnonymousAccessAllowed");
                            return true;
                        }
                        if (pathData.AnonymousAccessChecked && isAnonymousUser) { // fast path for anonymous user
                            // another thread could be modifying CachedPathData, so return the 
                            // value of AnonymousAccessAllowed instead of assuming it is false
                            Debug.Trace("FAM", "IsUserAllowedToFile: pathData.AnonymousAccessChecked && isAnonymousUser");
                            return pathData.AnonymousAccessAllowed;
                        }
                    }
                }
            }


            // Step 3: Check the cache for the file-security-descriptor
            //        for the requested file
            bool freeDescriptor;
            FileSecurityDescriptorWrapper oSecDesc = GetFileSecurityDescriptorWrapper(fileName, out freeDescriptor);

            ////////////////////////////////////////////////////////////
            // Step 4: Check if access is allowed
            bool fAllowed;
            if (iAccess == 1) { // iff it's a GET or POST or HEAD or OPTIONs verb, we can cache the result
                if (oSecDesc._AnonymousAccessChecked && isAnonymousUser) {
                    Debug.Trace("FAM", "IsUserAllowedToFile: oSecDesc._AnonymousAccessChecked && isAnonymousUser");
                    fAllowed = oSecDesc._AnonymousAccess;
                }
                else {
                    Debug.Trace("FAM", "IsUserAllowedToFile: calling oSecDesc.IsAccessAllowed with iAccess == 1");
                    fAllowed = oSecDesc.IsAccessAllowed(context.WorkerRequest.GetUserToken(), iAccess);
                }

                if (!oSecDesc._AnonymousAccessChecked && isAnonymousUser) {
                    oSecDesc._AnonymousAccess = fAllowed;
                    oSecDesc._AnonymousAccessChecked = true;
                }

                // Cache results in CachedPathData if the file exists and annonymous access has been checked.
                // Note that if CachedPathData.Exists is false, then it does not have a dependency on the file path,
                // and won't be expunged if the file changes.
                if (pathData != null && pathData.Exists && oSecDesc._AnonymousAccessChecked) {
                    Debug.Trace("FAM", "IsUserAllowedToFile: updating pathData");
                    pathData.AnonymousAccessAllowed = oSecDesc._AnonymousAccess;
                    pathData.AnonymousAccessChecked = true;
                }
            } 
            else {
                Debug.Trace("FAM", "IsUserAllowedToFile: calling oSecDesc.IsAccessAllowed with iAccess != 1");
                fAllowed = oSecDesc.IsAccessAllowed(context.WorkerRequest.GetUserToken(), iAccess); // don't cache this anywhere
            }

            ////////////////////////////////////////////////////////////
            // Step 5: Free the security descriptor if adding to cache failed
            if (freeDescriptor)
                oSecDesc.FreeSecurityDescriptor();

            if (fAllowed) {
                WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFileAuthorizationSuccess);
            }
            else {
                if (!isAnonymousUser)
                    WebBaseEvent.RaiseSystemEvent(null, WebEventCodes.AuditFileAuthorizationFailure);
            }

            return fAllowed;
        }
        private static FileSecurityDescriptorWrapper GetFileSecurityDescriptorWrapper(string fileName, out bool freeDescriptor) {
            if (CachedPathData.DoNotCacheUrlMetadata) {
                freeDescriptor = true;
                return new FileSecurityDescriptorWrapper(fileName);
            }

            freeDescriptor = false;
            string                          oCacheKey   = CacheInternal.PrefixFileSecurity + fileName;
            FileSecurityDescriptorWrapper   oSecDesc    = HttpRuntime.Cache.InternalCache.Get(oCacheKey) as FileSecurityDescriptorWrapper;

            // If it's not present in the cache, then create it and add to the cache
            if (oSecDesc == null) {
                Debug.Trace("FAM", "GetFileSecurityDescriptorWrapper: cache miss for " + fileName);
                oSecDesc = new FileSecurityDescriptorWrapper(fileName);
                string cacheDependencyPath = oSecDesc.GetCacheDependencyPath();
                if (cacheDependencyPath != null) {
                    // Add it to the cache: ignore failures, since a different thread may have added it or the file doesn't exist
                    try {
                        Debug.Trace("FAM", "GetFileSecurityDescriptorWrapper: inserting into cache with dependency on " + cacheDependencyPath);
                        CacheDependency dependency = new CacheDependency(0, cacheDependencyPath);
                        TimeSpan slidingExp = CachedPathData.UrlMetadataSlidingExpiration;
                        HttpRuntime.Cache.InternalCache.Insert(oCacheKey, oSecDesc, new CacheInsertOptions() {
                                                                                    Dependencies = dependency,
                                                                                    SlidingExpiration = slidingExp,
                                                                                    OnRemovedCallback = new CacheItemRemovedCallback(oSecDesc.OnCacheItemRemoved)
                                                                                });
                    } catch (Exception e){
                        Debug.Trace("internal", e.ToString());
                        freeDescriptor = true;
                    }
                }
            }
            return oSecDesc;
        }


        private void WriteErrorMessage(HttpContext context) {
            if (!context.IsCustomErrorEnabled) {
                context.Response.Write((new FileAccessFailedErrorFormatter(context.Request.PhysicalPathInternal)).GetErrorMessage(context, false));
            } else {
                context.Response.Write((new FileAccessFailedErrorFormatter(null)).GetErrorMessage(context, true));
            }
            // In Integrated pipeline, ask for handler headers to be generated.  This would be unnecessary
            // if we just threw an access denied exception, and used the standard error mechanism
            context.Response.GenerateResponseHeadersForHandler();
        }


        static internal bool RequestRequiresAuthorization(HttpContext context) {

            Object                        sec;
            FileSecurityDescriptorWrapper oSecDesc;
            string                        oCacheKey;

            if (!IsWindowsIdentity(context)) {
                return false;
            }

            oCacheKey = CacheInternal.PrefixFileSecurity + context.Request.PhysicalPathInternal;

            sec = HttpRuntime.Cache.InternalCache.Get(oCacheKey);

            // If it's not present in the cache, then return true
            if (sec == null || !(sec is FileSecurityDescriptorWrapper))
                return true;

            oSecDesc = (FileSecurityDescriptorWrapper) sec;
            if (oSecDesc._AnonymousAccessChecked && oSecDesc._AnonymousAccess)
                return false;

            return true;
        }
        internal static bool IsUserAllowedToPath(HttpContext context, VirtualPath virtualPath)
        {
            return IsUserAllowedToFile(context, virtualPath.MapPath());
        }
    }

    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////
    internal class FileSecurityDescriptorWrapper : IDisposable {
        ~FileSecurityDescriptorWrapper() {
            FreeSecurityDescriptor();
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal FileSecurityDescriptorWrapper(String strFile) {
            _FileName = FileUtil.RemoveTrailingDirectoryBackSlash(strFile);
            _securityDescriptor = UnsafeNativeMethods.GetFileSecurityDescriptor(_FileName);
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal bool IsAccessAllowed(IntPtr iToken, int iAccess) {
            if (iToken == IntPtr.Zero)
                return true;

            if (_SecurityDescriptorBeingFreed)
                return IsAccessAllowedUsingNewSecurityDescriptor(iToken, iAccess);

            _Lock.AcquireReaderLock();
            try {
                try {
                    if (!_SecurityDescriptorBeingFreed) {
                        if (_securityDescriptor == IntPtr.Zero)
                            return true;
                        if (_securityDescriptor == UnsafeNativeMethods.INVALID_HANDLE_VALUE)
                            return false;
                        else
                            return (UnsafeNativeMethods.IsAccessToFileAllowed(_securityDescriptor, iToken, iAccess) != 0);
                    }
                } finally {
                    _Lock.ReleaseReaderLock();
                }
            } catch {
                throw;
            }

            return IsAccessAllowedUsingNewSecurityDescriptor(iToken, iAccess);
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        private bool IsAccessAllowedUsingNewSecurityDescriptor(IntPtr iToken, int iAccess) {
            if (iToken == IntPtr.Zero)
                return true;

            IntPtr secDes = UnsafeNativeMethods.GetFileSecurityDescriptor(_FileName);
            if (secDes == IntPtr.Zero)
                return true;
            if (secDes == UnsafeNativeMethods.INVALID_HANDLE_VALUE)
                return false;

            try {
                try {
                    return (UnsafeNativeMethods.IsAccessToFileAllowed(secDes, iToken, iAccess) != 0);
                } finally {
                    UnsafeNativeMethods.FreeFileSecurityDescriptor(secDes);
                }
            } catch {
                throw;
            }
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal void OnCacheItemRemoved(String key, Object value, CacheItemRemovedReason reason) {
            FreeSecurityDescriptor();
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal void FreeSecurityDescriptor() {
            if (!IsSecurityDescriptorValid())
                return;
            _SecurityDescriptorBeingFreed = true;

            _Lock.AcquireWriterLock();
            try {
                try {
                    if (!IsSecurityDescriptorValid())
                        return;
                    // VSWHIDBEY 493667: double free in webengine!FreeFileSecurityDescriptor()
                    IntPtr temp = _securityDescriptor;
                    _securityDescriptor = UnsafeNativeMethods.INVALID_HANDLE_VALUE;
                    UnsafeNativeMethods.FreeFileSecurityDescriptor(temp);
                } finally {
                    _Lock.ReleaseWriterLock();
                }
            } catch {
                throw;
            }
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal bool IsSecurityDescriptorValid() {
            return
                _securityDescriptor != UnsafeNativeMethods.INVALID_HANDLE_VALUE &&
                _securityDescriptor != IntPtr.Zero;
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        internal string GetCacheDependencyPath() {
            // if security descriptor is invalid, we cannot cache it
            if (_securityDescriptor == UnsafeNativeMethods.INVALID_HANDLE_VALUE) {
                Debug.Trace("FAM", "GetCacheDependencyPath: invalid security descriptor");
                return null;
            }
            // if security descriptor is valid (file exists), cache it with a dependency on the file name
            if (_securityDescriptor != IntPtr.Zero) {
                Debug.Trace("FAM", "GetCacheDependencyPath: valid security descriptor");
                return _FileName;
            }
            // file does not exist, but if it's path is beneath the app root, we will cache it and
            // use the first existing directory as the cache depenedency path
            string existingDir = FileUtil.GetFirstExistingDirectory(AppRoot, _FileName);

#if DBG
            if (existingDir != null) {
                Debug.Trace("FAM", "GetCacheDependencyPath: beneath app root");
            }
            else {
                Debug.Trace("FAM", "GetCacheDependencyPath: not beneath app root");
            }
#endif
            return existingDir;
        }

        /////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////////////////////////////
        private static string AppRoot {
            get {
                string appRoot = _AppRoot;
                if (appRoot == null) {
                    InternalSecurityPermissions.AppPathDiscovery.Assert();
                    appRoot = Path.GetFullPath(HttpRuntime.AppDomainAppPathInternal);
                    appRoot = FileUtil.RemoveTrailingDirectoryBackSlash(appRoot);
                }
                return appRoot;
            }
        }

        void IDisposable.Dispose()
        {
            FreeSecurityDescriptor();
            GC.SuppressFinalize(this);
        }
        private  IntPtr               _securityDescriptor;
        internal bool                 _AnonymousAccessChecked  = false;
        internal bool                 _AnonymousAccess         = false;
        private  bool                 _SecurityDescriptorBeingFreed        = false;
        private  string               _FileName                = null;
        private  ReadWriteSpinLock    _Lock                    = new ReadWriteSpinLock();
        private static string         _AppRoot                 = null;
    }

    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////
    internal class FileAccessFailedErrorFormatter : ErrorFormatter {
        private String _strFile;

        internal FileAccessFailedErrorFormatter(string strFile) {
            _strFile = strFile;
            if (_strFile == null)
                _strFile = String.Empty;
        }

        protected override string ErrorTitle {
            get { return SR.GetString(SR.Assess_Denied_Title);}
            //get { return "Access Denied Error";}
        }

        protected override string Description {
            get {
                return SR.GetString(SR.Assess_Denied_Description3);
                //return "An error occurred while accessing the resources required to serve this request. &nbsp; This typically happens if you do not have permissions to view the file you are trying to access.";
            }
        }

        protected override string MiscSectionTitle {
            get { return SR.GetString(SR.Assess_Denied_Section_Title3); }
            //get { return "Error message 401.3";}
        }

        protected override string MiscSectionContent {
            get {
                string miscContent;
                if (_strFile.Length > 0)
                    miscContent = SR.GetString(SR.Assess_Denied_Misc_Content3, HttpRuntime.GetSafePath(_strFile));
                //return "Access is denied due to NT ACLs on the requested file. Ask the web server's administrator to give you access to "+ _strFile + ".";
                else
                    miscContent = SR.GetString(SR.Assess_Denied_Misc_Content3_2);

                AdaptiveMiscContent.Add(miscContent);
                return miscContent;
            }
        }

        protected override string ColoredSquareTitle {
            get { return null;}
        }

        protected override string ColoredSquareContent {
            get { return null;}
        }

        protected override bool ShowSourceFileInfo {
            get { return false;}
        }
    }
}