Example #1
0
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (!UrlAuthorizationModule.CheckUrlAccessForPrincipal("~/Download/", requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod))
            {
                requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                requestContext.HttpContext.Response.End();
            }

            hapConfig    config = hapConfig.Current;
            string       path   = HttpUtility.UrlDecode(((string)requestContext.RouteData.Values["path"]).Replace('^', '&').Replace("|", "%"));
            DriveMapping unc    = config.MyFiles.Mappings.FilteredMappings[((string)requestContext.RouteData.Values["drive"]).ToUpper().ToCharArray()[0]];

            path = Converter.FormatMapping(unc.UNC, ADUser) + '\\' + path.Replace('/', '\\');
            HAP.Data.SQL.WebEvents.Log(DateTime.Now, "MyFiles.Download", requestContext.HttpContext.User.Identity.Name, HttpContext.Current.Request.UserHostAddress, HttpContext.Current.Request.Browser.Platform, HttpContext.Current.Request.Browser.Browser + " " + HttpContext.Current.Request.Browser.Version, HttpContext.Current.Request.UserHostName, "Downloading: " + path);

            Downloader downloader = new Downloader();

            if (requestContext.RouteData.Values.ContainsKey("path"))
            {
                downloader.RoutingPath = requestContext.RouteData.Values["path"] as string;
            }
            else
            {
                downloader.RoutingPath = string.Empty;
            }
            downloader.RoutingDrive = requestContext.RouteData.Values["drive"] as string;
            downloader.RoutingDrive = downloader.RoutingDrive.ToUpper();
            return(downloader);
        }
Example #2
0
        public virtual void PostResolveRequestCache(HttpContextBase context)
        {
            RouteData routeData = this.RouteCollection.GetRouteData(context);

            if (routeData != null)
            {
                IRouteHandler routeHandler = routeData.RouteHandler;
                if (routeHandler == null)
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, System.Web.SR.GetString("UrlRoutingModule_NoRouteHandler"), new object[0]));
                }
                if (!(routeHandler is StopRoutingHandler))
                {
                    RequestContext requestContext = new RequestContext(context, routeData);
                    context.Request.RequestContext = requestContext;
                    IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);
                    if (httpHandler == null)
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture, System.Web.SR.GetString("UrlRoutingModule_NoHttpHandler"), new object[] { routeHandler.GetType() }));
                    }
                    if (httpHandler is UrlAuthFailureHandler)
                    {
                        if (!FormsAuthenticationModule.FormsAuthRequired)
                        {
                            throw new HttpException(0x191, System.Web.SR.GetString("Assess_Denied_Description3"));
                        }
                        UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this);
                    }
                    else
                    {
                        context.RemapHandler(httpHandler);
                    }
                }
            }
        }
Example #3
0
        private static void AddLinkToList(List <Link> list, string url, string @class, string title)
        {
            var virtualUrl = "~" + url;

            if (UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualUrl, HttpContext.Current.User, "GET"))
            {
                var link = new Link(url, @class, title);
                list.Add(link);
            }
        }
Example #4
0
        public void OnPostAuthenticate(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;

            if (!UrlAuthorizationModule.CheckUrlAccessForPrincipal(app.Request.Path,
                                                                   app.User,
                                                                   "GET"))
            {
                //Code here to read cookies, redirect user etc.
            }
        }
Example #5
0
        protected override IHttpHandler GetHttpHandler(RequestContext context)
        {
            if (ValidateAccessRights && !UrlAuthorizationModule
                .CheckUrlAccessForPrincipal(_virtualPath, context.Context.User,
                                            context.Context.Request.HttpMethod.ToString()))
            {
                throw new HttpException(403, "Access denied.");
            }

            return(BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(Page)) as IHttpHandler);
        }
Example #6
0
        /// <summary>
        /// Calculate the NavigateUrl in Render because no other event is absolutely guaranteed.
        /// </summary>
        /// <remarks>
        /// SiteMapKey will now become <c>NavigateUrl</c> incase <see cref="AutoSiteMapProvider"/> is
        /// not available or the containing page is not known to <see cref="AutoSiteMapProvider"/>.
        /// </remarks>
        /// <param name="writer"></param>
        protected override void Render(HtmlTextWriter writer)
        {
            if (this.FiltersControl != null && !this.FiltersControl.Visible)
            {
                // Don't render anything
                return;
            }

            if (this.SecurityCheck && !string.IsNullOrWhiteSpace(this.NavigateUrl) &&
                !UrlAuthorizationModule.CheckUrlAccessForPrincipal(this.NavigateUrl, this.Page.User, "GET"))
            {
                // Security check failed. Nothing to render
                return;
            }
            if (string.IsNullOrEmpty(this.SiteMapKey))
            {
                // Do nothing. Use NavigateUrl as is
            }
            else
            {
                string url;
                bool   broken = true;       // Assume that the link is potentially broken
                if (!SiteMap.Enabled || SiteMap.CurrentNode == null)
                {
                    url = this.SiteMapKey;
                }
                else
                {
                    SiteMapNode node = SiteMap.Provider.FindSiteMapNodeFromKey(this.SiteMapKey);
                    if (node == null)
                    {
                        url = this.SiteMapKey;
                    }
                    else
                    {
                        url    = node.Url;
                        broken = false;     // Not broken
                    }
                }
                this.NavigateUrl = url + "?" + this.NavigateUrl;
                if (this.FiltersControl != null)
                {
                    this.NavigateUrl += "&" + this.FiltersControl.AsQueryString();
                }

                if (broken)
                {
                    this.Style.Add("border-bottom", "0.4mm dotted red");
                    this.ToolTip = string.Format("Link to {0} is not available", this.SiteMapKey);
                }
            }

            base.Render(writer);
        }
        internal bool RequestRequiresAuthorization()
        {
            // if current user is anonymous, then trivially, this page does not require authorization
            if (!User.Identity.IsAuthenticated)
            {
                return(false);
            }

            // Ask each of the authorization modules
            return
                (FileAuthorizationModule.RequestRequiresAuthorization(this) ||
                 UrlAuthorizationModule.RequestRequiresAuthorization(this));
        }
