Beispiel #1
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            // Enable CSRF protection at the pipeline level
            // to be able to use it in AuthorizationModule.cs
            Csrf.Enable(pipelines);

            base.ApplicationStartup(container, pipelines);
        }
Beispiel #2
0
        /// <summary>
        /// Modifies our application startup to enable CSRF, and reparse thrown exceptions into messages and status codes.
        /// </summary>
        /// <remarks>
        /// To use this functionality, within every 'form' block, after all the inputs add '@Html.AntiForgeryToken()'.
        /// Then, within your POST reception, call 'this.ValidateCsrfToken();, catch the CsrfValidationException, and handle the result appropriately.
        /// </remarks>
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            Csrf.Enable(pipelines);

            pipelines.BeforeRequest += (ctx) =>
            {
                NancyContext context = ctx as NancyContext;
                logger.Info(context.Request.UserHostAddress + ": " + context.Request.Url);

                if (Global.SystemStats.AddCall(context.Request.UserHostAddress))
                {
                    logger.Info($"Throttling a request from {context.Request.UserHostAddress}");
                    return(this.GenerateJsonException(new ExcessiveQueriesException(), HttpStatusCode.TooManyRequests));
                }

                // Technically this is 7.4% over 1 MiB. I'm not going to be pedantic.
                int           maxIterations = 12;
                int           hundredKiB    = 100 * 1024;
                byte[]        hundredK      = new byte[hundredKiB];
                RequestStream requestStream = context.Request.Body;
                for (int i = 0; i < maxIterations; i++)
                {
                    // This unfortunately means we're processing the request stream twice.
                    if (requestStream.Read(hundredK, 0, hundredKiB) != hundredKiB)
                    {
                        // The request is under 1 MiB, so continue processing. Reset the stream so deserializing the JSON works.
                        requestStream.Seek(0, SeekOrigin.Begin);
                        return(null);
                    }
                }

                logger.Info($"Request from {context.Request.UserHostAddress} to {context.Request.Url} over 1 MiB");
                return(this.GenerateJsonException(new ExcessiveNapackException(), HttpStatusCode.BadRequest));
            };

            StaticConfiguration.DisableErrorTraces = false;
            pipelines.OnError += (context, exception) =>
            {
                HttpStatusCode code            = HttpStatusCode.InternalServerError;
                Exception      parsedException = exception as Exception;
                if (parsedException != null)
                {
                    if (!exceptionStatusCodeMapping.TryGetValue(parsedException.GetType(), out code))
                    {
                        code = HttpStatusCode.InternalServerError;
                    }
                }
                else
                {
                    parsedException = new Exception("Unable to decode the detected exception!");
                }

                logger.Warn($"Hit a {parsedException.GetType()} exception: {parsedException.Message}");
                return(this.GenerateJsonException(parsedException, code));
            };
        }
Beispiel #3
0
        protected override void ApplicationStartup(IKernel container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            Csrf.Enable(pipelines);

            pipelines.BeforeRequest.AddItemToStartOfPipeline(FlowPrincipal);
            pipelines.BeforeRequest.AddItemToStartOfPipeline(SetCulture);
        }
        public Controller(string name, ControllerType controllerType, string definition, Csrf csrfProtection, bool authorise)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (definition == null) throw new ArgumentNullException("definition");

            Name = name;
            ControllerType = controllerType;
            Definition = definition;
            CsrfProtection = csrfProtection;
            Authorise = authorise;
        }
Beispiel #5
0
        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            //读数据库
            SQLiteHelper.Init(new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataBase")));

            StaticConfiguration.EnableRequestTracing = true;
            //显示详细错误信息
            StaticConfiguration.DisableErrorTraces = false;
            //启用AntiToken
            Csrf.Enable(pipelines);
        }
