The issue with JWT in particular is that it doesn't bring anything to the table, but comes with a whole lot of terrifying complexity. Worse, you as a developer won't see that complexity: JWT looks like a simple token with a magic cryptographically-protected bag-of-attributes interface. The problems are all behind the scenes.
For most applications, the technical problems JWT solves are not especially complicated. Parseable bearer tokens are something Rails has been able to generate for close to a decade using ActiveSupport::MessageEncryptor. AS::ME is substantially safer than JWT, but people are swapping it out of applications in favor of JWT.
Someone needs to write the blog post about how to provide bag-of-attributes secure bearer tokens in all the major programming environments. Someone else needs to get to work standardizing one of those formats as an alternative to JWT so that there's a simple answer to "if not JWT then what?" that rebuts the (I think sort of silly) presumption that whatever an app uses needs to be RFC standardized.
But there's a reason crypto people hate the JWT/JOSE/JWE standards. You should avoid them. They're in the news again because someone noticed that one of the public key constructions (ECDHE-ES) is terribly insecure. I think it's literally the case that no cryptographer bothered to point this out before because they all assumed people knew JWT was a tire fire.
Because every token has an iat datetime, you don't need a token blacklist to invalidate tokens. You just need some sort of tokens_invalid_if_issued_before_datetime setting that gets checked whenever you validate the signature of a token.
The alternative is to store a UUID for each user, and just rotate those whenever they log out, change or reset their password, or there is some sort of security event. These are then stored in the payload and used as a secret. The one advantage over just using dates is that with the former, there can be weird bugs if you have multiple servers with clocks that are out of sync.
But you shouldn't ever need to blacklist specific tokens, at least not unless you have some highly specialized use case.
Is that not effectively a server-side session?
With most web frameworks (e.g. Django), the user model is retrieved on every request anyway. So it would be perhaps more accurate to say that it's a server-side session that's effectively not a server-side session, since no additional lookups are needed, only the user model lookup that's already done anyway.
No, because you would also store either a separate datetime or uuid on each user model. And if just one user has their credentials compromised, then you would bump the date or generate a new UUID for just that user.
The global datetime would only be bumped if some site wide vulnerability were found.
Proponents say critics dont offer alternatives at the same time they always literally 'reverse' engineered sessions if you dig deep enough.
I give up. JWT is just a hip thing to do right now. :(
That's what I do in my system.
- your JWT libraries don't do anything dumb like accepting the `none` algorithm
- you're using HMAC SHA-256
- your access tokens have a short (~20 min) expiration time
- your refresh tokens are easily revocable
Can you elaborate on the specific security advantages that a token encoded with ActiveSupport::MessageEncryptor would have over such a JWT implementation?
Why do you think there aren't more AS::ME implementations out there if it's a superior solution? I only know of a Go implementation and haven't seen others: https://godoc.org/github.com/mattetti/goRailsYourself/crypto
Edit
I saw you mention Fernet in another comment. As a Heroku alum I'm quite familiar with Fernet (we used it for lots of things), but to my knowledge those projects are on life support at best.
I go farther still and require a VERY short expiration on service to service requests (documented as 1m, coded as 2m) which combined with https limits the chance of replay attacks.
HMAC is great for monolithic architecture, but I've quite enjoyed using asymmetric RS256. I don't think that's something AS::ME offers.
My (limited) understanding is the security issues arise around the implementation & handling some of the default claims (NBF, IAT, etc.) and producing/verifying the signature.
But I don't quite understand how moving to a different format solves these issues?
The OP article makes it sound like it's impossible to use JWT correctly, but I was under the impression that if I 1) am the issuer, and 2) I hardcode a single algorithm on my API endpoints, that neither of the issues in the OP apply. (The EC issue would apply if that algorithm was chosen).
Is there a safe subset of JWT? And isn't there value to small players in using the safe subset of JWT which is battle-hardened by guys with big security teams like Google?
What is the significance of that part?
Of course, it'd be better still to use a format _meant_ to provide human-readable canonical representations of data, e.g. Ron Rivest's canonical S-expressions (http://people.csail.mit.edu/rivest/Sexp.txt), but of course this is information technology and we have to reinvent the wheel — usually as an irregular polygon — every 3-4 years rather than using techniques which are tried and true.
Presumably this means that you have to have have a "flat" JSON structure rather than lots of nested objects and arrays?
Could you give more info about this? If ECDHE-ES is avoided why else is JWT insecure?
1. Take something like AS::ME that already has real use and implement it for as many platforms as possible
2. Define a really restricted subset of JWT (which may be necessary anyway for purposes of saying to management "yes, we're buzzword compliant")
3. Invent a non-AS::ME "bag-of-attributes secure bearer token" system and implement it everywhere.
I think part of the trouble with 3 is that people like me genuinely worry that if we tried to roll our own we'd manage to do worse than JWT in spite of JWT being terrible.
So maybe step zero is for somebody with crypto knowledge to explain one sane way to do the "bag-of-attributes secure bearer token" part ... or you to point the audience to a blog post that already exists that describes it, because, well, because I suspect quite a few of us trust you to say "this post actually describes a sensible plan" while we don't trust ourselves to be able to tell.
For example, AS::ME relies on shared secrets, which I think makes it unfit for distributed systems. Implementing JWK with asymmetric keys can really reduce provisioning and configuration costs. Keeping the signing secret on one private, hardened auth server (or cluster) also allows smart things like automated key rotation.
2. 100%. There's at least one right way to do JWT, but more ways to do JWT wrong.
3. JWT et al provide a fine starting point, I don't see a reason to start from scratch.
I'm not tied to the JWT spec, but I'm quite happy with what I've been able to accomplish using a careful implementation in my AuthN server: https://github.com/keratin/authn
JWT is a perfectly valid structure, even if the spec is more flexible than it should be. By that matter, https also has historically supported algorithms and protocols later broken. Nobody is suggesting we stop use HTTPS, only that we limit acceptable protocol and algorithms supported.
https://github.com/fernet/spec/blob/master/Spec.md
Fernet was written originally for Python but there's a Ruby implementation, a Golang implementation, and a Clojure implementation. I believe that for at least 80% of applications considering JWT, Fernet provides exactly the right amount of functionality, and does so far more safely than JWT.
Clojure implementation:
https://github.com/derwolfe/fernet-clj
I also found a JavaScript implementation:
Am I right that this would work fine both in that or in e.g. a query parameter?
(sorry if I'm asking really stupid questions, but I'd rather look stupid than accidentally a security hole)
Beyond this a header/signature for the body/payload will reduce the risk of the rest.
As to being able to select the signature algorithm, or set the uri for the public key... ignore this, or whitelist domains or methods. Yes, there's some wholes regarding a "by the books" implementation... that doesn't mean you need to support the entire spec.
I implemented about 1/2 the SCORM spec in an API once, and it was 8 years before a specific course needed a part that was missing. Yes, it isn't 100% compliant, but if it does the job, and is more secure as a result, then I'm in favor of it.
I thought crypto mantra was "Never roll your own." An RFC (Request For Comments) is a literal attempt to follow that advice by seeking the advice of cryptographers who are presumably smarter at coming up with crypto standards. Where were the cryptographers during the draft phase when comments were being solicited?
>I think it's literally the case that no cryptographer bothered to point this out before because they all assumed people knew JWT was a tire fire.
Oh. Cunningham's Law. You know, if you're not part of the solution, you're part of the precipitate.
That's some considerable JWT fallout, since companies making a business out of security are endorsing it. Auth0 for example, https://auth0.com/docs/jwt
Until I read this article, I was under the impression JWT was the best new thing.
You have a responsibility to built trustworthy systems, and you get no pass on building with flawed components simply because you wish experts had made those components less flawed.
Meanwhile your comments bury whatever substantive content they might hold under layers of emotional, accusatory garbage. Maybe get those feelings locked down a bit before posting?
If you have access to an experienced devops team who can securely maintain an nginx server with some proxy logic then maybe that's a possibility, but otherwise what other viable options are there? Wishing that JWT were more secure won't make it so, but neither will wishing that CORS were more flexible. And if it's a choice between subclassing the JWT handlers to provide a couple extra security checks vs trying to securely configure and maintain a whole extra proxy setup, then the former seems like the lesser of the evils.
[1]: https://docs.aws.amazon.com/cognito/latest/developerguide/am...
Can you explain what you mean, as oppose to other kinds of session tokens?
Roy Fielding makes it abundantly clear[0] in the seminal delineation of REST that
We next add a constraint to the client-server interaction: communication must be stateless in nature, as in the client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3), such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
This has given me pause to doubt just how many people are really implementing REST, and/or how useful a model it is in modern web applications.[0]https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arc...
Not many. I've made a good career out of consulting people who are doing REST wrong :)
Usually they are either storing state or forgetting about HTAEOAS (Hypermedia). Often they are also negotiated format and version incorrectly and in a way that doesn't scale.
Absolutely. If you GET a collection resource, then POST a new item into the collection, then GET the collection again, the response will have changed. Having these kind of temporal dependencies on the answer you receive is not something REST argues against.
Dear Americans, the queen would like you to stop saying "could care less" - by David Mitchell of Peep Show
Between that and the incessant use of the incorrect phrase "for free" instead of the correct phrase "for nothing" it's amazing that I can stand to read anything on the internet.
xD
xD
I don't hate secure cookies or anything, but some people act like plain-old regular cookies haven't been thoroughly solved by this point.
Related: Something people get wrong a lot with secure cookies is worrying about obscuring the cookie more than securing it. Encryption does not give you authentication; you need MAC for that. An encrypted message can still be blindly modified. Imagine being able to change a UID stored in a "secure" cookie even if you couldn't 100% control which. Eventually, if you try enough permutations, you're going to escalate your privileges!
Need an emergency revoke of every token? Easy: Replace your signature key. Any older token will fail signature verification. In which case, your system should require authentication and then generate a new token with an updated signature.
You have a single page webapp that uses two APIs for part of the application. For security reasons the APIs are zoned in such a way that neither of them can communicate with each other. The machine of the user sits in a zone where it can send HTTP requests to the zones of either API.
Now design a way to manage sessions across both APIs...
There are certainly a number of ways to accomplish this, but JWT was the cleanest and most performant.
If all the servers are in one location, a random byte sequence as session id key with cached info is the most simple, compact and efficient.
Distribute signing and encryption keys to all servers. Have them encrypt and sign the outgoing serialized token, whatever that consists of. Have them verify and decrypt the incoming token. This is just straight-forward cryptography, with keys known only to the server, so I'm pretty sure you won't get any arguments from (1). (And, I suppose the encryption could even be skipped, if you don't care that the internal format of the token is known.)
Emergency revocation of all tokens [0] is simply rotating the signing key. All tokens issued prior to the rotation will fail verification with the new key. That should trigger the authentication process, which will issue a new token with the updated key. This solves the revocation issue present in argument (2).
[0] Any other form of revocation is, in my opinion, not distinguishable from having server-side state. If you have to keep a list of bad tokens, why not just keep a list of the good tokens instead... And then it's only a short hop to the token being nothing but a key to lookup the full session state on the server.
Nobody has to implement the FULL spec, you only need to allow what your environment needs.
I just want you to know that such tactics are not very appreciated from this side of the conversation.
What does JWT provide that using bog-standard crypto primitives in the way I described doesn't? Other than a name and a standard?
Isn't this how HTTPS works, HTTPS today doesn't use the same SSL and algorithms allowed in 1996, it's evolved and changed in practice. The author isn't suggesting everyone just not use HTTPS because some possible algorithm has been determined to be weak is he?
I think this is a very interesting, because it's basically validating the article's argument. People are going to feel safe implementing JWT because it's an RFC, without knowing where these "generally bad idea" landmines are. That's the dangerous part.
And yes, the same issues exist in SSL / TLS. And guess what? There's loads of articles just like this one stating how dangerous older modes of these protocols are. Articles like this and the discussions they spawn are exactly the kind of thing necessary to move the world forward into safer implementations.
Aren't cookies just strings passed as HTTP headers?
(I'm much more in the localStorage + Authorization header for this reason. I recommend [1] for reading. If malicious JS is running, cookies won't save you, since the malicious JS is capable of simply making the request itself, to which the cookie will automatically be attached by the browser. localStorage+JS eliminates CSRF. If someone XSS's you, the difference is irrelevant.)
[1]: http://blog.portswigger.net/2016/05/web-storage-lesser-evil-...
That's just exchanging one security issue for another. Now you have the ability for people to steal tokens after an XSS attack. And yes, that's significantly different from "can make requests on your behalf".
The correct solution is to solve the CSRF vulnerabilities by using CSRF tokens. Not to change your auth persistence mechanism.
* Use SameSite cookies (unfortunately, not yet supported by all browsers)
* Don't accept application/x-www-form-urlencoded, multipart/form-data, or text/plain at your endpoints, or
* Use CSRF tokens if you need to accept server-side rendered HTML forms
XSS is a lot harder to protect against, one of the better ways to mitigate it's effects is to use http only cookies
XSS is avoidable by systematically having a framework that escapes any inputs that are run through it. (jinja2, on the server, can do this, though it defaults to not, which I wish wasn't true.) I'm not saying that XSS is much better that CSRF, really; I've seen these, too.
the point (and that of the linked article) is more that either you're not subject to XSS, in which case localStorage is strictly better than cookies (it is default-secure), or you're subject to XSS, in which case neither saves you.
Definitely if your service is a valuable target that hackers will spend the time to reverse engineer your client code to create custom tailored XSS attacks then protecting against Session Hijacking does seem to be pointless.
But session hijacking is considered to be a very common attack (though I can't find any real numbers anywhere, maybe it's not?), most services with low attack value will probably be better served by httpOnly cookies and csrf tokens that make worthwhile XSS attacks more time consuming then preventing XSS altogether, which is an enormous, continuous effort.
Also your implying that CSRF is hard to defend against (otherwise why do you keep running into it) but in the same breath saying that XSS is simple to defend against.
If people can't defend against CSRF (which is usually just a simple flag for most frameworks), they aren't prepared to defend against XSS which means getting into a security mindset in all things. A serverside template is not enough - XSS can manifest in headers, in clientside code, in third party code, in redirections and it is easy for a developer to mistakingly add a new attack surface.
But if I write some code using DRAKMA, urllib or net/http, and can see those cookies just fine.
> Although I suppose you could argue that a cookie is just another header value.
So... yes.
But yes, it is.
Here is a point of order for developers who work on something realize it isn't idiot proof (them proof) out of the box and then want to write a sensational post:
Implementation and design are a core part of anything you do and considering the risks and accounting for them are part of doing business.
Having worked with large organizations that do active and passive scanning of the web I am constantly shocked how often we are contacting someone about basic SQL injection in their application... in 2017.
JWT is an incredibly powerful standard if implemented effectively but its not for the LAZY, it requires thoughtfulness where ever it is active.
JWT solves a serious and real problem that organizations face at scale which is why you see it implemented in systems like google sign in. Realistically its not going anywhere.
People love criticizing the movement towards stateless tokens on the web I find it pretty funny... crawl down the stack from their webheads and you usually come face to face with Kerberos managing auth within their networks...
Server-side session tokens stored in the database worked fine ten years ago, and they work fine today. No need to muck with the load balancer.
Stateless tokens are great too, and use two-factor auth when you need that extra layer of security. No need for newfangled standards; HTTP Basic remains a simple and effective way to convey that token.
This is as opposed to < 0.1ms for verifying a JWT. JWT is a structure for stateless tokens... once you have a token, what does 2FA add? nothing. Also, some algorithms are insecure, so don't use them, or blacklist them... Or, better whitelist the algorithm you do use.
Very short lived JWT mitigates this as the window for replay is reduced, over HTTPS by the time you can crack it, that window is effectively gone. The server can verify a signature on a JWT in a fraction of a second... far faster than a DB call... Not including replication issues.
OAuth2 + JWT is fine... just whitelist the algorithms you allow and use HTTPS for all communications, even internal.
A server with 1GB can hold a lot of JWT's in memory. Probably more than most of the people building services here have to actually deal with.
Your tokens should generally have a rather short lifetime - then you can keep the entire relevant window of revocations in memory.
The implementation is not trivial though, that's for sure.
No? Maybe? It depends on your load balancer. Assigning a client to a specific server is "sticky sessions". Many of us don't want to tie a client to a specific server and prefer a completely stateless 12-factor-style mechanism where any server can serve the client and stateless tokens provide a mechanism to achieve this.
without revocation. What's wrong with tieing a client to a server, or co-located server? Either they are close enough to share tokens / sync fast, or not?
Nothing, if you can get away with it. What do you do if your server dies or is overloaded? The 12-factor patterns came to be for services running on ephemeral hosts in cloud environments. Stateless servers mean you can seamlessly serve requests from another server without problem. Sure, you can store the sessions in a shared resource (redis perhaps?) but this complicated failover and redundancy and may add latency.
Maybe this isn't an issue, maybe it is. If you don't need or want that, then just use normal sessions, for sure.
Revocation can be handled (although admittedly not as well as with sessions or stored tokens) through short TTL's and refresh tokens (which are stored, but only need to be looked up when the stateless token expires). Its not perfect, but its often a good enough tradeoff.
By your measure, 1GB can store a lot of tokens in memory: 32B tokens + that again as metadata (e.g. user ID + TTL in Redis) = 15,625,000 tokens.
And you're overestimating the necessary size of a revocation store. Only a tiny fraction of your users ever log out or otherwise invalidate session via means other than TTL. You're looking at storing just a couple thousand 4-8 byte revoked session ids and ttls instead of gigabytes of session data.
If you have a security breach and need to invalidate all tokens, just reject all tokens with an issue date before it's fixed. And they all fall off anyway after a week (or however long the ttl is).
For client-server a 5 minute refresh is fine, as long as you do a lookup for refresh, so you can expire refresh tokens, requiring a full re-auth.
The purpose of this article it criticize the standard, not particular libraries.
(1) Criticizing vulnerabilities in particular JWT libraries, as in this article.
(2) Generally criticizing the practice of using any "stateless" client tokens. Because there's no great way to revoke them early while remaining stateless, etc.
The problem is that both of these groups only criticize, neither of them can ever seem to actually recommend any alternatives.
I could care less about JWT per se. I'm happy to implement a similar pattern with something else (e.g. store a secure cookie post-auth, skip all the refresh business and just let it expire when it expires, and employ an ugly revocation strategy only if absolutely necessary). I don't need JWT for this.
If I'm providing a REST API, then I'd prefer a token string that I could pass as a header value rather than forcing the use of cookies. Although I suppose you could argue that a cookie is just another header value.
Either way, if you're serving up a REST API to a JavaScript UI... what's NOT a good option is server-side session state (e.g. Java servlet sessions). That requires you to either: configure your load balancer for sticky-sessions, or employ a solution to share session state across all your server-side instances (which never works very reliably). Moreover, relying on a session isn't a very RESTful auth strategy in the first place.
So if I'm writing a SPA in 2017, then I'm definitely taking a client-side approach and running afoul of the #2 critics. And since JWT is so widely implemented (e.g. if I use a "Login with Google" option then I'm using JWT), I'm probably running afoul of the #1 critics too.
These criticism are fine, I guess. There's no faster route to blog clicks, book sales, speaker invites, and consulting dollars than: (1) telling everyone to jump on this year's hype train, or (2) telling everyone that last year's hype train sucks. What the world really needs is a bit more actual prescriptive recommendations of what to do instead.