Example #8
0
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            string substVirtualPath = GetSubstitutedVirtualPath(requestContext);

            if (this.CheckPhysicalUrlAccess && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(substVirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod))
            {
                throw new SecurityException();
            }

            // add query string parameters
            string queryString = string.Empty;
            string SEName      = string.Empty;

            foreach (KeyValuePair <string, object> aux in requestContext.RouteData.Values)
            {
                if (aux.Key.Contains("SEPart"))
                {
                    // reassemble SEName from the SEParts
                    SEName = requestContext.HttpContext.Server.UrlEncode(aux.Value.ToString()) + (SEName.Length == 0 ? string.Empty : "-" + SEName);
                }
                else
                {
                    queryString += (queryString.Length == 0 ? "?" : "&") + requestContext.HttpContext.Server.UrlEncode(aux.Key) + "=" + requestContext.HttpContext.Server.UrlEncode(aux.Value.ToString());
                }
            }

            if (SEName.Length > 0)
            {
                queryString += (queryString.Length == 0 ? "?" : "&") + "SEName=" + SEName;                     // add reassembled SEName
            }
            IHttpHandler handler = null;

            if (substVirtualPath.Contains(".aspx"))
            {
                handler = BuildManager.CreateInstanceFromVirtualPath("~/" + substVirtualPath, typeof(Page)) as IHttpHandler;
            }

            else if (substVirtualPath.Contains(".ashx"))
            {
                handler = BuildManager.CreateInstanceFromVirtualPath("~/" + substVirtualPath, typeof(IHttpHandler)) as IHttpHandler;
            }

            if (handler != null)
            {
                HttpContext.Current.SetRequestData(new RequestData(requestContext));
            }


            return(handler);
        }
        public IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
        {
            if (!UrlAuthorizationModule.CheckUrlAccessForPrincipal(VirtualPath, requestContext.HttpContext.User, requestContext.HttpContext.Request.HttpMethod))
            {
                requestContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                requestContext.HttpContext.Response.End();
            }

            var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;

            foreach (var urlParm in requestContext.RouteData.Values)
            {
                requestContext.HttpContext.Items[urlParm.Key] = urlParm.Value;
            }
            return(page);
        }
Example #10
0
 internal static bool IsUserAllowedToPath(HttpContext context, VirtualPath virtualPath)
 {
     if (FileAuthorizationModule.IsWindowsIdentity(context))
     {
         if (HttpRuntime.IsFullTrust)
         {
             if (!IsUserAllowedToPathWithNoAssert(context, virtualPath))
             {
                 return(false);
             }
         }
         else if (!IsUserAllowedToPathWithAssert(context, virtualPath))
         {
             return(false);
         }
     }
     return(UrlAuthorizationModule.IsUserAllowedToPath(context, virtualPath));
 }
Example #11
0
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (this.CheckPhysicalUrlAccess && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
                    this.VirtualPath,
                    requestContext.HttpContext.User,
                    requestContext.HttpContext.Request.HttpMethod))
            {
                throw new SecurityException();
            }

            var page = BuildManager.CreateInstanceFromVirtualPath(
                this.VirtualPath,
                typeof(Page)) as IHttpHandler;

            if (page != null)
            {
                var routablePage = page as IRoutablePage;

                if (routablePage != null)
                {
                    routablePage.Routing = new RoutingHelper(requestContext);
                }

                // The WebForm's Form.Action value may be incorrect; override it with the raw URL:
                var webForm = page as Page;
                if (webForm != null)
                {
                    webForm.Load += delegate { webForm.Form.Action = requestContext.HttpContext.Request.RawUrl; }
                }
                ;
            }

            try
            {
                string date = requestContext.RouteData.GetRequiredString("date");
            }
            catch (InvalidOperationException)
            {
            }

            return(page);
        }
    }
Example #12
0
        /// <summary>
        /// Internal method for rerouting to local, application relative paths.
        /// </summary>
        /// <param name="newLocalRelativePath"></param>
        protected void RerouteRequestLocal(string newLocalRelativePath)
        {
            // if we want to authorize the redirected url, do it now
            bool canAccess = true;

            if (_authorizeRedirectionUrl)
            {
                // drop any query string
                string testUrl = newLocalRelativePath.Split(new char[] { '?' })[0];
                canAccess = UrlAuthorizationModule.CheckUrlAccessForPrincipal(testUrl, HttpContext.Current.User, "GET");
            }

            // can we access the locally redirected path?
            if (canAccess)
            {
                HttpContext.Current.RewritePath(newLocalRelativePath, false);
            }
            else
            {
                // nope... authorization failed.
                if (_authorizeRedirectionUrl && !string.IsNullOrEmpty(_authorizeFailureRedirectUrl))
                {
                    // the failure URL may contain a {0} placeholder; if it does,
                    // substitute the original incoming url for it.
                    string failureUrl = _authorizeFailureRedirectUrl;
                    if (_authorizeFailureRedirectUrl.Contains("{0}"))
                    {
                        string originalUrl     = HttpContext.Current.Request.RawUrl;
                        string originalEncoded = HttpUtility.UrlEncode(originalUrl);
                        failureUrl = string.Format(_authorizeFailureRedirectUrl, originalEncoded);
                    }

                    HttpContext.Current.RewritePath(failureUrl, true);
                    //HttpContext.Current.Response.Redirect(failureUrl);
                }
                else
                {
                    throw new NoMatchFoundException("Authorization failed on the redirected URL, and no redirection page was established in the <urlMappingModule> 'authorizeFailureRedirectUrl' attribute in web.config.");
                }
            }
        }
Example #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlControl control = loginView.FindControl("menuManageRoles") as HtmlControl;
            HtmlControl mnuManageRoleModules = loginView.FindControl("menuManageRoleModules") as HtmlControl;

            HtmlControl registerControl = loginView.FindControl("menuRegister") as HtmlControl;
            HtmlControl menuReports     = loginView.FindControl("menuReports") as HtmlControl;

            if (Context.User.Identity.Name != string.Empty && control != null && registerControl != null)
            {
                registerControl.Visible = Convert.ToBoolean(Session["UserManagement"]);
            }


            if (Context.User.Identity.Name != string.Empty && menuReports != null)
            {
                menuReports.Visible = Convert.ToBoolean(Session["ViewCharts"]);
            }

            //if (Context.User.Identity.Name != string.Empty && control != null && Context.User.IsInRole("Admin"))
            if (Context.User.Identity.Name != string.Empty && control != null && Convert.ToBoolean(Session["RoleManagement"]))
            {
                control.Visible = UrlAuthorizationModule.CheckUrlAccessForPrincipal("~/Account/ManageRoles.aspx", Context.User, "GET");
                mnuManageRoleModules.Visible = UrlAuthorizationModule.CheckUrlAccessForPrincipal("~/Account/ManageRoleModules.aspx", Context.User, "GET");
            }
            else
            {
                if (control != null)
                {
                    control.Visible = false;
                }

                if (mnuManageRoleModules != null)
                {
                    mnuManageRoleModules.Visible = false;
                }
            }
        }
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (this.CheckPhysicalUrlAccess &&
                !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
                    this.VirtualPath,
                    requestContext.HttpContext.User,
                    requestContext.HttpContext.Request.HttpMethod))
            {
                throw new SecurityException();
            }

            var page = BuildManager.CreateInstanceFromVirtualPath(this.VirtualPath,
                                                                  typeof(Page)) as IHttpHandler;

            if (page != null)
            {
                var routablePage = page as IRoutablePage;
                if (routablePage != null)
                {
                    routablePage.RequestContext = requestContext;
                }
            }
            return(page);
        }