Beispiel #6
0
 protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
 {
     base.ApplicationStartup(container, pipelines);
     //数据库
     // MYSQLHelper.ConnectionString = ConfigurationManager.ConnectionStrings["conn"].ToString();
     DataAccessCenter.Load();
     //请求跟踪
     //StaticConfiguration.EnableRequestTracing = true;暂时不打开,性能消耗很大
     //显示详细错误信息
     StaticConfiguration.DisableErrorTraces = false;
     //启用AntiToken
     Csrf.Enable(pipelines);
 }
        private async Task <bool> ValidateAntiForgeryToken()
        {
            try
            {
                await Csrf.ValidateRequestAsync(this.Context);

                return(true);
            }
            catch (Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException)
            {
                return(false);
            }
        }
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Content"));
            Conventions.ViewLocationConventions.Add((viewName, model, context) => "Content/Views/" + viewName);

            Csrf.Enable(pipelines);
            CookieBasedSessions.Enable(pipelines, new CookieBasedSessionsConfiguration()
            {
                Serializer = new JsonSessionSerialiser()
            });
        }
Beispiel #9
0
        public void Should_be_able_to_disable_csrf()
        {
            var context = new NancyContext {
                Request = this.request, Response = this.response
            };

            context.Items[CsrfToken.DEFAULT_CSRF_KEY] = "TestingToken";

            Csrf.Disable(this.pipelines);
            this.pipelines.AfterRequest.Invoke(context);

            this.response.Cookies.Any(c => c.Name == CsrfToken.DEFAULT_CSRF_KEY).ShouldBeFalse();
        }
        protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => ctx.Response.Headers.Add("X-FRAME-OPTIONS", "DENY"));

            Csrf.Enable(pipelines);

            var formsConfig = new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/autenticar",
                UserMapper  = container.Resolve <IUserMapper>()
            };

            FormsAuthentication.Enable(pipelines, formsConfig);
        }
Beispiel #11
0
        public void ValidateCsrfToken_gets_provided_token_from_request_header_if_not_present_in_form_data()
        {
            // Given
            var token   = Csrf.GenerateTokenString();
            var context = new NancyContext();
            var module  = new FakeNancyModule {
                Context = context
            };

            // When
            context.Request = RequestWithHeader(CsrfToken.DEFAULT_CSRF_KEY, token);
            context.Request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, token);

            // Then
            module.ValidateCsrfToken();
        }
Beispiel #12
0
        public Controller(string name, ControllerType controllerType, string definition, Csrf csrfProtection, bool authorise)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (definition == null)
            {
                throw new ArgumentNullException("definition");
            }

            Name           = name;
            ControllerType = controllerType;
            Definition     = definition;
            CsrfProtection = csrfProtection;
            Authorise      = authorise;
        }
Beispiel #13
0
        public CsrfFixture()
        {
            this.pipelines = new MockPipelines();

            this.cryptographyConfiguration = CryptographyConfiguration.Default;
            var csrfStartup = new CsrfApplicationStartup(
                this.cryptographyConfiguration,
                new DefaultCsrfTokenValidator(this.cryptographyConfiguration));

            csrfStartup.Initialize(this.pipelines);
            Csrf.Enable(this.pipelines);

            this.request = new FakeRequest("GET", "/");

            this.optionsRequest = new FakeRequest("OPTIONS", "/");

            this.response = new Response();
        }
Beispiel #14
0
        public void ValidateCsrfToken_gets_provided_token_from_form_data()
        {
            // Given
            var token   = Csrf.GenerateTokenString();
            var context = new NancyContext {
                Request = this.request
            };
            var module = new FakeNancyModule {
                Context = context
            };

            // When
            context.Request.Form[CsrfToken.DEFAULT_CSRF_KEY] = token;
            context.Request.Cookies.Add(CsrfToken.DEFAULT_CSRF_KEY, token);

            // Then
            module.ValidateCsrfToken();
        }
