Implementing HTTPS Everywhere in ASP.Net MVC application.
Implementing HTTPS Everywhere in ASP.Net MVC application.
HTTPS everywhere is a common theme of the modern infosys topics. Despite of that when I google for implementation of HTTPS in ASP.Net MVC applications, I find only a handful of horrible questions on StackOverflow, about how to implement HTTPS only on certain pages (i.e. login page). There have been numerous rants about security holes awaiting for you down that path. And Troy Hunt will whack you over your had for doing that!
See that link above? Go and read it! Seriously. I’ll wait.
Have you read it? Troy there explains why you want to have HTTPS Everywhere on your site, not just on a login page. Listen to this guy, he knows what he is talking about.
Problem I faced when I wanted to implement complete “HTTPS Everywhere” in my MVC applications is lack of implementation instructions. I had a rough idea of what I needed to do, and now that I’ve done it a few times on different apps, my process is now ironed-out and I can share that with you here.
1. Redirect to HTTPS
Redirecting to HTTPS schema is pretty simple in modern MVC. All you need to know about is RequireHttpsAttribute. This is named as Attribute and can be used as an attribute on separate MVC controllers and even actions. And I hate it for that – it encourages for bad practices. But luckily this class is also implements IAuthorizationFilter interface, which means this can be used globally on the entire app as a filter.
Problem with this filter – once you add it to your app, you need to configure SSL on your development machine. If you work in team, all dev machines must be configured with SSL. If you allow people to work from home, their home machines must be configured to work with SSL. And configuring SSL on dev machines is a waste of time. Maybe there is a script that can do that automatically, but I could not find one quickly.
Instead of configuring SSL on local IIS, I decided to be a smart-ass and work around it. Quick study of source codehighlighted that the class is not sealed and I can just inherit this class. So I inherited RequireHttpsAttribute and added logic to ignore all local requests:
public class RequreSecureConnectionFilter : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.HttpContext.Request.IsLocal)
{
// when connection to the application is local, don't do any HTTPS stuff
return;
}
base.OnAuthorization(filterContext);
}
}
If you are lazy enough to follow the link to the source code, I’ll tell you all this attribute does is check if incoming request schema used is https (that is what Request.IsSecureConnection does), if not, redirect all GET request to https. And if request comes that is not secured and not GET, throw exception. I think this is a good-aggressive implementation.
One might argue that I’m creating a security hole by not redirecting to https on local requests. But if an intruder managed to do local requests on your server, you are toast anyway and SSl is not your priority at the moment.
I looked up what filterContext.HttpContext.Request.IsLocal does and how it can have an impact on security. Here is the source code:
public bool IsLocal {
get {
String remoteAddress = UserHostAddress;
// if unknown, assume not local
if (String.IsNullOrEmpty(remoteAddress))
return false;
// check if localhost
if (remoteAddress == "127.0.0.1" || remoteAddress == "::1")
return true;
// compare with local address
if (remoteAddress == LocalAddress)
return true;
return false;
}
}
This is decompiled implementation of System.Web.HttpRequest. UserHostAddress get client’s IP address. If IP is localhost (IPv4 or IPv6), return true. LocalAddress property returns servers IP address. So basically .IsLocal() does what it says on the tin. If request comes from the same IP the application is hosted on, return true. I see no issues here.
By the way, here are the unit tests for my implementation of the secure filter. Can’t go without unit testing on this one!
And don’t forget to add this filter to list of your global filters
public static class FilterConfig
{
public void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new RequreSecureConnectionFilter());
// other filters to follow...
}
}
2. Cookies
If you think that redirecting to https is enough, you are very wrong. You must take care of your cookies. And set all of them by default to be HttpOnly and SslOnly. Read Troy Hunt’s excellent blog post why you need your cookies to be secured.
You can secure your cookies in web.config pretty simple:
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>
The only issue with that is development stage. Again, if you developing locally you won’t be able to login to your application without https running locally. Solution to that is web.config transformation.
So in your web.config you should always have
<system.web>
<httpCookies httpOnlyCookies="true" />
</system.web>
and in your web.Release.config file add
<system.web>
<httpCookies httpOnlyCookies="true" requireSSL="true" lockItem="true" xdt:Transform="Replace" />
</system.web>
This secures your cookies when you publish your application. Simples!
3. Secure authentication cookie
Apart from all your cookies to be secure, you need to specifically require authentication cookie to be SslOnly. For that you need to add requireSSL="true" to your authentication/forms part of web.config. Again, this will require you to run your local IIS with https configured. Or you can do web.config transformation only for release. In your web.Release.config file add this into system.web section
<authentication mode="Forms">
<forms loginUrl="~/Logon/LogOn" timeout="2880" requireSSL="true" xdt:Transform="Replace"/>
</authentication>
4. Strict Transport Security Header
Strict Transport Security Header is http header that tells web-browsers only to use HTTPS when dealing with your web-application. This reduces the risks of SSL Strip attack. To add this header by default to your application you can add add this section to your web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" />
</customHeaders>
</httpProtocol>
</system.webServer>
Again, the same issue as before, developers will have to have SSL configured on their local machines. Or you can do that via web.config transformation. Add the following code to your web.Release.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=16070400; includeSubDomains" xdt:Transform="Insert" />
</customHeaders>
</httpProtocol>
</system.webServer>
5. Secure your WebApi
WebApi is very cool and default template for MVC application now comes with WebApi activated. Redirecting all MVC requests to HTTPS does not redirect WebApi requests. So even if you secured your MVC pipeline, your WebApi requests are still available via HTTP.
Unfortunately redirecting WebApi requests to HTTPS is not as simple as it is with MVC. There is no [RequireHttps]available, so you’ll have to make one yourself. Or copy the code below:
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
public class EnforceHttpsHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// if request is local, just serve it without https
object httpContextBaseObject;
if (request.Properties.TryGetValue("MS_HttpContext", out httpContextBaseObject))
{
var httpContextBase = httpContextBaseObject as HttpContextBase;
if (httpContextBase != null && httpContextBase.Request.IsLocal)
{
return base.SendAsync(request, cancellationToken);
}
}
// if request is remote, enforce https
if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
return Task<HttpResponseMessage>.Factory.StartNew(
() =>
{
var response = new HttpResponseMessage(HttpStatusCode.Forbidden)
{
Content = new StringContent("HTTPS Required")
};
return response;
});
}
return base.SendAsync(request, cancellationToken);
}
}
This is a global handler that rejects all non https requests to WebApi. I did not do any redirection (not sure this term is applicable to WebApi) because there is no excuse for clients to use HTTP first.
WARNING This approach couples WebApi to System.Web libraries and you won’t be able to use this code in self-hosed WebApi applications. But there is a better way to implement detection if request is local. I have not used it because my unit tests have been written before I learned about better way. And I’m too lazy to fix this -)
Don’t forget to add this handler as a global:
namespace MyApp.Web.App_Start
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// other configurations...
// make all web-api requests to be sent over https
config.MessageHandlers.Add(new EnforceHttpsHandler());
}
}
}
6. Set up automatic security scanner for your site
ASafaWeb is a great tool that checks for a basic security issues on your application. The best feature is scheduled scan. I’ve set all my applications to be scanned on weekly basis and if something fails, it emails me. So far this helped me once, when error pages on one of the apps were messed up. If not for this automated scan, the issue could have stayed there forever. So go and sign-up!
Conclusion
This is no way a complete guide on securing your application. But this will help you with one of the few steps you need to take to lock down your application.
In this Gist you can copy my web.Release.config transformation file, in case you got confused with my explanation.
Implementing HTTPS Everywhere in ASP.Net MVC application.的更多相关文章
- [转]剖析ASP.Net MVC Application
http://www.cnblogs.com/errorif/archive/2009/02/13/1389927.html 为了完全了解Asp.net MVC是怎样工作的,我将从零开始创建一个MVC ...
- 源码学习之ASP.NET MVC Application Using Entity Framework
源码学习的重要性,再一次让人信服. ASP.NET MVC Application Using Entity Framework Code First 做MVC已经有段时间了,但看了一些CodePle ...
- [转]Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)
本文转自:http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-a ...
- [转]Implementing User Authentication in ASP.NET MVC 6
本文转自:http://www.dotnetcurry.com/aspnet-mvc/1229/user-authentication-aspnet-mvc-6-identity In this ar ...
- [转]Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application (3 of 10)
本文转自:http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/sorting-fi ...
- Migrating an ASP.NET MVC application to ADFS authentication
I recently built an ASP.NET application at work to help track internal use of our products. It's bee ...
- ASP.NET MVC 5 -从控制器访问数据模型
在本节中,您将创建一个新的MoviesController类,并在这个Controller类里编写代码来取得电影数据,并使用视图模板将数据展示在浏览器里. 在开始下一步前,先Build一下应用程序(生 ...
- Demystifying ASP.NET MVC 5 Error Pages and Error Logging
出处:http://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging Error pages and error ...
- 【转】ASP.NET MVC 的最佳实践
[This post is based on a document authored by Ben Grover (a senior developer at Microsoft). It is ou ...
随机推荐
- Java容器:HashTable, synchronizedMap与ConcurrentHashMap
首先需要明确的是,不管使用那种Map,都不能保证公共混合调用的线程安全,只能保证单条操作的线程安全,在这一点上各Map不存在优劣. 前文中简单说过HashTable和synchronizedMap,其 ...
- 你真的会用Gson吗?Gson使用指南(3)
原文出处: 怪盗kidou 注:此系列基于Gson 2.4. 本次的主要内容: 字段过滤的几种方法 基于@Expose注解 基于版本 基于访问修饰符 基于策略(作者最常用) POJO与JSON的字段映 ...
- 使用nvm进行node多版本管理
nvm与Python的virtualenv和Ruby的rvm类似.NVM (Node Version Manager,Node多版本管理器)是一个通用的叫法,它目前有许多不同的实现.通常我们说的 nv ...
- useradd 命令的常见用法
在Linux系统中 useradd 是个很基本的命令,但是使用起来却很不直观.以至于在 Ubuntu 中居然添加了一个 adduser 命令来简化添加用户的操作.本文主要描述笔者在学习使用 usera ...
- VMware DHCP Service服务无法启动问题的解决
我的电脑出现VMware DHCP Service和VMware NAT Service两个服务无法启动的问题: 打开VMware主界面,菜单->编辑->虚拟网络编辑器: 勾选上“将主机虚 ...
- Python中结巴分词使用手记
手记实用系列文章: 1 结巴分词和自然语言处理HanLP处理手记 2 Python中文语料批量预处理手记 3 自然语言处理手记 4 Python中调用自然语言处理工具HanLP手记 5 Python中 ...
- 疯狂Java学习笔记(75)-----------NIO.2第一篇
Java 7引入了NIO.2.NIO.2是继承自NIO框架,并添加了新的功能(比如:处理软链接和硬链接的功能).这篇帖子包含三个部分,我将使用NIO.2的一些演示样例.由此向大家演示NIO.2的基本用 ...
- java 7中新增的CPU和负载的监控
java 7中新增的CPU和负载的监控 import java.lang.management.ManagementFactory; import java.lang.management.Opera ...
- 天猫魔盒1代TMB100E刷机, 以及右声道无声的问题
这个是在小米盒子1代之后买的, 当时速度比小米盒子快, 除了遥控器比较软, 电池盖不太对得齐以外, 用起来还不错. 但是时间长了之后总是不停自己升级, 自己安装一些应用, 还删不了, 要知道这个盒子的 ...
- Python3 笔记
Ubuntu18.04 Python3环境 默认python3已经安装了, 可能是安装其他应用的时候因为依赖关系安装的. 安装pip3, 先sudo apt update 一下, apt-cache ...