Example #15
0
        /// <summary>
        /// 해당 RequestContext에 대한 처리기 반환
        /// </summary>
        /// <param name="requestContext"></param>
        /// <returns></returns>
        public virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (IsDebugEnabled)
            {
                log.Debug("요청에 따른 HttpHandler를 선택합니다... requestContext=[{0}]", requestContext);
            }

            var virtualPath = GetVirtualPath();

            if (virtualPath.IsWhiteSpace())
            {
                throw new InvalidOperationException("처리할 핸들러 가상경로가 없습니다.");
            }

            foreach (var urlParm in requestContext.RouteData.Values)
            {
                requestContext.HttpContext.Items[urlParm.Key] = urlParm.Value;
            }

            if (CheckPhysicalUrlAccess &&
                !UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualPath,
                                                                   requestContext.HttpContext.User,
                                                                   requestContext.HttpContext.Request.HttpMethod))
            {
                throw new SecurityException();
            }

            var page = BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(T)) as IHttpHandler;

            if (IsDebugEnabled)
            {
                log.Debug("HttpHandler를 구했습니다. virtualPath=[{0}], page=[{1}]", virtualPath, page);
            }

            return(page);
        }
Example #16
0
        /// <summary>
        /// This is where we filter requests and intercept those that want resizing performed.
        /// We first strip FakeExtension, then verify the remaining file extension is supported for decoding.
        /// We fire URL rewriting events. If the result includes any supported querystring params afterwards, we process the request. Otherwise we let it fall back to IIS/ASP.NET.
        /// If the file doesn't exist, we also ignore the request. They're going to cause a 404 anyway.
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void CheckRequest_PostAuthorizeRequest(object sender, EventArgs e)
        {
            //Skip requests if the Request object isn't populated
            HttpApplication app = sender as HttpApplication;

            if (app == null)
            {
                return;
            }
            if (app.Context == null)
            {
                return;
            }
            if (app.Context.Request == null)
            {
                return;
            }

            conf.FirePostAuthorizeRequest(this, app.Context);



            //Allow handlers of the above event to change filePath/pathinfo so we can successfull test the extension
            string originalPath = conf.PreRewritePath;

            //Trim fake extensions so IsAcceptedImageType will work properly
            string filePath = conf.TrimFakeExtensions(originalPath);


            //Is this an image request? Checks the file extension for .jpg, .png, .tiff, etc.
            if (conf.SkipFileTypeCheck || conf.IsAcceptedImageType(filePath))
            {
                //Copy the querystring so we can mod it to death without messing up other stuff.
                NameValueCollection q = conf.ModifiedQueryString;

                //Call URL rewriting events
                UrlEventArgs ue = new UrlEventArgs(filePath, q);
                conf.FireRewritingEvents(this, app.Context, ue);

                //Pull data back out of event object, resolving app-relative paths
                string virtualPath = PathUtils.ResolveAppRelativeAssumeAppRelative(ue.VirtualPath);
                q = ue.QueryString;

                //Store the modified querystring in request for use by VirtualPathProviders
                conf.ModifiedQueryString = q; // app.Context.Items["modifiedQueryString"] = q;

                //See if resizing is wanted (i.e. one of the querystring commands is present).
                //Called after processPath so processPath can add them if needed.
                //Checks for thumnail, format, width, height, maxwidth, maxheight and a lot more
                if (conf.HasPipelineDirective(q))
                {
                    //Who's the user
                    IPrincipal user = app.Context.User as IPrincipal;

                    // no user (must be anonymous...).. Or authentication doesn't work for this suffix. Whatever, just avoid a nullref in the UrlAuthorizationModule
                    if (user == null)
                    {
                        user = new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[0]);
                    }

                    //Do we have permission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal?
                    bool canCheckUrl = System.Security.SecurityManager.IsGranted(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted));


                    //Run the rewritten path past the auth system again, using the result as the default "AllowAccess" value
                    bool isAllowed = true;
                    if (canCheckUrl && !app.Context.SkipAuthorization)
                    {
                        try {
                            isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualPath, user, "GET");
                        } catch (NotImplementedException) { } //For MONO support
                    }
                    IUrlAuthorizationEventArgs authEvent = new UrlAuthorizationEventArgs(virtualPath, new NameValueCollection(q), isAllowed);

                    //Allow user code to deny access, but not modify the url or querystring.
                    conf.FireAuthorizeImage(this, app.Context, authEvent);

                    if (!authEvent.AllowAccess)
                    {
                        throw new ImageProcessingException(403, "Access denied", "Access denied");
                    }



                    //Does the file exist physically? (false if VppUsage=always or file is missing)
                    bool existsPhysically = (conf.VppUsage != VppUsageOption.Always) && System.IO.File.Exists(HostingEnvironment.MapPath(virtualPath));

                    //If not present physically (and VppUsage!=never), try to get the virtual file. Null indicates a missing file
                    IVirtualFile vf = (conf.VppUsage != VppUsageOption.Never && !existsPhysically) ? conf.GetFile(virtualPath, q) : null;

                    //Only process files that exist
                    if (existsPhysically || vf != null)
                    {
                        try{
                            HandleRequest(app.Context, virtualPath, q, vf);
                            //Catch not found exceptions
                        } catch (System.IO.FileNotFoundException notFound) { //Some VPPs are optimisitic , or could be a race condition
                            FileMissing(app.Context, virtualPath, q);
                            throw new ImageMissingException("The specified resource could not be located", "File not found", notFound);
                        } catch (System.IO.DirectoryNotFoundException notFound) {
                            FileMissing(app.Context, virtualPath, q);
                            throw new ImageMissingException("The specified resource could not be located", "File not found", notFound);
                        }
                    }
                    else
                    {
                        FileMissing(app.Context, virtualPath, q);
                    }
                }
            }
        }