Beispiel #15
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            // Password hasher using PBKDF2
            var saltedHash = new SaltedHash(
                _configuration.Encryption.SaltLength,
                _configuration.Encryption.HashLength,
                _configuration.Encryption.NumberOfIterations);

            container.Register <ISaltedHash, SaltedHash>(saltedHash);

            // Disable _Nancy
            DiagnosticsHook.Disable(pipelines);

            // Takes care of outputting the CSRF token to Cookies
            Csrf.Enable(pipelines);

            // Don't show errors when we are in release
            StaticConfiguration.DisableErrorTraces = !StaticConfiguration.IsRunningDebug;

            // Wire up flowing of OWIN user to a Nancy one
            pipelines.BeforeRequest.AddItemToStartOfPipeline(FlowPrincipal);

            // TODO: Remove dummy data
            //var user = new CloudEntity<User>
            //{
            //    PartitionKey = "*****@*****.**",
            //    RowKey = "Manual",
            //    Value = new User
            //    {
            //        Email = "*****@*****.**",
            //        DisplayName = "David Cumps",
            //        HashAndSalt = saltedHash.GetHashAndSaltString("admin")
            //    }
            //};

            //var tableClient = container.Resolve<CloudStorageAccount>().CreateCloudTableClient();
            //tableClient.RetryPolicy = new NoRetry();
            //var t = new TableStorageProvider(tableClient);
            //t.CreateTable("User");
            //t.Insert("User", user);
        }
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            Csrf.Enable(pipelines);

            this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("moo", "Content"));

            CookieBasedSessions.Enable(pipelines);

            pipelines.AfterRequest += (ctx) =>
            {
                var username = ctx.Request.Query.pirate;

                if (username.HasValue)
                {
                    ctx.Response = new HereBeAResponseYouScurvyDog(ctx.Response);
                }
            };
        }
        public void Initialize()
        {
            var bootstrapper = new ConfigurableBootstrapper((cfg) =>
            {
                cfg.Module <HomeModule>();
                cfg.Dependency <IUserMapper>(new UsuarioMapper());
                cfg.CsrfTokenValidator(new FakeCsrfTokenValidator());
                cfg.ApplicationStartup((container, pipelines) =>
                {
                    Csrf.Enable(pipelines);
                    var formsConfig = new FormsAuthenticationConfiguration()
                    {
                        RedirectUrl = "~/autenticar",
                        UserMapper  = container.Resolve <IUserMapper>()
                    };

                    FormsAuthentication.Enable(pipelines, formsConfig);
                });
            });

            browser = new Browser(bootstrapper);
        }
Beispiel #18
0
 public void Initialize(IPipelines pipelines) =>
 Csrf.Enable(pipelines);
Beispiel #19
0
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            Csrf.Disable(pipelines);
        }
Beispiel #20
0
        public static string GetOrganName(Gdxj xj, GetOrganDictClass godc)
        {
            string result = string.Empty;

            try
            {
                AjaxCommand.Send.ContextCommandParams ccp = new AjaxCommand.Send.ContextCommandParams()
                {
                    @params = godc
                };
                string json = JsonConvert.SerializeObject(ccp, Formatting.Indented);
                string html = RequestHelper.GetByPostJsonWithCsrf(setting.url.QueryOrganDicUrl, json, ref xj.GdxjCookie.cookie, Csrf.GetCsrfToken(), setting.url.QueryGradeRefererUrl);
                ReceiveOrganNameClass receiveData = JsonConvert.DeserializeObject <ReceiveOrganNameClass>(html);
                if (receiveData.map != null)
                {
                    result = receiveData.map.text;
                }
            }
            catch (Exception e)
            {
                throw (e);
            }
            return(result);
        }
Beispiel #21
0
        private static ReceiveSchoolInfoClass GetSchoolInfo(Gdxj xj, string schoolID)
        {
            ReceiveSchoolInfoClass result = new ReceiveSchoolInfoClass();
            GetSchoolInfoClass     gsic   = new GetSchoolInfoClass(schoolID);

            try
            {
                AjaxCommand.Send.ContextCommandParams ccp = new AjaxCommand.Send.ContextCommandParams()
                {
                    @params = gsic
                };
                string json = JsonConvert.SerializeObject(ccp, Formatting.Indented);
                string html = RequestHelper.GetByPostJsonWithCsrf(setting.url.QuerySchoolInfoUrl, json, ref xj.GdxjCookie.cookie, Csrf.GetCsrfToken(), setting.url.QueryGradeRefererUrl);
                result = JsonConvert.DeserializeObject <ReceiveSchoolInfoClass>(html);
            }
            catch (Exception e)
            {
                throw (e);
            }
            return(result);
        }
