10 ms·
Life in a post-database world: Using crypto to avoid database writes
- dmos62 12y agoLoved reading this. Most original article I've recently read.
- danielschonfeld 12y ago+1! This was a really refreshing read on HN. Wish there were more articles like this one utilizing crypto for modern programming applications.
- lumpypua 12y agoAn iPad app I like and wanted to build on top of uses signed requests. Except the signing occurs on the iPad and is verified by the server. Oops. I disassembled the app and took the secret key to generate my own requests.
- Kenji 12y ago>HMAC256("userId=johnnysmith&expirationTime=1356156000&oldBcryptHash=$oldBcryptHash&clientIpAddress=$clientIpAddress", $mySuperSecretKey) Maybe I'm wrong but he can still use this password reset if he remembered his login and logged in. ID stays, it might not be expired, BcryptHash stays, Ip stays. That, of course, is suboptimal.
- maxerickson 12y agoIt will be checked against the current hash. The reset creates a new hash, so the token won't work a second time.
- pests 12y agoHes saying the user logs in with their normal password and takes no other action on the reset. The reset is still valid until the expiration.
- sk5t 12y agoI don't understand what problem you are describing. A user who remembers his momentarily-forgotten password can of course change or reset it regardless. The article quite sensibly describes using the old password hash as a nonce without pestering the database with extraneous records.
- Kenji 12y agoIt would be nice to stop all reset tokens if the user has logged in after the reset tokens were made. But you're right, it's not really a problem unless one chooses make it one ;)
- sk5t 12y agoOne could overcome this by tracking the user's last password-driven login date and rolling it into the MAC; alternately, just use a short expiration time on the reset token and don't sweat it.
- morgante 12y agoBut that's just introducing additional state (last login date), so if you're starting to do that there's not much point in the HMAC approach.
- yeukhon 12y agoI think it all comes down to what benefit your user's security. If you want to expose to user his or her account's activity, like history of recent password reset, recent login activity, things that a typical FB user would see in the user's activity page, that can be a really nice security feature. So maybe after all the HMAC approach works just fine with extra state added. But I think the point the author is bringing is that the application can simply just do HMAC(.....) easily and verify in a few lines of just if and else branch, whereas the traditional password reset code would probably take more lines and more conditions. I had written code that did exactly what the author didn't like and trust me that code wasn't pretty and I had spent many hours to optimize the code. Edge cases and test cases shitted my codebase.
- njohnson41 12y agoUsing HMAC'd tokens to authenticate requests is pretty common in the form of cookie-based session variables (at least in most non-PHP web frameworks, e.g. Flask). This is really the same technique, except for email requests, where the data is embedded in a URL instead of a cookie. Not to say it's not useful, just that it's not really novel. You also still have to be careful of replay attacks, which the author briefly addresses.
- tedunangst 12y agoIt's both common and a common source of mistakes. Every web framework I know of that uses HMAC'd sessions has had at least one glaring vulnerability that could have been avoided by using the old school opaque token database lookup technique.
- tomjen3 12y agoIf you are google scale I would say do whatever you need to do to make your scale work since your very expensive scale experts can know if there is something that is going to bite you, but in most cases that is overkill. Store it in your database, then in some key value database (e.g redis) if you must.
- sytse 12y agoI loved the article and all the use cases are valid. However I don't think the first two use cases save that much effort. 1. In Rails apps with the devise gem the password reset token is just a column, not a whole other table. 2. Email activation, having the additional non-activated records is not a big problem, 20% extra records in my users table is pretty acceptable.
- bryanlarsen 12y agoSince Rails 4.1, the technique described in the article is trivial to use. Check out message_verifier.
- sytse 12y agoI looked it up, http://api.rubyonrails.org/classes/ActiveSupport/MessageVerifier.html http://api.rubyonrails.org/classes/ActiveSupport/MessageVeri... looks cool, but didn't find a quick way to use it with Devise.
- bryanlarsen 12y agoIt's not the extra database columns, it's the removal of a state field. The additional of a single boolean state field essentially doubles your API area because now you have two types of users that may try to do things, and it's highly unlikely you have saturation testing for unverified users.
- sytse 12y agoThat makes sense, normally Devise handles that for me https://github.com/plataformatec/devise https://github.com/plataformatec/devise
- tomjen3 12y agoActually rails has (or had I haven't looked at it seriously since the load and execute all the yaml fiasco) a relatively simple before filter (it may have been called before_filter, actually) that you use to filter out users who are not signed in, it wouldn't be difficult at all to change that to check the user was signed in and verified and to update the single place where the user is allowed in (likely /verify) as an unverified user to not use that filter. Django has native support for unverified users. That said it is still a good point.
- jakozaur 12y agoOne of the other use case is session ids. Pretty much you can sign: user id|timeout|user custom property Having custom property (per user number), gives an opportunity to kill sessions. E.g. session is compromised, just increment it and regenerate session for valid user.
- jsnell 12y agoLast time I used this approach I ended up regretting it. The problem is that the links become ugly, unwieldy for the users to handle, and occasionally cause problems that are rather hard to debug. For example the base64 encoding I was using for the authentication token included '.' as a one of the characters. Well, turns out that the linkification code in gmail will ignore a '.' at the end of the link (which is kind of sensible). So 1/64 of my validation links ended up being invalid. The supposed benefit of the scheme is that you don't need to evolve your DB schema as you add or remove validation fields. That's rubbish. If you're happy with storing data with no schema in the links, you should be equally happy storing it without a schema in the DB. (For example a token field, an expiration time field, and a json blob containing the actual payload corresponding to the token).
- sk5t 12y ago'.' is not a standard base64 character; did you roll your own? Base36 and base32 are popular where portability and paranoia of being MIME/URL-mangled are concerns, e.g., Google Authenticator's OATH TOTP implementation for the secret key.
- jimktrains2 12y agoif you check http://en.wikipedia.org/wiki/Base64 http://en.wikipedia.org/wiki/Base64 there are actually RFC-standard alphabets that use . and - because they're URL-safe.
- bazzargh 12y agoI was surprised when I read that, since I've implemented those RFCs before and didn't remember this coming up - so I checked. Unfortunately, that's just a problem with the wikipedia article. The only one listed there as an RFC using '.' is RFC 4686, (in the padding column right now it says "= (optional, not recommended. Recommended use .)"). That's wrong though. In RFC 4648 it actually says: The remaining unreserved URI character is ".", but some file system environments do not permit multiple "." in a filename, thus making the "." character unattractive as well. And... The pad character "=" is typically percent-encoded when used in an URI, but if the data length is known implicitly, this can be avoided by skipping the padding The data length is known for a cryptographic hash, so you would omit the '='. I'll fix wikipedia.
- francescolaffi 12y agoyou should have a look at JSON Web Token http://jwt.io/ http://jwt.io/
- vidarh 12y agoInteresting, but massive overkill when you're transferring assertions between two parties where only one party (the server) is allowed to create the assertions. In the examples in the article, the JWT header is just plain cruft because you're unlikely to be switching encoding often (and if you decide to, including a single much shorter token as a "stand-in" for the bloated JSON data would be much better; using JSON). The payload also represents a lot of extra overhead unless you intend to transfer more than just a single level dictionary. It's kind of comical that they present it as "compact" given that probably something like 30% of the length of the presented example is unnecessary.
- ris 12y agoThis is the way I've always done password resets and activation emails, and it never seemed particularly non-obvious. In fact I seem to remember django's default out-of-the-box password reset mechanism does it more or less this way.
- ars 12y agoI've also always done it this way. I didn't realize that was anything unusual. It just seemed so obvious.
- plorkyeran 12y agoI tend to mistrust using crypto for things that can reasonably be done without crypto. Even if the initial implementation is perfect, it's too easy for a future maintainer to make a simple mistake that introduces major security flaws. The place to use this sort of technique is where it enables a fundamentally different architecture for your application, and not just where it's a small performance optimization.
- adevine 12y agoWhile this is true, to my mind it's almost "6 of one/half dozen of the other". Using the examples given, there have been many security flaws where a generated token like a password reset token (one stored in the DB) is not truly random, or not as random as the implementer envisioned. Also, keeping systems secure when they need to support use cases that inherently try to subvert some measure of security (like "forgot password") is difficult, and I find the difficulty is much more likely to be in the overall workflow than flaws in the "generateToken" and "validateToken" methods themselves.
- andrewchambers 12y agoPure code with stateless systems are usually easier to test and less error prone.
- tomjen3 12y agoIn this case (although it wasn't shown very well in the article) it does enable a very different architecture: you can generate the code in one data center and have it work on a computer in any other datacenter. Unless you are google scale you don't need that, so I am on your side (other than HMACS not actually being that difficult to fuck up, compared to e.g just encrypting the entire thing in AES at which point you are hosed).
- michael_storm 12y agoIn other words: a maintenance nightmare, filled with security gotchas, difficult to scale, and hard to write. So is the alternative the author describes (except for scaling). HMACs for temporary credentials are clever and simple, if you're already versed in crypto primitives. But to anyone else, they're magic security sauce: "But why can't I just use MD5? Wait, no, that's broken somehow - what about SHA? What do I include in the HMAC? Do I have to use a new key every time?" The solution trades implementation complexity for arcane knowledge. The author is so confident that his solution is superior because he already has that arcane knowledge. That said, a well-implemented HMAC-based password reset flow is probably more bulletproof than a well-implemented DB-based flow. So if you're implementing AWS, go for HMAC. If you're implementing a blog, go with whatever you feel like. Just implement it well.
- morgante 12y agoI don't really consider HMACs to be particularly arcane knowledge. They're easy to generate in any language and straightforward to work with. While I consider myself to be a pretty good developer, I'm definitely not well-versed in crypto and math isn't my strongest skill. Despite that, I've had no problem using crypto for several of the obvious use cases (ex. password resets).
- Terr_ 12y agoArcane to use as the consumer of a library, or arcane to implement on your own? The most important rule of thumb for crypto is that you'll probably mess up doing it yourself.
- williamcotton 12y agoThat rule if for like, implementing AES on your own, not just using HMAC! No one is saying roll your own HMAC!
- lvh 12y agoThat's a common misconception. While designing your own cipher or implementing AES is a terrible idea, it's fairly easy to produce broken systems with strong primitives like AES or HMAC, and the brokenness would not have anything to do with the implementation of those primitives.
- oautholaf 12y agoThere's really a strong reason to do this for things like user session tokens, where using crypto and avoiding database updates could easily remove a substantial portion of your database traffic. But for things that are less common, like password resets and email validation, consider the downsides: a) using the database gives you a built in (depending on schema) audit log of these events, where a signed token does not b) If the key is stolen in the scheme described, the person in possession of the key can hack into all your accounts. If you use database state, someone needs to have access to the database. c) (also mentioned above) You will almost certainly be able to have a smaller token if it refers to database state, which has it's own advantages: copy and paste errors, etc There's certainly advantages to crypto tokens/cookies, and they're the right call in some circumstances, but there's downsides to consider as well.
- adventured 12y agoSpot on. The article disregards that you really need a log of activity to check against with reset requests. Should I allow an abusive user to send 37 reset codes in 15 minutes to an email address they don't own (or even if they do own it)? Absolutely not. How else do you keep track of that activity without storing it in a database of some sort to check against?
- riquito 12y agoFor short lived things like these you can store the info you need in a memory based storage.
- thegeomaster 12y agoIt's a nice article and generally a sound approach, but reading it has led me to think about something else: imagine an Internet where the data about each user (what would normally be entries in different tables on the servers) is stored, encrypted and authenticated, on the user's computer, as opposed to being stored on the server. Yes, I know, this goes against the 'cloud' principle we see around us and introduces a bunch of issues with syncing this data and it being available everywhere, which is the point of SaaS-like websites. But on the other hand, small websites could use this approach to drastically cut their costs and maintenance work they need to do. Also, a compromise of a server would expose the keys used for encryption, but then the attackers would need another piece of the puzzle, and that's stored on the user's computer. Don't get me wrong, I'm not advocating this principle or implying it is needed and doable with the current technologies (I don't think we have a way of reliably storing such long-term data within the user's browser), but it's an interesting train of thought. It doesn't obviate the need for the server to store any sensitive information, just some of it. User info, password hashes, credit card numbers, maybe even social graphs depending on the use case, could all be stored this way. There will always be websites for which this doesn't make a lot of sense, but a lot of the other ones, mainly small players, could benefit from this. It's curious how, when you describe it like that, it sounds that your data is being held hostage by a third party. After all, the server doesn't allow you to see what's in the encrypted opaque blobs, it only allows a controlled set of operations to be done with this data, and the only thing they do is further mutate this opaque blob. But it is no less transparent than the current state of affairs, namely servers keeping the data for themselves. I'm interested to hear HN's opinion on this, flaws in the approach I've missed, etc.
- theseoafs 12y ago> imagine an Internet where the data about each user (what would normally be entries in different tables on the servers) is stored, encrypted and authenticated, on the user's computer, as opposed to being stored on the server. Trying to authenticate solely on the client side isn't as fruitful as you might be imagining, since it introduces potential security isues. Without any server-side authentication using only information (i.e. a blob) that the server has access to, it becomes very easy for clients to spoof/pretend to be other clients. Consider that if this kind of system were easy/fruitful to implement, a lot of businesses would have done it already to avoid increased development/server costs on their end.
- randerson 12y agoThis is all fine and well until you need to measure "how many users reset their passwords" or "what is the bounce rate of users confirming their email addresses". This may be useful for avoiding sensitive data, but it's not a practical substitute for writing to the database, nor is it really that much effort to create two database tables.
- morgante 12y agoThat sort of data belongs in an analytics or event database (ie. one with entirely different requirements from your normal database). Usually when I implement a stateless approach like this I still fire off a log event every time we generate a password reset.
- hurin 12y agoIn other words: a maintenance nightmare, filled with security gotchas, difficult to scale, and hard to write. I'm not sure I follow this. To change a password you need to write to the db anyways, it's one extra check to set token used=1 or remove it. Why is that a huge deal? Now you don’t have to worry about clearing old bitrot from the database or worrying about when to expire non-verified accounts. It's also possible to use Redis or another fast store with timeouts. The problem seems rather exaggerated.
- engendered 12y agoWhile encryption is obviously a tool every developer should be using, this seems a little hand-wavy and built against a rather contrived strawman. It is a little info-mercially -- you fuss, you muss... Is a table and a couple of columns actually difficult? Is this, or has this ever been, a problem for anyone? When did we enter the "post-database" world? This all makes plenty of sense if you buy the strawman, otherwise it seems like some pretty strong over-reaching.
- ratsbane 12y agoThese things can be useful fraud-detection signals. If you don't log password reset requests then you're missing a chance to catch suspicious behavior. Even if you're capturing that data but using it now, at least having it gives you that potential. Also, unless you plan on making the valid window very short, you probably want to mark reset requests as used so someone's old email doesn't get used again. It's not a completely crazy idea, but the minimal amount of trouble required for the extra tables doesn't seem like enough to give up the logging and expiration benefits.
- bad_user 12y agoLogging things in a relational database for the purpose of catching suspicious behavior is a bad idea. You also don't need to mark reset requests as used, if the generated token was composed of the user's old hashed password or email, as that token will be invalid as soon as the user does the reset.
- adventured 12y agoIt's worth noting the parent didn't say anything about relational databases. Even if they did, I don't see how that would be a problem. How else can you keep track of whether there is a wave of reset abuse targeting an user / email, if not through saving it to some sort of data store? eg - after 5 reset attempts in 15 or 30 minutes, prevent any further reset attempts for the next X amount of time; either outright, or based on a signature of the request
- bad_user 12y ago"Some sort of data store" does not imply the normal solution that people deploy to solve this problem. There is a big difference between defining a table in your database that keeps track of resets, or using a queue of messages (event sourcing even?) with filters applied for detecting abnormal behavior. The former is a dirty solution, dirty because you're storing junk that shouldn't be stored in a relational database and it doesn't take care of other much more important kinds of attacks on your system. Whereas the later is extensible. So lets say that in addition to limiting the number of resets one does, you also want to limit the number of failed login attempts to 10 per hour. You may also want to limit users jumping between IP addresses, you don't want to be too strict about it, because mobile connections, but you do want to prevent multiple sessions active that use the same user credentials. You may also want your system to evolve based on taking averages out of user's past activity. Now where does that data go? Of course it's in "some kind of data store", but that says nothing, because the log files stored on disk are also a data store.
- aaronlevin 12y agoArmin Ronacher wrote about this back in 2013. [My Favorite Database is the Network](http://lucumr.pocoo.org/2013/11/17/my-favorite-database/ http://lucumr.pocoo.org/2013/11/17/my-favorite-database/)
- steven2012 12y agoIf I understand the article properly, what the author is suggesting is that instead of writing lines into the database that contain information about users, they create a hash that has some secret + user-supplied information, and if it matches, then that's considered validation. The reason why I completely disagree with this is because this is embedded in code. All your developers will have access to this code, and you have people joining and leaving your company all the time. If this scheme is used to protect more important information and if it leaks, then it could cause chaos. The difference is that all developers generally have access to code, but only some well-trusted people have database access in prod. If I care about security, that is a more secure way to do things.
- ars 12y agoSounds like security by obscurity to me. If you are worried about the secret part of the MAC then keep that secret, or change it when someone leaves.
- baby 12y agoYou could make the secret of the MAC an environment variable. PS: I don't understand why you are getting downvoted, your comment is more relevant than most of the comments here who don't understand a MAC.
- wtbob 12y agoHow do you prevent your developers from accessing the production database? Use the same mechanism to prevent them from knowing the production HMAC secret. If the production DB credentials are hard-coded, developers would indeed have access to the prod DB; if the production HMAC secret were hard-coded, developers would indeed be able to forge tokens. So don't do that. That's why we use environment variables.
- legulere 12y agoWhy the scheme in case-study 2 can be bad: User 1 registers username "alice". User 2 registers username "alice". User 1 verifies account. User 2 tries to verify the account. If the programmer didn't forget to check twice if an account name exists there's some error. This might not happen often, but you still need to write a good error handling for that case.
- TJSomething 12y agoAdd a salt. It doesn't even have to be that large because of the unlikelihood. Alternately, adding IP address as a hashed parameter should distinguish them well.
- legulere 12y agoDo I understand you right, that you should add something to the user-generated usernames? This seems like something that would be rejected by users to me.
- doomrobo 12y agoCool approach, but I don't see how it could be used to make one-time links. You can invalidate a valid immutable datum; you can only wait until it is expired. To make a link expire immediately after being clicked, you need to store a something server-side.
- kibibu 12y agoYou include the expiry time in the URL and HMAC the URL as well.
- jholman 12y agoI don't think you understand. At a minimum, I don't understand you. The question is not how to make links that expire after a time, the question is how to make links that expire after a fixed number of uses (e.g. one use). Suppose your link expires in 30 minutes (or any other time). What stops me from using that link 30 times, once per minute?
- aptwebapps 12y agomschwaig replied with the answer above [0]: use the old password hash when creating the token. For an example in the wild, see how Django does it[1]. 0. https://news.ycombinator.com/item?id=9055749 https://news.ycombinator.com/item?id=9055749 1. https://github.com/django/django/blob/master/django/contrib/auth/tokens.py https://github.com/django/django/blob/master/django/contrib/...
- jholman 12y agoThank you for the reply, and once I read it enough times in a row, I got it through my thick head. It's still not clear to me, however, how to generalize this technique to create limited-use links that are not necessarily for resetting passwords.
- aptwebapps 12y ago
- EGreg 12y agoAbout the only thing useful here is having the session id be validated before being used. PHP is notorious for allowing the client to select any session id they want. I've read "the network is my favorite database" a while ago. Similar concept. But, the problem is that the urls are really long and wouldn't fit into an sms for example. If you are trying to get users to get started with your service the last thing you want to do is throw more friction at the process. It's a bit like Microsoft shuttling ViewState back and forth in the old ASP, instead of just storing sessions in the database. Signing things is good for validation, to prevent giving out resources to a client which wasn't given valid credentials. But that stuff should be stored in cookies, not links. Links should be simple and to the point. And if that means having the links contain a token the server can use to look up additional info, tinyurl-style, then so be it. That lookup is fast, and once you did it, you can cache it in a hash based cache like memcache. Better experience for the end user and better security for you. In short - I agree with the author's premise about guarantees etc. but when giving humans links, they should be simple. Store all the authentication crap in cookies. To bring my point home, I'll just remark that inviting someone by sms or email is a way to not only motivate them to sign up but also having them click a unique link already verifies their mobile number or email address in one shot. One click and they have an account.
- Justsignedup 12y agoProblems I see: - Anyone with access to the secret token can now generate their own urls without fail or evidence. With a DB you need to at least insert a row and thus leave evidence (especially if you are auditing db activity) - No way to individually invalidate anyone. Example: What if ONE account's db tokens were exposed. Should be able to invalidate those tokens, not ALL tokens. - Not necessarily easier than one "expiring token" mechanism that is re-used throughout the system. - I don't feel great about exposing all my private security checks in url parameters. Why give users clues on how I do security? I can provide that in a better, more meaningful way. - No way to easily invalidate all tokens of specific nature. Example: If you want to invalidate all password reset tokens, all 2-factor authorization tokens, all confirm email tokens after any password reset, all systems must know of each other rather than go to the token table and set "valid" on all those tokens to "false" for everything. The hash would need to account for what change triggers this hash invalidation rather than just someone picking what to reset from a dinner menu as a separate concern.
- hvidgaard 12y ago> Anyone with access to the secret token can now generate their own urls without fail or evidence. With a DB you need to at least insert a row and thus leave evidence (especially if you are auditing db activity) And they wouldn't be valid. It's much simpler to invalidate them provided that you don't need information from the DB, than reading from the DB. > No way to individually invalidate anyone. Example: What if ONE account's db tokens were exposed. Should be able to invalidate those tokens, not ALL tokens. Of course you design it in such a way, that you can change one of the inputs, which will by definition invalidate the tokens. > Not necessarily easier than one "expiring token" mechanism that is re-used throughout the system. The point is to seperate this boilerplate logic from your core business logic. > I don't feel great about exposing all my private security checks in url parameters. Why give users clues on how I do security? I can provide that in a better, more meaningful way. Any serious security systems assume that an attacker already know 100% of the workings of the system. You should not rely on obscurity, but on your secret - in this case the crypto key. > No way to easily invalidate all tokens of specific nature. Again, if this is a requirement, then make such a global parameter an input to the token generation. It's still much simpler than doing it "the old fashioned way".
- Justsignedup 12y agoProblems I see: - Anyone with access to the secret token can now generate their own urls without fail or evidence. With a DB you need to at least insert a row and thus leave evidence (especially if you are auditing db activity) - No way to individually invalidate anyone. Example: What if ONE account's db tokens were exposed. Should be able to invalidate those tokens, not ALL tokens. - Not necessarily easier than one "expiring token" mechanism that is re-used throughout the system. - I don't feel great about exposing all my private security checks in url parameters. Why give users clues on how I do security? I can provide that in a better, more meaningful way. - No way to easily invalidate all tokens of specific nature. Example: If you want to invalidate all password reset tokens, all 2-factor authorization tokens, all confirm email tokens after any password reset, all systems must know of each other rather than go to the token table and set "valid" on all those tokens to "false" for everything. The hash would need to account for what change triggers this hash invalidation rather than just someone picking what to reset from a dinner menu as a separate concern.
- meesterdude 12y agoGreat article! While I don't think I'll be implementing any of the solutions outlined in the article (because the database does not represent a pain point for me) I do think this is a fascinating technique and is something worth keeping in the toolbox as a solution.
- ryan-allen 12y agoI love this technique, I copied it from Amazon a while back and have been using it to avoid storing state in the database ever since, I love it. Also, Rails has done something similar with their sessions, ages ago, with the whole state being stored in the client with a secret on the server. It's such a cool idea, and now there's the JWT [1] thing that you can use, and I use all the time these days. [1] http://jwt.io/ http://jwt.io/
- Tinned_Tuna 12y agoYea... this has been around for years. JSP and ASP.NET have allowed for this kind of shennanigans in their "view state" (albeit, security is a configuration option away...) mechanism. It's not hard to extend it out to things flying back and forth to the user. As for usability, these sort of things should be wrapped up in a nice container class; HMAC taken care of, and (probably) a key-value API presented. No fuss, no muss. If there's no such library, creating one could definitely pose a security risk to any project without sufficient expertise, as this post appears to be endorsing. Find an existing, tested, reviewed implementation that provides the API you need, and stick with it.
- jjarmoc 12y agoLately I see this approach used more and more. I really don't understand what the big gain is. Sure, you save yourself a few database round trips, but is that really that big a deal? Compare that savings with the additional size of URL parameters (increasing network overhead) in addition to the processing overhead of encryption/signing/validation. Have we really made a performance gain? I don't have any hard numbers, but I'm willing to wager than at gains are fairly negligable. From a security standpoint, I'm not fond of this approach, and I don't think it's benefits outweight the added risks. Here's why: - Encryption (including simple signing) is really easy to get wrong in subtle ways. A simple mistake like using SHA256() instead of HMACSHA256() breaks the system badly. - A corralary to the first point is that using a strong key is vital. The article says nothing of the criteria a strong key should meet and a poor key could enable additional attacks. While I'm not aware of anything allowing for HMAC key recovery in better than brute force, this could be problematic. If your key is a random 10 character ASCII string, it falls to brute force in minutes at most. If it's 256 random, you're much better off. - This scheme introduces a significant number of anonymous user-supplied inputs to the application which didn't previously exist. Each of these is a potential place for things to go wrong, which can give rise to other vulnerabilities (XSS, SQLi, etc) depending on what you're doing with that input. You'll need to be sure that you validate the signature prior to doing anything with these unverified inputs, in addition to performing sanity checks on their contents prior to signing. Part of secure application design is to minimize attack surface and complexity - this does the opposite. - Once a signature is created, it can't be revoked. I mean, you could store the signature in the database and validate it's presence on receipt, or include in your signed values a nonce that's stored in the database, but that kind of defeats the goal of avoiding database storage. This is something the article tries to address by signing over things like an expiry time, the user's old password digest, etc. But that's insufficent as well (I'll get into why below). - While I'm not aware of anything allowing for HMAC key recovery in better than brute force, choosing a secure key is still important. The article says nothing of the criteria a strong key should meet and a poor key could enable additional attacks. - Even if you get everything right, key exposure is fatal. You've introduced a single point of failure in the system that didn't previously exist, and a fairly catostrophic one. If the app ever leaks that key, you're only option is to rotate it (assuming you detect the exposure), which invalidates any existing signed values. That's the broad points, let's look at the article's examples: http://myapp.com/resetPassword?userId=johnnysmith&expirationTime=1356156000&token=%SECURITYHASH% Okay, so we have an irrevokable reset token for johnnysmith valid until 12/22/2012. The article doesn't mention where the key comes from. Since the key is the only thing johnny doesn't know, he can attempt as many keys as he wants offline. If he gets a hit, he can now create a valid token for any account he wants. NOT GOOD If the key is sufficiently long and randomly generated, this becomes much more difficult to the point of infeasibility but if the key is weak, so too is the overall security. As the article notes the token can also be reused multiple times, even if johnny has already used it. They offer a means of fixing this: HMAC256("userId=johnnysmith&expirationTime=1356156000&oldBcryptHash=$oldBcryptHash&clientIpAddress=$clientIpAddress", $mySuperSecretKey) Okay, so with the bcrypt digest covered under the hash, a change of password will cause the signature to no longer match. But now on verification we have to pull the user's hash before calculating the HMAC, so we've added a database read back which reduces the perceived benefits. Furthermore, this token is still valid if Johnny requests a password reset, and while waiting for the email to arrive remembers that he changed it from 'Password123' to 'Password456' and logs in. There's then a window of time where that token remains valid (until expirationTime arrives) and can be abused. The article doesn't address this case at all. I suppose they'd say that on issuing a token, you should disable login to Johnny's account until he's reset, but how would you do this? Well, you'd set a flag in that database on Johnny's record, and we're kind of back where we started again with both a database read and write, but with added cryptographic overhead and attack surface too. The next example talks about account registration. It states that you can verify a user's email account by sending them a link to: http://myapp.com/createAccount?email=johnnysmith@gmail.com&token=%SECURITYHASH% This doesn't concern me as much as password recovery, since account creation is likely to be fairly anonymous anyhow and not nearly as security sensitive. Still, it's not technically true that the token validates your receipt of the email. Instead, it validates your receipt of the email, or your knowledge of the key and values used to generate the token. In practice, this is likely a small difference, but a truly random token stored in the database would require database access or visibility into the email to obtain, whereas this requires only knowledge of the key instead. Case Study 3 talks about one-time-use and expiring resources. There's not enough detail here about their scheme for me to really critique, but they point out AWS/S3 use of HMAC signing as an example. Except that AWS/S3 signing isn't about one-time use or expiration. Instead, it's about authenticity. AWS operates with an ACCESS_KEY and SECRET_KEY which are a pair of tokens related to each other. Requests with 'params' are signed as: Signature = HMAC(ACCESS_KEY + params, SECRET_KEY) Signature, ACCESS_KEY, and params are sent to the server. SECRET_KEY is the HMAC signing key. On the server side, AWS presumbaly does a DB lookup for your ACCESS_KEY, obtains the corresponding SECRET_KEY, and validates the signature matches. This authenticates that the requestor has knowledge of the SECRET_KEY, but it implies the existing of a database lookup. If you think of the ACCESS_KEY as a username, you'll see that this is really authenticating each request, as well as preventing tampering. You can issue keypairs that're good for only one use, or expire after a set time period, etc. but there's nothing implicit in the HMAC scheme that causes this. Interestingly, this scheme almost certainly requires storing the token in a server-side database the exact thing the author wants to prevent. This can be done reasonably well, but it's a minefield to navigate when we have a tried and true solution. What's so bad about database storage of tokens? The post kind of starts with the assertion that they should be avoided, but I see no clear explanation as to why.