Example #17
0
 public void FixtureSetUp()
 {
     app    = new HttpApplication();
     module = new UrlAuthorizationModule();
 }
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            if (this.CheckPhysicalUrlAccess && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(
                    this.VirtualPath,
                    requestContext.HttpContext.User,
                    requestContext.HttpContext.Request.HttpMethod))
            {
                throw new SecurityException();
            }

            var page = BuildManager.CreateInstanceFromVirtualPath(
                this.VirtualPath,
                typeof(Page)) as IHttpHandler;

            if (page != null)
            {
                var routablePage = page as IRoutablePage;

                if (routablePage != null)
                {
                    routablePage.Routing = new RoutingHelper(requestContext);
                }

                // The WebForm's Form.Action value may be incorrect; override it with the raw URL:
                var webForm = page as Page;
                if (webForm != null)
                {
                    webForm.Load += delegate { webForm.Form.Action = requestContext.HttpContext.Request.RawUrl; }
                }
                ;
            }

            if (VirtualPath.EndsWith("Faq.asp"))
            {
                if (requestContext.RouteData.Values.ContainsKey("category") && requestContext.RouteData.Values.ContainsKey("subject"))
                {
                }
            }
            if (VirtualPath.EndsWith("Topic.aspx"))
            {
                if (requestContext.RouteData.Values.ContainsKey("username"))
                {
                    var m = Membership.GetUser(requestContext.RouteData.GetRequiredString("username"));
                    if (m != null)
                    {
                        var blogs = Forums.GetUserBlogTopics(-1, (int)m.ProviderUserKey);
                        if (blogs.Count > 0)
                        {
                            int topicId = 0;
                            if (requestContext.RouteData.Values.ContainsKey("subject"))
                            {
                                var topic =
                                    blogs.SingleOrDefault(
                                        t => t.Subject == requestContext.RouteData.GetRequiredString("subject"));
                                if (topic != null)
                                {
                                    topicId = topic.Id;
                                }
                            }
                            else
                            {
                                topicId = blogs[0].Id;
                            }
                            if (topicId != 0)
                            {
                                requestContext.HttpContext.Items.Add("TopicId", topicId);
                            }
                        }
                    }
                    return(page);
                }
                else
                {
                    var m = Membership.GetUser(requestContext.HttpContext.User.Identity.Name);
                    if (m != null)
                    {
                        var blogs = Forums.GetUserBlogTopics(-1, (int)m.ProviderUserKey);
                        if (blogs.Count > 0)
                        {
                            int topicId = 0;
                            if (requestContext.RouteData.Values.ContainsKey("subject"))
                            {
                                var topic =
                                    blogs.SingleOrDefault(
                                        t => t.Subject == requestContext.RouteData.GetRequiredString("subject"));
                                if (topic != null)
                                {
                                    topicId = topic.Id;
                                }
                            }
                            else
                            {
                                topicId = blogs[0].Id;
                            }
                            if (topicId != 0)
                            {
                                requestContext.HttpContext.Items.Add("TopicId", topicId);
                            }
                        }
                    }
                    return(page);
                }
                string topicSubject = requestContext.RouteData.GetRequiredString("subject");

                if (topicSubject != "")
                {
                    if (topicSubject.IsNumeric())
                    {
                        int topicId = Convert.ToInt32(topicSubject);
                        requestContext.HttpContext.Items.Add("TopicId", topicId);
                    }
                    else
                    {
                        var topic = Topics.GetTopicsBySubject(topicSubject);
                        if (topic.Count == 1)
                        {
                            int topicId = ((SearchResult)topic[0]).Id;
                            requestContext.HttpContext.Items.Add("TopicId", topicId);
                        }
                        else
                        {
                            requestContext.HttpContext.Items.Add("Subject", topicSubject);
                            return
                                ((Page)
                                 BuildManager.CreateInstanceFromVirtualPath("~/Content/Forums/Search.aspx",
                                                                            typeof(Page)));
                        }
                    }
                }
            }
            if (VirtualPath.EndsWith("Profile.aspx"))
            {
                string userName = requestContext.RouteData.GetRequiredString("username");
                if (userName != "")
                {
                    requestContext.HttpContext.Items.Add("user", userName);
                }
            }
            if (VirtualPath.EndsWith("Event.aspx"))
            {
                string date = requestContext.RouteData.GetRequiredString("date");
                if (date != "")
                {
                    requestContext.HttpContext.Items.Add("date", date);
                }
            }
            return(page);
        }
    }
Example #19
0
        public IEnumerable <IIssue> GetIssues()
        {
            List <IIssue> issues = new List <IIssue>();

            //If a plugin has a configuration section, but is not installed, log an issue.
            if (c.getNode("sizelimiting") != null)
            {
                issues.Add(new Issue("Use <sizelimits>, not <sizelimiting> to configure the SizeLimiting plugin", IssueSeverity.ConfigurationError));
            }
            if (c.getNode("sizelimits") != null &&
                !c.Plugins.Has <SizeLimiting>())
            {
                issues.Add(new Issue("You have specified configuration settings for the SizeLimiting plugin, but it is not installed. ",
                                     "Use <add name=\"SizeLimiting\" /> inside <plugins> to install.", IssueSeverity.ConfigurationError));
            }

            if (c.Pipeline.ProcessedCount < 1)
            {
                issues.Add(new Issue("To potentially see additional errors here, perform an image resize request.", IssueSeverity.Warning));
            }

            bool canCheckUrls = System.Security.SecurityManager.IsGranted(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted));

            if (canCheckUrls)
            {
                try {
                    IPrincipal user = new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[0]);
                    UrlAuthorizationModule.CheckUrlAccessForPrincipal(HostingEnvironment.ApplicationVirtualPath.TrimEnd('/') + '/', user, "GET");
                } catch (NotImplementedException) {
                    issues.Add(new Issue("UrlAuthorizationModule.CheckUrlAccessForPrincipal is not supported on this runtime (are you running Mono?)",
                                         "It may be possible for users to bypass UrlAuthorization rules you have defined for your website, and access images that would otherwise be protected. If you do not use UrlAuthorization rules, this should not be a concern. " +
                                         "You may also re-implement your security rules by handling the Config.Current.Pipeline.AuthorizeImage event.", IssueSeverity.Warning));
                }
            }

            if (!canCheckUrls)
            {
                issues.Add(new Issue("Grant the website SecurityPermission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal",
                                     "Without this permission, it may be possible for users to bypass UrlAuthorization rules you have defined for your website, and access images that would otherwise be protected. If you do not use UrlAuthorization rules, this should not be a concern. " +
                                     "You may also re-implement your security rules by handling the Config.Current.Pipeline.AuthorizeImage event.", IssueSeverity.Critical));
            }


            if (File.Exists(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "PrecompiledApp.config")))
            {
                issues.Add(new Issue("Precompilation is enabled. Image providers may not work as expected."));
            }

            string assembliesRunningHotfix = "";

            Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
            foreach (Assembly a in asms)
            {
                //Only check DLLs with ImageResizer in their name
                AssemblyName assemblyName = new AssemblyName(a.FullName);
                if (assemblyName.Name.IndexOf("ImageResizer", StringComparison.OrdinalIgnoreCase) < 0)
                {
                    continue;
                }

                object[] attrs;

                attrs = a.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false);
                if (attrs != null && attrs.Length > 0)
                {
                    if (((AssemblyInformationalVersionAttribute)attrs[0]).InformationalVersion.IndexOf("hotfix", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        assembliesRunningHotfix += assemblyName.Name + ", ";
                    }
                }
            }
            assembliesRunningHotfix = assembliesRunningHotfix.TrimEnd(',', ' ');

            if (!string.IsNullOrEmpty(assembliesRunningHotfix))
            {
                issues.Add(new Issue("You are running a hotfix version of the ImageResizer.",
                                     "You should upgrade to a released version with an equal or higher version number as soon as possible. " +
                                     "Hotfix and release DLLs with the same version number are not the same - the release DLL should be used instead." +
                                     "\nAssemblies marked as hotfix versions: " + assembliesRunningHotfix, IssueSeverity.Warning));
            }


            return(issues);
        }
