Ejemplo n.º 1
0
        /// <summary>
        /// Checks if the current request is coming from an authenticated Umbraco User
        /// </summary>
        /// <param name="httpApp">The current HttpApplication</param>
        /// <returns>Whether or not the request is from an authenticated Umbraco User</returns>
        public static bool IsRequestAuthenticatedUmbracoUser(HttpApplication httpApp)
        {
            var httpContext   = new HttpContextWrapper(httpApp.Context);
            var umbAuthTicket = httpContext.GetUmbracoAuthTicket();

            return(httpContext.AuthenticateCurrentRequest(umbAuthTicket, true));
        }
        public bool Authorize(DashboardContext context)
        {
            var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
            var ticket             = httpContextWrapper.GetUmbracoAuthTicket();

            httpContextWrapper.AuthenticateCurrentRequest(ticket, true);
            var user = UmbracoContext.Current.Security.CurrentUser;

            return(user != null && user.AllowedSections.Contains("developer"));
        }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public bool Authorize(DashboardContext context)
        {
            var httpContext = new HttpContextWrapper(HttpContext.Current);
            var ticket      = httpContext.GetUmbracoAuthTicket();

            httpContext.AuthenticateCurrentRequest(ticket, true);
            var user = Current.UmbracoContext.Security.CurrentUser;

            return(user != null && user.Groups.Any(g => g.Alias == Umbraco.Core.Constants.Security.AdminGroupAlias));
        }
        public bool Authorize(DashboardContext context)
        {
            var http   = new HttpContextWrapper(HttpContext.Current);
            var ticket = http.GetUmbracoAuthTicket();

            http.AuthenticateCurrentRequest(ticket, true);

            var user = UmbracoContext.Current.Security.CurrentUser;

            return(user != null && user.UserType.Alias == "admin");
        }
        public static bool AuthenticateTicket()
        {
            // see http://issues.umbraco.org/issue/U4-6342#comment=67-19466 (from http://issues.umbraco.org/issue/U4-6332)
            var http   = new HttpContextWrapper(HttpContext.Current);
            var ticket = http.GetUmbracoAuthTicket();

            if (ticket != null)
            {
                return(http.AuthenticateCurrentRequest(ticket, true));
            }
            return(false);
        }
        /// <summary>
        /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office
        /// so we'll force authentication.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            //If this is not a back office request, then the module won't have authenticated it, in this case we
            // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior
            // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge
            if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false)
            {
                var http   = new HttpContextWrapper(Context);
                var ticket = http.GetUmbracoAuthTicket();
                http.AuthenticateCurrentRequest(ticket, true);
            }
        }