Beispiel #22
0
 protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
 {
     Csrf.Enable(pipelines);
     FruitOfTheDay.Enable(pipelines);
     CookieBasedSessions.Enable(pipelines);
 }
Beispiel #23
0
        private static Dictionary <string, string> GetData(Gdxj xj, SendDataClass gdc)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();
            string url = (gdc.GetType() == typeof(GetGeneralDictClass)) ? setting.url.QueryGeneralDicUrl : setting.url.QueryForDicUrl;

            try
            {
                AjaxCommand.Send.ContextCommandParams ccp = new AjaxCommand.Send.ContextCommandParams()
                {
                    @params = gdc
                };
                string json = JsonConvert.SerializeObject(ccp, Formatting.Indented);
                string html = RequestHelper.GetByPostJsonWithCsrf(url, json, ref xj.GdxjCookie.cookie, Csrf.GetCsrfToken(), setting.url.QueryGradeRefererUrl);
                ReceiveDictDataClass receiveStudentData = JsonConvert.DeserializeObject <ReceiveDictDataClass>(html);
                receiveStudentData.rows.ForEach(r =>
                {
                    result.Add(r.value, r.text);
                });
            }
            catch (Exception e)
            {
                throw (e);
            }
            return(result);
        }
Beispiel #24
0
 protected override void ApplicationStartup(global::Nancy.TinyIoc.TinyIoCContainer container, IPipelines pipelines)
 {
     Csrf.Disable(pipelines);
 }
Beispiel #25
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            container.Register <IDatabaseManager, DBStateResolver>().AsSingleton();

#if !DEBUG
            DiagnosticsHook.Disable(pipelines);
#else
            StaticConfiguration.EnableRequestTracing = true;
#endif

            redisServer = new RedisServer(LogError, LogDebug, (new RedisConfig()).Address);
            container.Register <RedisServer>(redisServer);

            var serviceId = redisServer.GenerateUniqueId().Result;
            container.Register <IServerConfigService, WebServerConfigService>(new WebServerConfigService(redisServer, serviceId));

            sessionService = container.Resolve <SessionService>();

            // CSRF that uses Redis for shared token generation. Tokens currently don't expire.
            Csrf.Enable(pipelines, new CryptographyConfiguration(
                            new RijndaelEncryptionProvider(new RedisBasedKeyGenerator(redisServer)),
                            new DefaultHmacProvider(new RedisBasedKeyGenerator(redisServer)))
                        );

            pipelines.BeforeRequest.AddItemToEndOfPipeline(ctx =>
            {
                var origin = ctx.Request.Headers["Origin"].FirstOrDefault();

                if (origin == null)
                {
                    return(null);
                }

                var matches = corsDomains.FirstOrDefault(
                    allowed => Regex.IsMatch(origin, "^" + allowed + "$", RegexOptions.IgnoreCase));

                // No matches, so let's abort.
                if (matches == null)
                {
                    var responseJson = (Response)"CORS not allowed.";

                    responseJson.ContentType = "application/json";
                    responseJson.StatusCode  = HttpStatusCode.BadRequest;

                    return(responseJson);
                }
                return(null);
            });

            pipelines.AfterRequest.AddItemToEndOfPipeline(ctx =>
            {
                var origin = ctx.Request.Headers["Origin"].FirstOrDefault();

                if (origin == null)
                {
                    return;
                }

                ctx.Response.Headers.Add("Access-Control-Allow-Origin", origin);
                ctx.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
                ctx.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
                ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Accept,Origin,Content-type");
                ctx.Response.Headers.Add("Access-Control-Expose-Headers", "Accept,Origin,Content-type");
            });

            pipelines.BeforeRequest.AddItemToEndOfPipeline(ProcessSessionAuth);

            pipelines.OnError += (ctx, ex) => {
                throw ex;
            };
        }
Beispiel #26
0
 public IWire EnableCsrf(IPipelines pipelines)
 {
     NancyStackWiring.ConfigurationOptions.CsrfEnabled = true;
     Csrf.Enable(pipelines);
     return(this);
 }