Example #20
0
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Fixes issue 10.
            bool   isRemote               = request.Path.EndsWith(remotePrefix, StringComparison.OrdinalIgnoreCase);
            string requestPath            = string.Empty;
            string queryString            = string.Empty;
            bool   validExtensionLessUrl  = false;
            string urlParameters          = "";
            string extensionLessExtension = "";

            if (isRemote)
            {
                // We need to split the querystring to get the actual values we want.
                string urlDecode = HttpUtility.UrlDecode(request.QueryString.ToString());

                if (!string.IsNullOrWhiteSpace(urlDecode))
                {
                    // UrlDecode seems to mess up in some circumstance.
                    if (urlDecode.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
                    {
                        urlDecode = urlDecode.Replace(":/", "://");
                    }

                    string[] paths = urlDecode.Split('?');

                    requestPath = paths[0];

                    // Handle extension-less urls.
                    if (paths.Count() > 2)
                    {
                        queryString   = paths[2];
                        urlParameters = paths[1];
                    }
                    else if (paths.Length > 1)
                    {
                        queryString = paths[1];
                    }

                    validExtensionLessUrl = RemoteFile.RemoteFileWhiteListExtensions.Any(
                        x => x.ExtensionLess && requestPath.StartsWith(x.Url.AbsoluteUri));

                    if (validExtensionLessUrl)
                    {
                        extensionLessExtension = RemoteFile.RemoteFileWhiteListExtensions.First(
                            x => x.ExtensionLess && requestPath.StartsWith(x.Url.AbsoluteUri)).ImageFormat;
                    }
                }
            }
            else
            {
                requestPath = HostingEnvironment.MapPath(request.Path);
                queryString = HttpUtility.UrlDecode(request.QueryString.ToString());
            }

            // Only process requests that pass our sanitizing filter.
            if ((ImageHelpers.IsValidImageExtension(requestPath) || validExtensionLessUrl) && !string.IsNullOrWhiteSpace(queryString))
            {
                // Replace any presets in the querystring with the actual value.
                queryString = this.ReplacePresetsInQueryString(queryString);

                string fullPath  = string.Format("{0}?{1}", requestPath, queryString);
                string imageName = Path.GetFileName(requestPath);

                if (validExtensionLessUrl && !string.IsNullOrWhiteSpace(extensionLessExtension))
                {
                    fullPath = requestPath;

                    if (!string.IsNullOrWhiteSpace(urlParameters))
                    {
                        string hashedUrlParameters = urlParameters.ToMD5Fingerprint();

                        // TODO: Add hash for querystring parameters.
                        imageName += hashedUrlParameters;
                        fullPath  += hashedUrlParameters;
                    }

                    imageName += "." + extensionLessExtension;
                    fullPath  += extensionLessExtension + "?" + queryString;
                }

                // Create a new cache to help process and cache the request.
                DiskCache cache = new DiskCache(request, requestPath, fullPath, imageName, isRemote);

                // Since we are now rewriting the path we need to check again that the current user has access
                // to the rewritten path.
                // Get the user for the current request
                // If the user is anonymous or authentication doesn't work for this suffix avoid a NullReferenceException
                // in the UrlAuthorizationModule by creating a generic identity.
                string virtualCachedPath = cache.GetVirtualCachedPath();

                IPrincipal user = context.User ?? new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[0]);

                // Do we have permission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal?
                PermissionSet permission = new PermissionSet(PermissionState.None);
                permission.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted));
                bool hasPermission = permission.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
                bool isAllowed     = true;

                // Run the rewritten path past the auth system again, using the result as the default "AllowAccess" value
                if (hasPermission && !context.SkipAuthorization)
                {
                    isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualCachedPath, user, "GET");
                }

                if (isAllowed)
                {
                    // Is the file new or updated?
                    bool isNewOrUpdated = await cache.IsNewOrUpdatedFileAsync();

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        string cachedPath = cache.CachedPath;

                        // Process the image.
                        using (ImageFactory imageFactory = new ImageFactory())
                        {
                            if (isRemote)
                            {
                                Uri uri = new Uri(requestPath + "?" + urlParameters);

                                RemoteFile remoteFile = new RemoteFile(uri, false);

                                // Prevent response blocking.
                                WebResponse webResponse = await remoteFile.GetWebResponseAsync().ConfigureAwait(false);

                                SemaphoreSlim semaphore = GetSemaphoreSlim(cachedPath);
                                try
                                {
                                    semaphore.Wait();

                                    using (MemoryStream memoryStream = new MemoryStream())
                                    {
                                        using (WebResponse response = webResponse)
                                        {
                                            using (Stream responseStream = response.GetResponseStream())
                                            {
                                                if (responseStream != null)
                                                {
                                                    responseStream.CopyTo(memoryStream);

                                                    // Process the Image
                                                    imageFactory.Load(memoryStream)
                                                    .AddQueryString(queryString)
                                                    .AutoProcess()
                                                    .Save(cachedPath);

                                                    // Store the response type in the context for later retrieval.
                                                    context.Items[CachedResponseTypeKey] = imageFactory.MimeType;

                                                    // Ensure that the LastWriteTime property of the source and cached file match.
                                                    Tuple <DateTime, DateTime> creationAndLastWriteDateTimes = await cache.SetCachedLastWriteTimeAsync();

                                                    // Add to the cache.
                                                    cache.AddImageToCache(creationAndLastWriteDateTimes);

                                                    // Trim the cache.
                                                    await cache.TrimCachedFolderAsync(cachedPath);
                                                }
                                            }
                                        }
                                    }
                                }
                                finally
                                {
                                    semaphore.Release();
                                }
                            }
                            else
                            {
                                // Check to see if the file exists.
                                // ReSharper disable once AssignNullToNotNullAttribute
                                FileInfo fileInfo = new FileInfo(requestPath);

                                if (!fileInfo.Exists)
                                {
                                    throw new HttpException(404, "No image exists at " + fullPath);
                                }

                                SemaphoreSlim semaphore = GetSemaphoreSlim(cachedPath);
                                try
                                {
                                    semaphore.Wait();

                                    // Process the Image
                                    imageFactory.Load(fullPath).AutoProcess().Save(cachedPath);

                                    // Store the response type in the context for later retrieval.
                                    context.Items[CachedResponseTypeKey] = imageFactory.MimeType;

                                    // Ensure that the LastWriteTime property of the source and cached file match.
                                    Tuple <DateTime, DateTime> creationAndLastWriteDateTimes = await cache.SetCachedLastWriteTimeAsync();

                                    // Add to the cache.
                                    cache.AddImageToCache(creationAndLastWriteDateTimes);

                                    // Trim the cache.
                                    await cache.TrimCachedFolderAsync(cachedPath);
                                }
                                finally
                                {
                                    semaphore.Release();
                                }
                            }
                        }
                    }

                    string incomingEtag = context.Request.Headers["If-None-Match"];

                    if (incomingEtag != null && !isNewOrUpdated)
                    {
                        // Explicitly set the Content-Length header so the client doesn't wait for
                        // content but keeps the connection open for other requests
                        context.Response.AddHeader("Content-Length", "0");
                        context.Response.StatusCode      = (int)HttpStatusCode.NotModified;
                        context.Response.SuppressContent = true;
                        context.Response.AddFileDependency(context.Server.MapPath(cache.GetVirtualCachedPath()));
                        this.SetHeaders(context, (string)context.Items[CachedResponseTypeKey]);

                        if (!isRemote)
                        {
                            return;
                        }
                    }

                    string virtualPath = cache.GetVirtualCachedPath();

                    // The cached file is valid so just rewrite the path.
                    context.RewritePath(virtualPath, false);
                }
                else
                {
                    throw new HttpException(403, "Access denied");
                }
            }
            else if (isRemote)
            {
                // Just repoint to the external url.
                HttpContext.Current.Response.Redirect(requestPath);
            }
        }
