A different kind of training

July 9, 2017 Leave a comment

Every year, I make an effort to attend at least one software conference. In years past, I attended several conferences around my area such as the Kansas City Developers Conference and St Louis Day of .NET.

I decided to take a break this year and do something different.

This weekend, I drove down to Farmington Missouri to attend the “basics of tactical shooting” course taught by Asymmetric Solutions. What drew me to Asymmetric Solutions was their impressive set of instructors with real world experience. Most, if not all, of their instructors are combat experienced special operations veterans.

I usually go to an indoor range once a week, but all of my shooting thus far have been from a static position using paper targets. I knew I wasn’t well rounded, so I wanted sign up for this course.

I didn’t know what to expect at first because I imagined the course being filled with military-esque characters. But as I arrived at the facility and people started to gather, I was pleasantly surprised to see there were a wide range of people from new shooters to very experienced. I felt like I was somewhere in the middle.

Our group had 14 students (3 women and 12 men) and 1 instructor (Dave). The day started off with dry firing exercises such as drawing from the holster and re-holstering. We moved onto practicing magazine changes and the difference between combat and tactical reloads. As our group became comfortable with handling our weapons, we started incorporating movements into our practice. We learned how to move forward, backwards, turn left/right, and make 180 degree turns.

The afternoon was dedicated to live fire exercises. Our instructor ran us through a variety of exercises on the range that incorporated everything we learned in the morning. We also discussed how to clear any malfunctions that occur during the operation of our weapon. I started off fairly decent when we were firing from a static position. As soon as we started incorporating movements or target discrimination drills, my inexperience started to show. Fortunately, our instructor was quick to explain what I was doing wrong and how to address it. It was a good learning experience for me to hear what I needed to improve on and listen to what the instructor was saying to other students as well. This was also a great opportunity for me to practice firing from my holster since it’s not allowed at the indoor range.

I believe I was the only person in my group that had a weapon with a manual safety. I brought my M&P M2.0 to the class. The majority of the people in my group, including the instructor, had a Glock. I know a lot of people balk at the idea of a manual safety on a pistol, but since my Sig P938 has a manual safety, I wanted to practice with another pistol that has a manual safety as well. It quickly dawned on me how much extra work there is to remember to flick on/off the safety each time I draw and re-holster. I’m fine with that, but it’s something I’ll have to practice to let muscle memory take over.

Some of my important takeaways:

  • Don’t be a robot. Practice drawing smoother and don’t have sharp robotic moments.
  • I take too long to sight in my weapon after I draw. I need to start sighting in my weapon as I extend my arms.
  • Slow down during target discrimination and acquire the next target before taking action.
  • Practice smoother magazine changes.

Our instructor Dave did an excellent job explaining each concept and technique to us. Most importantly, he explained why they were important in the real world. With so much emphasis placed on safety, there wasn’t a single time during the whole day where I felt unsafe. Trigger discipline, muzzle control, and gun checks were paramount. I believe everyone in our group had a good time.

The only negative thing about the course was the amount of time we spend waiting for our turn during the live fire exercises. Since the class had 14 students and each exercise only had 2-4 active participants at a time, we spend a lot of time watching and waiting for our turn. It was really hot outside this weekend, so standing around in the sun for 8 hours was brutal. I think this is the closest I’ve ever been to getting a sunburn. It would have been better if the class size was smaller or if they split us into two groups during the live fire exercises to allow students more opportunities to practice. However, the course was still worth it.

I am definitely going back to attend their advanced courses in the coming months. Hats off to Asymmetric Solutions and my instructor Dave for providing an excellent training environment.

Understanding multiple anti-forgery tokens in ASP.NET MVC

June 10, 2017 Leave a comment

The MVC helper “Html.AntiForgeryToken()” can be used to protect your application against cross-site request forgery (CSRF). This will generate both a hidden field and a cookie that contains matching values that are validated on the server.

Our website utilizes multiple forms on the same view and each form contains an anti-forgery token. However, each call to “Html.AntiForgeryToken()” generates a different value. For example, multiple calls such as:


… will generate multiple hidden fields that look like this:

<input name="__RequestVerificationToken" type="hidden" value="iAdQj5D0qrMuTggD8WpnOZPlVOfHg_qmPIEjnULAYd1h56cV2cL51rcaY8_UgxQbav5_6KTAtyE52ir1X6GmaS9ZPgw1" />
<input name="__RequestVerificationToken" type="hidden" value="Shvi8Bxe6-a8zfCfDGnxkaC-IETsbjkR9iIylwn-2VRWQ-GtQkdowdFw1biU7dN3j-xPJZHYQPe-hNfWspYjy_ZcCCY1" />
<input name="__RequestVerificationToken" type="hidden" value="ZhaVFngUMLo88jmTIx___BTWlYFyKh1GalwEeffRl0-o3Gu7_m98k6aQjO7IysZIdXxVx6TqL6QIfX19Uwq3Ia6dghA1" />

I wanted to learn how it works under the cover, so I used ReSharper and dotPeek to decompile the code to understand it better.

At the heart of the helper “Html.AntiForgeryToken()” is the method “GetFormInputElement” used to generate the hidden field.

public TagBuilder GetFormInputElement(HttpContextBase httpContext)

	AntiForgeryToken cookieTokenNoThrow = this.GetCookieTokenNoThrow(httpContext);
	AntiForgeryToken newCookieToken;
	AntiForgeryToken formToken;
	this.GetTokens(httpContext, cookieTokenNoThrow, out newCookieToken, out formToken);

	if (newCookieToken != null)
		this._tokenStore.SaveCookieToken(httpContext, newCookieToken);

	if (!this._config.SuppressXFrameOptionsHeader)
		httpContext.Response.AddHeader("X-Frame-Options", "SAMEORIGIN");

	TagBuilder tagBuilder = new TagBuilder("input");
	tagBuilder.Attributes["type"] = "hidden";
	tagBuilder.Attributes["name"] = this._config.FormFieldName;
	tagBuilder.Attributes["value"] = this._serializer.Serialize(formToken);
	return tagBuilder;

To understand why different values are generated in the hidden fields, we need to first take a look at the internal class “AntiForgeryToken” that represents the verification token.

internal sealed class AntiForgeryToken
	private BinaryBlob _securityToken;

	public BinaryBlob SecurityToken
			if (this._securityToken == null)
				this._securityToken = new BinaryBlob(128);

			return this._securityToken;
			this._securityToken = value;

	// Removed other properties, fields, and methods.
	// ...
	// ...

The token is represented by a “BinaryBlob”. Digging down into this class shows it uses “RNGCryptoServiceProvider” to randomly generate a 16 byte array.

private static byte[] GenerateNewToken(int bitLength)
	byte[] data = new byte[bitLength / 8];
	return data;

Looking back at the “GetFormInputElement” method, we can see the code checks for the existence of a token from the cookies collection using the method “GetCookieTokenNoThrow”. Drilling into the code shows it’s not complicated. If it exists, it deserializes into an “AntiForgeryToken”, otherwise it returns null.

public AntiForgeryToken GetCookieToken(HttpContextBase httpContext)
	HttpCookie cookie = httpContext.Request.Cookies[this._config.CookieName];

	if (cookie == null || string.IsNullOrEmpty(cookie.Value))
		return (AntiForgeryToken) null;

	return this._serializer.Deserialize(cookie.Value);

So what does it do with this deserialized token? We can see it’s passed to the method “GetTokens”. Drilling into this method eventually leads to the method “GenerateFormToken”.

private void GetTokens(HttpContextBase httpContext, AntiForgeryToken oldCookieToken, out AntiForgeryToken newCookieToken, out AntiForgeryToken formToken)
	newCookieToken = (AntiForgeryToken) null;

	if (!this._validator.IsCookieTokenValid(oldCookieToken))
		oldCookieToken = newCookieToken = this._validator.GenerateCookieToken();

	formToken = this._validator.GenerateFormToken(httpContext, AntiForgeryWorker.ExtractIdentity(httpContext), oldCookieToken);

// From the validator's class
public AntiForgeryToken GenerateFormToken(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken cookieToken)
	AntiForgeryToken antiForgeryToken = new AntiForgeryToken()
		SecurityToken = cookieToken.SecurityToken,
		IsSessionToken = false

	// Removed some code related to identities and additional data.
	// ...
	// ...

	return antiForgeryToken;

So from what we can see, if a token can be deserialized from the request’s cookie collection, it’ll reuse that token instead of generating a new one. If a token doesn’t exist in the cookie collection, it’ll instantiate a new instance of “AntiForgeryToken” and randomly generate a new 16 byte array to represent the token.