Ejemplo n.º 7
0
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            if (PackageHelpers.UmbracoVersion != "7.2.2")
            {
                return;
            }

            // Handle authentication stuff to counteract bug in Umbraco 7.2.2 (see U4-6342)
            HttpContextWrapper        http   = new HttpContextWrapper(Context);
            FormsAuthenticationTicket ticket = http.GetUmbracoAuthTicket();

            http.AuthenticateCurrentRequest(ticket, true);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Authorizes the user
        /// </summary>
        /// <param name="e"></param>
        /// <remarks>
        /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office
        /// so we'll force authentication.
        /// </remarks>
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            //If this is not a back office request, then the module won't have authenticated it, in this case we
            // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior
            // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge
            if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath) == false)
            {
                var http   = new HttpContextWrapper(Context);
                var ticket = http.GetUmbracoAuthTicket();
                http.AuthenticateCurrentRequest(ticket, true);
            }

            try
            {
                Security.ValidateCurrentUser(true);
                _hasValidated = true;

                if (!Security.ValidateUserApp(CurrentApp))
                {
                    var ex = new UserAuthorizationException(String.Format("The current user doesn't have access to the section/app '{0}'", CurrentApp));
                    LogHelper.Error <UmbracoEnsuredPage>(String.Format("Tried to access '{0}'", CurrentApp), ex);
                    throw ex;
                }
            }
            catch
            {
                // Clear content as .NET transfers rendered content.
                Response.Clear();

                // Some umbraco pages should not be loaded on timeout, but instead reload the main application in the top window. Like the treeview for instance
                if (RedirectToUmbraco)
                {
                    Response.Redirect(SystemDirectories.Umbraco + "/logout.aspx?t=" + Security.GetSessionId(), true);
                }
                else
                {
                    Response.Redirect(SystemDirectories.Umbraco + "/logout.aspx?redir=" + Server.UrlEncode(Request.RawUrl) + "&t=" + Security.GetSessionId(), true);
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Authorizes the user
        /// </summary>
        /// <param name="e"></param>
        /// <remarks>
        /// Checks if the page exists outside of the /umbraco route, in which case the request will not have been authenticated for the back office
        /// so we'll force authentication.
        /// </remarks>
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            //If this is not a back office request, then the module won't have authenticated it, in this case we
            // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior
            // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge
            if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, Current.Configs.Global()) == false)
            {
                var http   = new HttpContextWrapper(Context);
                var ticket = http.GetUmbracoAuthTicket();
                http.AuthenticateCurrentRequest(ticket, true);
            }

            try
            {
                Security.ValidateCurrentUser(true);
                _hasValidated = true;

                if (!Security.ValidateUserApp(CurrentApp))
                {
                    var ex = new SecurityException(String.Format("The current user doesn't have access to the section/app '{0}'", CurrentApp));
                    Current.Logger.Error <UmbracoEnsuredPage>(ex, "Tried to access '{CurrentApp}'", CurrentApp);
                    throw ex;
                }
            }
            catch
            {
                // Clear content as .NET transfers rendered content.
                Response.Clear();

                // Ensure the person is definitely logged out
                UmbracoContext.Current.Security.ClearCurrentLogin();

                // Redirect to the login page
                Response.Redirect(SystemDirectories.Umbraco + "#/login", true);
            }
        }