Example #21
0
        /// <summary>
        /// Renders A tag and possibly a lock icon
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="item"></param>
        /// <param name="itemWidth"></param>
        private void RenderItem(HtmlTextWriter writer, MenuExItem item, Unit itemWidth)
        {
            if (!string.IsNullOrEmpty(item.ToolTip))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Title, item.ToolTip);
            }


            string iconName = string.Empty;

            string[]      y          = new string[] { "ui-button", "ui-widget", "ui-corner-all" };
            List <string> cssClasses = new List <string>(y);

            if (IsSamePageUrl(item))
            {
                cssClasses.Add("ui-state-active");
            }
            else
            {
                cssClasses.Add("ui-state-default");
                if (item.NavigateUrl.EndsWith("#"))
                {
                    writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "default");
                    iconName = "ui-icon-triangle-1-s";
                }
                else
                {
                    string url = this.ResolveUrl(item.NavigateUrl);
                    writer.AddAttribute(HtmlTextWriterAttribute.Href, url);

                    int  index = item.NavigateUrl.IndexOf('?');
                    bool isAccessible;
                    // Do not pass query string as part of URL
                    if (index < 0)
                    {
                        isAccessible = UrlAuthorizationModule.CheckUrlAccessForPrincipal(item.NavigateUrl, this.Page.User, "GET");
                    }
                    else
                    {
                        isAccessible = UrlAuthorizationModule.CheckUrlAccessForPrincipal(item.NavigateUrl.Substring(0, index), this.Page.User, "GET");
                    }
                    if (!isAccessible)
                    {
                        iconName = "ui-icon-locked";
                        cssClasses.Add("ui-priority-secondary");
                    }
                }
            }

            if (string.IsNullOrEmpty(iconName))
            {
                cssClasses.Add("ui-button-text-only");
            }
            else
            {
                cssClasses.Add("ui-button-text-icon-primary");
            }

            writer.AddAttribute(HtmlTextWriterAttribute.Class, string.Join(" ", cssClasses.ToArray()));
            if (itemWidth != Unit.Empty)
            {
                writer.AddStyleAttribute(HtmlTextWriterStyle.Width, itemWidth.ToString());
            }
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            if (!string.IsNullOrEmpty(iconName))
            {
                // Show lock icon
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "ui-button-icon-primary ui-icon " + iconName);
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.RenderEndTag();
            }

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ui-button-text");
            writer.RenderBeginTag(HtmlTextWriterTag.Span);
            writer.Write(item.Text);
            writer.RenderEndTag();      // span
            writer.RenderEndTag();      // a
        }
        public virtual bool GetIsAuthorized()
        {
            IController        controller  = null;
            RouteData          routeData   = null;
            VirtualHttpContext httpContext = null;
            var factory = ControllerBuilder.Current.GetControllerFactory();

            if (_pathSet)
            {
                if (Path.StartsWith("~"))
                {
                    var path = VirtualPathUtility.ToAppRelative(Path);
                    if (Global.VirtualPathProvider.FileExists(path) ||
                        Global.VirtualPathProvider.DirectoryExists(path))
                    {
                        // check hosting permissions
                        if (UrlAuthorizationModule.CheckUrlAccessForPrincipal(path, HttpContext.Current.User, "GET"))
                        {
                            return(true);
                        }
                    }

                    // get route date from path
                    httpContext = new VirtualHttpContext(Path);
                    routeData   = RouteTable.Routes.GetRouteData(httpContext);
                    if (routeData != null && routeData.Values.ContainsKey("controller"))
                    {
                        controller = factory.CreateController(new RequestContext(httpContext, routeData), routeData.Values["controller"].ToString());
                    }
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                routeData = new RouteData();
                routeData.Values.Add("controller", ControllerName);
                routeData.Values.Add("action", Action);
                httpContext = new VirtualHttpContext(new UrlHelper(HttpContext.Current.Request.RequestContext).RouteUrl(routeData.Values));
                controller  = factory.CreateController(new RequestContext(httpContext, routeData), ControllerName);
            }

            // check mvc based authentication defined in attributes
            if (controller != null)
            {
                // check access based on standard authorization
                if (!UrlAuthorizationModule.CheckUrlAccessForPrincipal(httpContext.Request.AppRelativeCurrentExecutionFilePath, HttpContext.Current.User, "GET"))
                {
                    return(false);
                }

                // check controller access
                var controllerContext    = new ControllerContext(httpContext, routeData, controller as ControllerBase);
                var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
                var actionDescriptor     = controllerDescriptor.FindAction(controllerContext,
                                                                           controllerContext.RouteData.Values["action"].
                                                                           ToString());

                // check method access
                if (VirtualHttpContext.ActionIsAuthorized(controllerContext, actionDescriptor))
                {
                    return(true);
                }
            }
            return(false);
        }
Example #23
0
        public virtual void PostResolveRequestCache(HttpContextBase context)
        {
            // Match the incoming URL against the route table
            RouteData routeData = RouteCollection.GetRouteData(context);

            // Do nothing if no route found
            if (routeData == null)
            {
                return;
            }

            // If a route was found, get an IHttpHandler from the route's RouteHandler
            IRouteHandler routeHandler = routeData.RouteHandler;

            if (routeHandler == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              SR.GetString(SR.UrlRoutingModule_NoRouteHandler)));
            }

            // This is a special IRouteHandler that tells the routing module to stop processing
            // routes and to let the fallback handler handle the request.
            if (routeHandler is StopRoutingHandler)
            {
                return;
            }

            RequestContext requestContext = new RequestContext(context, routeData);

            // Dev10 766875	Adding RouteData to HttpContext
            context.Request.RequestContext = requestContext;

            IHttpHandler httpHandler = routeHandler.GetHttpHandler(requestContext);

            if (httpHandler == null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentUICulture,
                              SR.GetString(SR.UrlRoutingModule_NoHttpHandler),
                              routeHandler.GetType()));
            }

            if (httpHandler is UrlAuthFailureHandler)
            {
                if (FormsAuthenticationModule.FormsAuthRequired)
                {
                    UrlAuthorizationModule.ReportUrlAuthorizationFailure(HttpContext.Current, this);
                    return;
                }
                else
                {
                    throw new HttpException(401, SR.GetString(SR.Assess_Denied_Description3));
                }
            }

            // Remap IIS7 to our handler
            context.RemapHandler(httpHandler);
        }