Going back to the method “GetFormInputElement”, we can see it calls the method “SaveCookieToken” after generating or reusing the existing token.

public void SaveCookieToken(HttpContextBase httpContext, AntiForgeryToken token)
	HttpCookie cookie = new HttpCookie(this._config.CookieName, this._serializer.Serialize(token))
		HttpOnly = true

	if (this._config.RequireSSL)
		cookie.Secure = true;


After generating the first token and saving it to the cookie collection, all subsequent calls to the helper method “Html.AntiForgeryToken()” will follow the same steps and reuse the existing token from the cookie collection instead of generating a new value. Since it is a session cookie, this means the anti-forgery token’s value is generated only once during a browser session and is reused for all subsequent calls.

So why are the hidden field values different from one another if they are reusing the same token? To answer that, we have to look at the token serializer.

public string Serialize(AntiForgeryToken token)
	using (MemoryStream memoryStream = new MemoryStream())
		using (BinaryWriter binaryWriter = new BinaryWriter((Stream) memoryStream))
			binaryWriter.Write((byte) 1);

			// Removed some code related to identities and additional data.
			// ...
			// ...

			return this._cryptoSystem.Protect(memoryStream.ToArray());

The “Protect” method uses the internal class “AspNetCryptoServiceProvider” to encrypt the token using our specified machineKey in the config. So while the encrypted values may look different, the decrypted values are the same. To test this, we can use the decompiled code from dotPeek to “Unprotect” the encrypted values.

byte[] one = MachineKey45CryptoSystem.Instance.Unprotect("iAdQj5D0qrMuTggD8WpnOZPlVOfHg_qmPIEjnULAYd1h56cV2cL51rcaY8_UgxQbav5_6KTAtyE52ir1X6GmaS9ZPgw1");
byte[] two  = MachineKey45CryptoSystem.Instance.Unprotect("Shvi8Bxe6-a8zfCfDGnxkaC-IETsbjkR9iIylwn-2VRWQ-GtQkdowdFw1biU7dN3j-xPJZHYQPe-hNfWspYjy_ZcCCY1");
byte[] three = MachineKey45CryptoSystem.Instance.Unprotect("ZhaVFngUMLo88jmTIx___BTWlYFyKh1GalwEeffRl0-o3Gu7_m98k6aQjO7IysZIdXxVx6TqL6QIfX19Uwq3Ia6dghA1");

Comparing all three byte arrays reveals they are identical.

In summary, the verification tokens generated from “Html.AntiForgeryToken()” are all identical within a browser session, regardless how many times we call it. The values appear different because they’re encrypted using our machineKey.

Check whether a .NET dll is built for Any CPU, x86, or x64

November 16, 2016 Leave a comment

As much as I would like all builds to come from a build server, many times a build comes from a developer’s machine. When I receive a build from another developer’s machine, I need to check if their build is targeting the correct platform.

I can use CorFlags.exe, which is part of the .NET Framework SDK, to find out this information from a dll. Running CorFlags.exe with the file path to the dll will produce the following output:

>> CorFlags "C:\example.dll"

Microsoft (R) .NET Framework CorFlags Conversion Tool.  Version
Copyright (c) Microsoft Corporation.  All rights reserved.

Version   : v4.0.30319
CLR Header: 2.5
PE        : PE32
CorFlags  : 0x3
ILONLY    : 1
32BITREQ  : 1
Signed    : 0

The two fields we need to look at are “PE” and “32BITREQ”.

Any CPU PE: PE32, 32BITREQ: 0
x86 PE: PE32, 32BITREQ: 1
x64 PE: PE32+, 32BITREQ: 0

To programmatically determine the target platform, we can use Module.GetPEKind().

Assembly a = Assembly.ReflectionOnlyLoadFrom(@"C:\example.dll");

PortableExecutableKinds peKind;
ImageFileMachine machine;

a.ManifestModule.GetPEKind(out peKind, out machine);


The results of peKind can be interpreted with:

Any CPU ILOnly
x86 ILOnly, Required32Bit
x64 ILOnly, PE32Plus

MITM using Chromium Embedded Framework and Fiddler

October 4, 2016 Leave a comment