Ejemplo n.º 10
0
        /// <inheritdoc />
        public override bool Execute(IJob job, IConfiguration c)
        {
            AddMediaTypes();
            job.UnwatchWebRequests();

            if (!(c is MediaProtectionConfiguration config))
            {
                job.WriteJournal(new JournalMessage("Error: Config passed into Media Protection was not of the correct type"));
                return(false);
            }

            if (!config.Enable || !job.Environment.Enable)
            {
                return(true);
            }

            if (config.EnableHotLinkingProtection)
            {
                var domains = new List <string>();
                foreach (var domain in job.Environment.Domains)
                {
                    try
                    {
                        var uriBuilder = new UriBuilder(domain.Name);
                        domains.Add(uriBuilder.Host);
                    }
                    catch (Exception)
                    {
                        // Swallow
                    }
                }

                var regex = new Regex("^(" + string.Join("|", config.HotLinkingProtectedDirectories) + ")", RegexOptions.IgnoreCase);

                job.WatchWebRequests(PipeLineStages.BeginRequest, regex, 30000, (count, httpApp) =>
                {
                    var referrer = httpApp.Request.UrlReferrer;
                    if (referrer == null || String.IsNullOrWhiteSpace(referrer.Host) ||
                        referrer.Host.Equals(httpApp.Request.Url.Host, StringComparison.InvariantCultureIgnoreCase) ||
                        domains.Any(x => x.Equals(referrer.Host, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        //  This media is being accessed directly,
                        //  or from a browser that doesn't pass referrer info,
                        //  or from our own domain
                        //  so allow access
                        return(new WatchResponse(WatchResponse.Cycles.Continue));
                    }

                    job.WriteJournal(new JournalMessage($"Access was denied, {httpApp.Context.Request.UserHostAddress} from {referrer.Host} was trying to hotlink your media assets"));

                    //  Someone is trying to hotlink our media
                    httpApp.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    httpApp.Response.End();
                    return(new WatchResponse(WatchResponse.Cycles.Stop));
                });
            }

            if (!config.EnableMembersOnlyMedia)
            {
                return(true);
            }

            var mediaFolder = VirtualPathUtility.ToAbsolute(new Uri(Umbraco.Core.IO.SystemDirectories.Media, UriKind.Relative).ToString()) + "/";

            job.WatchWebRequests(PipeLineStages.BeginRequest, new Regex(mediaFolder, RegexOptions.IgnoreCase), 30100, (count, httpApp) =>
            {
                var httpContext   = new HttpContextWrapper(httpApp.Context);
                var umbAuthTicket = httpContext.GetUmbracoAuthTicket();

                //  If we have logged in as a backend user, then allow all access
                if (httpContext.AuthenticateCurrentRequest(umbAuthTicket, true))
                {
                    return(new WatchResponse(WatchResponse.Cycles.Continue));
                }

                var filename = httpApp.Request.Url.LocalPath;

                var secureMedia = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem(CacheKey + "F" + filename, () =>
                {
                    var umbracoContext = Umbraco.Web.UmbracoContext.Current;

                    if (umbracoContext == null)
                    {
                        var newHttpContext = new HttpContextWrapper(HttpContext.Current);
                        umbracoContext     = UmbracoContext.EnsureContext(
                            newHttpContext,
                            ApplicationContext.Current,
                            new Umbraco.Web.Security.WebSecurity(newHttpContext, ApplicationContext.Current),
                            UmbracoConfig.For.UmbracoSettings(),
                            UrlProviderResolver.Current.Providers,
                            true);
                    }

                    var mediaService = new UmbracoMediaService(umbracoContext);
                    var mediaId      = mediaService.Id(filename);

                    if (mediaId == null)
                    {
                        return(false);
                    }

                    var pathIdKeys      = new List <string>();
                    object accessRights = null;

                    var traverseId = mediaId;

                    //  We traverse up the ancestors until we either hit the root, or find our access rights
                    //  from either our special alias value or a cache value from a previous request
                    while (traverseId != null)
                    {
                        var cacheIdKey = CacheKey + "I" + traverseId;
                        accessRights   = ApplicationContext.Current.ApplicationCache.RuntimeCache.GetCacheItem(cacheIdKey);
                        if (accessRights != null)
                        {
                            break;
                        }

                        pathIdKeys.Add(cacheIdKey);
                        var memberOnly = mediaService.Value((int)traverseId, MemberOnlyAlias);
                        if (memberOnly == null)
                        {
                            accessRights = false;
                        }
                        else
                        {
                            switch (memberOnly)
                            {
                            case bool _:
                                accessRights = (bool)memberOnly ? 1 : 0;
                                break;

                            case int _:
                                accessRights = (int)memberOnly != 0;
                                break;

                            case string _:
                                //  Is a MNTP that states which member groups can access this media item
                                try
                                {
                                    accessRights = ((string)memberOnly).Split(',').Select(int.Parse).ToArray();
                                }
                                catch (Exception)
                                {
                                    //  Swallow conversion issues, and continue processing
                                }
                                break;
                            }
                            break;
                        }

                        traverseId = mediaService.ParentId((int)traverseId);
                    }

                    if (accessRights == null)
                    {
                        accessRights = false;
                    }

                    //  Give our descendants the same access rights as us
                    foreach (var key in pathIdKeys)
                    {
                        ApplicationContext.Current.ApplicationCache.RuntimeCache.InsertCacheItem(key, () => accessRights, _cacheLength);
                    }
                    return(accessRights);
                }, _cacheLength);

                if (secureMedia is bool b)
                {
                    if (b == false ||
                        (httpApp.Context.User != null && httpApp.Context.User.Identity.IsAuthenticated))
                    {
                        //  They are allowed to view this media
                        return(new WatchResponse(WatchResponse.Cycles.Continue));
                    }
                }

                if (secureMedia is int[] ints)
                {
                    if (ints.Length == 0)
                    {
                        //  They are allowed to view this media
                        return(new WatchResponse(WatchResponse.Cycles.Continue));
                    }

                    if (httpApp.Context.User.Identity.IsAuthenticated)
                    {
                        //  TODO: Need to handle when security is member group based
                        return(new WatchResponse(WatchResponse.Cycles.Continue));
                    }
                }
                job.WriteJournal(new JournalMessage($"An unauthenticated member tried to access {filename} with IP Address: {httpApp.Context.Request.UserHostAddress}"));

                //  You need to be logged in or be a member of the correct member group to see this media
                httpApp.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                httpApp.Response.End();
                return(new WatchResponse(WatchResponse.Cycles.Stop));
            });

            return(true);
        }