Example #24
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Fixes issue 10.
            bool   isRemote    = request.Path.EndsWith(RemotePrefix, StringComparison.OrdinalIgnoreCase);
            string requestPath = string.Empty;
            string queryString = string.Empty;

            if (isRemote)
            {
                // We need to split the querystring to get the actual values we want.
                string urlDecode = HttpUtility.UrlDecode(request.QueryString.ToString());

                if (!string.IsNullOrWhiteSpace(urlDecode))
                {
                    // UrlDecode seems to mess up in some circumstance.
                    if (urlDecode.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
                    {
                        urlDecode = urlDecode.Replace(":/", "://");
                    }

                    string[] paths = urlDecode.Split('?');

                    requestPath = paths[0];

                    if (paths.Length > 1)
                    {
                        queryString = paths[1];
                    }
                }
            }
            else
            {
                requestPath = HostingEnvironment.MapPath(request.Path);
                queryString = HttpUtility.UrlDecode(request.QueryString.ToString());
            }

            // Only process requests that pass our sanitizing filter.
            if (ImageUtils.IsValidImageExtension(requestPath) && !string.IsNullOrWhiteSpace(queryString))
            {
                string fullPath  = string.Format("{0}?{1}", requestPath, queryString);
                string imageName = Path.GetFileName(requestPath);

                // Create a new cache to help process and cache the request.
                DiskCache cache = new DiskCache(request, requestPath, fullPath, imageName, isRemote);

                // Since we are now rewriting the path we need to check again that the current user has access
                // to the rewritten path.
                // Get the user for the current request
                // If the user is anonymous or authentication doesn't work for this suffix avoid a NullReferenceException
                // in the UrlAuthorizationModule by creating a generic identity.
                string virtualCachedPath = cache.GetVirtualCachedPath();

                IPrincipal user = context.User
                                  ?? new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[0]);

                // Do we have permission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal?
                PermissionSet permission = new PermissionSet(PermissionState.None);
                permission.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted));
                bool hasPermission = permission.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);

                bool isAllowed = true;

                // Run the rewritten path past the auth system again, using the result as the default "AllowAccess" value
                if (hasPermission && !context.SkipAuthorization)
                {
                    isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualCachedPath, user, "GET");
                }

                if (isAllowed)
                {
                    // Is the file new or updated?
                    bool isNewOrUpdated = await cache.IsNewOrUpdatedFileAsync();

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        // Process the image.
                        using (ImageFactory imageFactory = new ImageFactory())
                        {
                            if (isRemote)
                            {
                                Uri uri = new Uri(requestPath);

                                RemoteFile remoteFile = new RemoteFile(uri, false);

                                // Prevent response blocking.
                                WebResponse webResponse = await remoteFile.GetWebResponseAsync().ConfigureAwait(false);

                                using (MemoryStream memoryStream = new MemoryStream())
                                {
                                    using (WebResponse response = webResponse)
                                    {
                                        using (Stream responseStream = response.GetResponseStream())
                                        {
                                            if (responseStream != null)
                                            {
                                                // Trim the cache.
                                                await cache.TrimCachedFoldersAsync();

                                                responseStream.CopyTo(memoryStream);

                                                imageFactory.Load(memoryStream)
                                                .AddQueryString(queryString)
                                                .Format(ImageUtils.GetImageFormat(imageName))
                                                .AutoProcess().Save(cache.CachedPath);

                                                // Ensure that the LastWriteTime property of the source and cached file match.
                                                DateTime dateTime = await cache.SetCachedLastWriteTimeAsync();

                                                // Add to the cache.
                                                await cache.AddImageToCacheAsync(dateTime);
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // Trim the cache.
                                await cache.TrimCachedFoldersAsync();

                                imageFactory.Load(fullPath).AutoProcess().Save(cache.CachedPath);

                                // Ensure that the LastWriteTime property of the source and cached file match.
                                DateTime dateTime = await cache.SetCachedLastWriteTimeAsync();

                                // Add to the cache.
                                await cache.AddImageToCacheAsync(dateTime);
                            }
                        }
                    }

                    // Store the response type in the context for later retrieval.
                    context.Items[CachedResponseTypeKey] = ImageUtils.GetResponseType(fullPath).ToDescription();

                    // The cached file is valid so just rewrite the path.
                    context.RewritePath(cache.GetVirtualCachedPath(), false);
                }
                else
                {
                    throw new HttpException(403, "Access denied");
                }
            }
        }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="context">
        /// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
        /// references to the intrinsic server objects
        /// </param>
        /// <returns>
        /// The <see cref="T:System.Threading.Tasks.Task"/>.
        /// </returns>
        private async Task ProcessImageAsync(HttpContext context)
        {
            HttpRequest request = context.Request;

            // Should we ignore this request?
            if (request.RawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE"))
            {
                return;
            }

            IImageService currentService = this.GetImageServiceForRequest(request);

            if (currentService != null)
            {
                bool   isFileLocal    = currentService.IsFileLocalService;
                bool   hasMultiParams = request.Url.ToString().Count(f => f == '?') > 1;
                string requestPath    = string.Empty;
                string queryString    = string.Empty;
                string urlParameters  = string.Empty;

                if (hasMultiParams)
                {
                    // We need to split the querystring to get the actual values we want.
                    string urlDecode = HttpUtility.UrlDecode(request.QueryString.ToString());

                    if (!string.IsNullOrWhiteSpace(urlDecode))
                    {
                        // UrlDecode seems to mess up in some circumstance.
                        if (urlDecode.IndexOf("://", StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            urlDecode = urlDecode.Replace(":/", "://");
                        }

                        string[] paths = urlDecode.Split('?');

                        requestPath = paths[0];

                        // Handle extension-less urls.
                        if (paths.Length > 2)
                        {
                            queryString   = paths[2];
                            urlParameters = paths[1];
                        }
                        else if (paths.Length > 1)
                        {
                            queryString = paths[1];
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(currentService.Prefix))
                    {
                        requestPath = HostingEnvironment.MapPath(request.Path);
                        queryString = HttpUtility.UrlDecode(request.QueryString.ToString());
                    }
                    else
                    {
                        requestPath = HttpUtility.UrlDecode(request.QueryString.ToString());
                    }
                }

                // Replace any presets in the querystring with the actual value.
                queryString = this.ReplacePresetsInQueryString(queryString);

                // Execute the handler which can change the querystring
                queryString = this.CheckQuerystringHandler(queryString, request.RawUrl);

                // If the current service doesn't require a prefix, don't fetch it.
                // Let the static file handler take over.
                if (string.IsNullOrWhiteSpace(currentService.Prefix) && string.IsNullOrWhiteSpace(queryString))
                {
                    return;
                }

                string parts    = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty;
                string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString);
                object resourcePath;

                if (hasMultiParams)
                {
                    resourcePath = string.IsNullOrWhiteSpace(urlParameters)
                        ? new Uri(requestPath, UriKind.RelativeOrAbsolute)
                        : new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute);
                }
                else
                {
                    resourcePath = requestPath;
                }

                // Check whether the path is valid for other requests.
                if (resourcePath == null || !currentService.IsValidRequest(resourcePath.ToString()))
                {
                    return;
                }

                // Create a new cache to help process and cache the request.
                DiskCache cache      = new DiskCache(requestPath, fullPath, queryString);
                string    cachedPath = cache.CachedPath;

                // Since we are now rewriting the path we need to check again that the current user has access
                // to the rewritten path.
                // Get the user for the current request
                // If the user is anonymous or authentication doesn't work for this suffix avoid a NullReferenceException
                // in the UrlAuthorizationModule by creating a generic identity.
                string virtualCachedPath = cache.VirtualCachedPath;

                IPrincipal user = context.User ?? new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[0]);

                // Do we have permission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal?
                PermissionSet permission = new PermissionSet(PermissionState.None);
                permission.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted));
                bool hasPermission = permission.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);

                bool isAllowed = true;

                // Run the rewritten path past the authorization system again.
                // We can then use the result as the default "AllowAccess" value
                if (hasPermission && !context.SkipAuthorization)
                {
                    isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualCachedPath, user, "GET");
                }

                if (isAllowed)
                {
                    // Is the file new or updated?
                    bool isNewOrUpdated = cache.IsNewOrUpdatedFile(cachedPath);

                    // Only process if the file has been updated.
                    if (isNewOrUpdated)
                    {
                        // Process the image.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifMetaData != null && preserveExifMetaData.Value))
                        {
                            using (await this.locker.LockAsync(cachedPath))
                            {
                                byte[] imageBuffer = await currentService.GetImage(resourcePath);

                                using (MemoryStream memoryStream = new MemoryStream(imageBuffer))
                                {
                                    // Reset the position of the stream to ensure we're reading the correct part.
                                    memoryStream.Position = 0;

                                    // Process the Image
                                    imageFactory.Load(memoryStream).AutoProcess(queryString).Save(cachedPath);

                                    // Add to the cache.
                                    cache.AddImageToCache(cachedPath);

                                    // Store the cached path, response type, and cache dependency in the context for later retrieval.
                                    context.Items[CachedPathKey]                = cachedPath;
                                    context.Items[CachedResponseTypeKey]        = imageFactory.CurrentImageFormat.MimeType;
                                    context.Items[CachedResponseFileDependency] = new List <string> {
                                        cachedPath
                                    };
                                }
                            }
                        }
                    }

                    // Image is from the cache so the mime-type will need to be set.
                    if (context.Items[CachedResponseTypeKey] == null)
                    {
                        string mimetype = ImageHelpers.GetMimeType(cachedPath);

                        if (!string.IsNullOrEmpty(mimetype))
                        {
                            context.Items[CachedResponseTypeKey] = mimetype;
                        }
                    }

                    if (context.Items[CachedResponseFileDependency] == null)
                    {
                        if (isFileLocal)
                        {
                            // Some services might only provide filename so we can't monitor for the browser.
                            context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
                                ? new List <string> {
                                cachedPath
                            }
                                : new List <string> {
                                requestPath, cachedPath
                            };
                        }
                        else
                        {
                            context.Items[CachedResponseFileDependency] = new List <string> {
                                cachedPath
                            };
                        }
                    }

                    // The cached file is valid so just rewrite the path.
                    context.RewritePath(virtualCachedPath, false);
                }
                else
                {
                    throw new HttpException(403, "Access denied");
                }
            }
        }
 public virtual bool CheckUrlAccessForPrincipal(string path)
 {
     return(UrlAuthorizationModule.CheckUrlAccessForPrincipal(path, PrincipalInfo.CurrentPrincipal, "GET"));
 }
Example #27
0
 private bool CheckUrlAccessWithAssert(string virtualPath, RequestContext requestContext, IPrincipal user)
 {
     return(UrlAuthorizationModule.CheckUrlAccessForPrincipal(virtualPath, user, requestContext.HttpContext.Request.HttpMethod));
 }