For some background, I use a popular website that shows certain artifacts around my city. When a location is clicked, it’ll show what artifacts are available at that location. The website works by sending an AJAX request to an API when a location is clicked and returns a JSON serialized list of artifacts.

A few weeks ago, I wrote a script to call their API directly. The script contained an infinite loop to call their API every minute and notify me when it found new artifacts. I could run this script when I was sleeping or away from my computer and it would text me the details using Twilio when it found something.

However, the website started cracking down on unsolicited API calls to their service a few days ago. Their first attempt was to generate a unique token each time a user visits their website and that token was included as part of the API call. This was simple to bypass since my script could simply scrap the website for the token.

They wised up pretty quickly. A few days later, they started obfuscating how the token was generated and each API call required a new token. I spent an hour trying to deobfuscate how they generated the token, but I couldn’t figure it out without spending a large amount of time on it.

Fortunately, there’s still a way around it. Chromium Embedded Framework (CEF) allows me to embed a headless browser into my script that is able to execute JavaScript and everything else a normal user would be able to do.

I can load the website using CEF and inject JavaScript into the website to click on links.

var browser = new ChromiumWebBrowser("https://example.com");

while (!browser.IsBrowserInitialized)
	Console.WriteLine("Waiting for browser initialization...");

while (browser.IsLoading)
	Console.WriteLine("Waiting for website to load...");

Console.WriteLine("Finished browser initialization.");
await browser.EvaluateScriptAsync("$('#location').trigger('click'););

Triggering a click event will cause the website to generate a new token and submit an AJAX request to their API. Unfortunately, I couldn’t find any CEF documentation that showed me how to intercept the AJAX response.

Instead of trying to intercept the AJAX response using CEF, I used FiddlerCore to capture the AJAX response. FiddleCore can see all the traffic between CEF and their API.

FiddlerApplication.Startup(443, FiddlerCoreStartupFlags.Default);

FiddlerApplication.BeforeResponse += session =>
	if (session.RequestMethod == "CONNECT" || !session.LocalProcess.StartsWith("myApplication"))
	if (!session.HostnameIs("api.example.com"))
	dynamic result = JObject.Parse(session.GetResponseBodyAsString());
	// Do something with result

Instead of calling their API directly, I had to jump through a few hoops to get the data I wanted. Injecting click events into the website through CEF allowed me to automate the API calls without having to decipher the token generation. FiddleCore allowed me to monitor the traffic between CEF and their API.

Back from NSBCon 2015

December 10, 2015 Leave a comment

I just returned from Dallas having attended NSBCon 2015.  Overall, a very positive experience with several informative sessions.  It was a good opportunity for me to relax and rejuvenated since I haven’t been feeling very motivated lately.

One of the announcements was ServiceMatrix is being discontinued. I’ve never been a fan of using drag-drop tools for anything outside of user interface development, so the discontinuation will probably save me some stress in the future.

The next release of NServiceBus will utilize asynchronous message handlers, which is unfortunately a breaking change. The session continued with explanations on how to migrate existing codebases and pitfalls to watch out for.

The session on Akka.NET and the actor model peaked my interest. I’ve heard of Akka.NET, but I haven’t investigated any further. Having one of the developers talk about Akka.NET was a good chance to hear what it brings to table. Definitely something I’ll need to look into more.

I especially enjoyed listening to the panel discussions and hearing everyone’s opinion on topics that the audience brought up. It’s always a pleasure to listen to several well known developers in the industry talking about past, present, and future architectures/patterns being used in the wild. The topic around technological fads resonated with me. In my opinion, there are simply too many people that immediately become overzealous about new and shiny patterns or technologies without looking at past mistakes. History repeats itself and too many people ignore that.

There was another great session about things not to do with NServiceBus. While the examples were targeted to NServiceBus, the principle applies to a lot of other things. Too many times, certain software is shoved down everyone’s throat as the end-all solution for everything.

Everything considered, I enjoyed the four days I spent in Dallas. Most of the sessions were very informative and insightful, so I have plenty to think about.

Logging database and web service calls with PostSharp

November 4, 2015 Leave a comment

We’ve been having some sporadic performance problems with our website. We needed to find out which page or operation was taking too long to complete and exhausting all the worker threads. Unfortunately, due to the size of the codebase and the lack of performance auditing, it was difficult to pinpoint where the problem was occurring.

Only a small portion of the codebase was utilizing dependency injection, so we couldn’t decorate or intercept all dependencies with an auditing class. Fortunately, an IL weaving framework such as PostSharp can help with this situation. This was my first time using PostSharp, but I found it tremendously helpful.

A good would start would be logging database and web service calls.

using (SqlConnection conn = new SqlConnection("Server=.\\SQL2008; Database=Test; Trusted_Connection=True"))
using (SqlCommand cmd = new SqlCommand("cp_GetUserInfo", conn))
	cmd.CommandType = CommandType.StoredProcedure;
	cmd.Parameters.AddWithValue("@UserName", "JD");

	using (SqlDataReader reader = cmd.ExecuteReader())
		while (reader.Read())
			Console.WriteLine("User {0} {1}'s member ID is {2}.", reader["FirstName"], reader["LastName"], reader["MemberID"]);

Without modifying the existing code, I want to log the connection string, any parameters, and the amount of time it took to execute this stored procedure. We’ll inherit from OnMethodBoundaryAspect to record information before and after our database call.

public class DatabaseAspect : OnMethodBoundaryAspect
	public override void OnEntry(MethodExecutionArgs args)
		args.MethodExecutionTag = Stopwatch.StartNew();
		SqlCommand cmd = (SqlCommand) args.Instance;

		Console.WriteLine("Executing command: {0}", cmd.CommandText);
		Console.WriteLine("\t- Connection String: {0}", cmd.Connection.ConnectionString);
		List<string> parameters = new List<string>();

		for (int i = 0; i < cmd.Parameters.Count; i++)
			parameters.Add("\t- Parameter " + cmd.Parameters[i].ParameterName + ": " + cmd.Parameters[i].Value);

		if (parameters.Count > 0)
			Console.WriteLine(String.Join("\n", parameters));

	public override void OnExit(MethodExecutionArgs args)
		Stopwatch sw = (Stopwatch) args.MethodExecutionTag;

		SqlCommand cmd = (SqlCommand) args.Instance;

		Console.WriteLine("Command \"{0}\" took {1} ms.", cmd.CommandText, sw.ElapsedMilliseconds);

Running the code will produce the following:

Executing command: cp_GetUserInfo
        - Connection String: Server=.\SQL2008; Database=Test; Trusted_Connection=True
        - Parameter @UserName: JD
Command "cp_GetUserInfo" took 1124 ms.
User John Doe's member ID is 1234.

Great, now I can see the length of each database call and the parameters without digging through IIS logs hoping to find something to reconstruct the request. In additional to database calls, I want to log any web service requests. As with the database aspect, we can inherit from OnMethodBoundaryAspect to log information before and after the request.

public class WebServiceAspect : OnMethodBoundaryAspect
	public override void OnEntry(MethodExecutionArgs args)
		args.MethodExecutionTag = Stopwatch.StartNew();
		dynamic client = args.Instance;
		Console.WriteLine("Found service call to: {0}", client.Client.Endpoint.Address);

	public override void OnExit(MethodExecutionArgs args)
		Stopwatch sw = (Stopwatch) args.MethodExecutionTag;

		dynamic client = args.Instance;
		Console.WriteLine("Service call to \"{0}\" took {1} ms.", client.Client.Endpoint.Address, sw.ElapsedMilliseconds);

We’ll apply these aspects to the entire assembly using assembly attributes.

[assembly: WebServiceAspect(AttributeTargetMembers = "regex:Return|Use", AttributeTargetAssemblies = "Example", AttributeTargetTypes = "Example.WcfClient*")]
[assembly: DatabaseAspect(AttributeTargetMembers = "Execute*", AttributeTargetAssemblies = "System.Data", AttributeTargetTypes = "System.Data.SqlClient.SqlCommand")]

Muting sounds in a Chrome tab

May 1, 2015 Leave a comment

Although I still prefer the Firefox’s developer tools for debugging, I have switched to Chrome almost exclusively for my day-to-day browsing.

A while ago, Chrome added an audio icon to indicate which tabs were playing sounds.

Audio icon in Chrome

While I love this feature, I always wanted a way to manually mute a single tab. Well, there is a way and I can’t believe I never knew about it until now. Just copy and paste the following into Chrome’s address bar and enable the audio mute option:


Now I can click on the audio icon and mute a single tab without having to mute my entire computer.

Audio muted in Chrome