Giter Club home page Giter Club logo

ruby-jwt's People

Contributors

ab320012 avatar aj-michael avatar anakinj avatar andyjdavis avatar bellebaum avatar codemonkeysteve avatar emiliocristalli avatar excpt avatar gobinathal avatar jamesstonehill avatar johnnyshields avatar jonmchan avatar julik avatar korstiaan avatar lautis avatar martinemde avatar matteopierro avatar n-studio avatar nickhammond avatar ogonki-vetochki avatar petergoldstein avatar phlegx avatar progrium avatar rewritten avatar richardlarocque avatar sporkmonger avatar threedaymonk avatar tpickett66 avatar yasonk avatar zhanghandong avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ruby-jwt's Issues

Needs to support asymmetric key signatures over shared secrets

Currently, you are using a shared secret to validate the signature of the JWT messages. This entirely defeats the purpose of signing the message and would only be suitable if you were encrypting and not signing the message. The idea behind signing a message is that only the originator can generate the signature and that signature can be validated but not forged. In your implementation any node that needs to validate a signature must in turn be able to forge new ones, because it must know the shared secret.

Therefore, ruby-jwt should allow for the use of asymmetric key based signature generation and checking as outlined in the ruby stdlib OpenSSL documentation here: http://ruby-doc.org/stdlib-2.0/libdoc/openssl/rdoc/OpenSSL.html#module-OpenSSL-label-Signatures. This will allow JWT consumers to verify requests without the ability to forge new ones.

signatures calculated incorrectly (hexdigest instead of digest)

Hi,

Thanks for writing this gem! I'm working on the Java implementation of JWT, using the outputs of your Ruby gem to sanity check my results. I ran into an incompatibility and traced it to your use of OpenSSL::HMAC.hexdigest instead of OpenSSL::HMAC.digest (which is what the spec intends).

This is the spec I'm using:
http://self-issued.info/docs/draft-jones-json-web-token-01.html#anchor10

Your call to hexdigest() is in line 16 of jwt.rb.

Here's an example to illustrate the difference:
ruby-1.8.7-p302 > key = "abcdefghijklmnop"
=> "abcdefghijklmnop"
ruby-1.8.7-p302 > msg = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
=> "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
ruby-1.8.7-p302 > base64url_encode(OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'), key, msg))
=> "Hp4r9or7FRoPXBtCBbQmU3gxrR2d_rDq_2ZGqeshh4A"
ruby-1.8.7-p302 > base64url_encode(OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('sha256'), key, msg))
=> "MWU5ZTJiZjY4YWZiMTUxYTBmNWMxYjQyMDViNDI2NTM3ODMxYWQxZDlkZmViMGVhZmY2NjQ2YTllYjIxODc4MA"

Please let me know if you disagree, or are using a different spec.

Mikhail

Catch up for ActiveWhatever 4.1.1 series

When upgrading to Active* 4.1.1 my bundle quits on jwt 0.1.12 not being found.
For now I am adding this to my Gemfile:

 gem "jwt",  "0.1.12", :git => 'https://github.com/progrium/ruby-jwt.git', :tag => 'jwt-0.1.12'  

Any idea when this gem will hit rubygems at that version?

Is it possible to decode the payload without validating the signature?

Is it possible to decode the payload without validating the signature?

c="eyJpZCI6MSwidHlwZSI6Im1hbmFnZW1lbnQiLCJpYXQiOiIyMDE1LTA4LTA2VDE1OjA3OjEyLjM3MFoiLCJleHAiOjE0MzkxMzI4MzJ9"

Base64.decode64(c)
"{\"id\":1,\"type\":\"management\",\"iat\":\"2015-08-06T15:07:12.370Z\",\"exp\":1439132832}"

I tried using the Base64 lib, but it returns the result in an escaped formatted string

Add a changelog

I was just notified that version 1.5.2 has been released and I'm finding it difficult to evaluate whether or not to make it a priority to upgrade the version I'm using, because there is a lot of changed code and many commits to evaluate. A changelog summarizing the major changes in new versions and what they mean to users would be very nice to have.

I'm willing to work on putting it together, but I'm sure I'll need to bug somebody with lots of questions.

Thanks for the great library!

Must we specify algorithm when calling decode to avoid vulnerabilities?

First of all, cool library. I was reading through the closed issues, and noticed #76. It seems to suggest that in order to be sure you are safe from this vulnerability affecting RSA and ECDSA algorithms, you need to specify the algorithm when decoding a JWT, like so: JWT.decode(token, key, true, algorithm: 'RS512'). So I then read through the readme for this library, but did not see this algorithm parameter mentioned anywhere in the readme. So now I'm confused and a little concerned.

Has the need to specify the optional algorithm parameter been removed due to a commit somewhere that made this library more secure by default? (That would be good)
Or must users specify this optional, undocumented algorithm parameter in order to be secure? (That would be bad)

If the latter is the case, I'm happy to help update the docs to clearly explain the algorithm needs to be passed in to keep things more secure.

Fix either README or source code

I found that README has incorrect (not yet implemented) examples.
I do use the iss check in the app and implemented it using my wrapper class.

After the 1.5 released, I removed the wrapper and tested the jwt gem. It appears that it requires special "setup" before:
5c09aad#commitcomment-11125584

Verify ISS should be off by default

It looks like 1.4.0 adds a new feature to verify the iss claim. The problem is that this feature is enabled by default, so if existing code doesn't specify an iss value for the options then the verification fails.

It seems that for backwards compatibility :verify_iss should be false.

set token to expire

Is it possible to set an expiration date on the token? Or do we have to do this manually by specifying a header key and comparing that ourselves with the current date?

Shouldn't verification of additional claims, like iss, aud etc. be enforced when in options?

First of all - thanks for the great gem!

What I've stumbled upon while using the gem is the verification of additional attributes, like e.g. the "iss" claim. When "iss" is supplied to the options in JWT.decode it is not enforced or checked, even when verify_iss is set to true as long as it's not present in the actual payload. Basically I've had the following decoding code:

options = {
  algorithm: 'HS256',
  verify_iss: true,
  'iss' => 'acme.org'
}
payload, = JWT.decode(token, "secret", true, options)

and provided it a token like:

token = JWT.encode({ data: 'payload' }, 'secret', 'HS256')

and expected it to raise an error, because iss is not set in the payload - is this assumption wrong? Should the presence of these attributes be verified again by the application? Looking at jwt.rb#166 the issuer is only verified when it's present in the payload. From my point of view - and I think the more "safe" variant - would be to always trust the options and when "iss" is present in the options then enforcing the check against the issuer.

PS: I'm not savvy with the JWT spec, so it can be that the JWT spec actually proposes the current design. Then just ignore & close my issue :)
PPS: And if this proposal makes sense, I'd be happy to create a PR

url safe encode and decode

This issue pops up when I am trying to make a JWT assertion to a service that isn't implemented using this gem. I think there may be an issue with base64url_encode.

body = JWT.encode({'foo' => 'bar'}, nil, nil).split('.').last
=> "eyJmb28iOiJiYXIifQ"
Base64.decode64(body)
=> "{\"foo\":\"bar\""

Shouldn't there be a closing curly brace on the above? I think you can use Base64.urlsafe_encode64 and Base64::urlsafe_decode64 instead of what you are doing in lines 38-45. I can submit a pull request with this unless there are any objections.

TypeError when specifying a wrong algorithm

So I ran my usual tests against tampered keys and I got a TypeError under MRI (2.0):

  1. Provide a tampered token with "alg": "HSMAC" (with a valid signature)
  2. Try to verify the token with an RSA public key
  3. TypeError: no implicit conversion of OpenSSL::PKey::RSA into String

I've monkeypatched my app to also rescue TypeError and not just DecodeError but this is just a temporary solution. Interestingly the error does not appear under JRuby.

I've recently read the article about possible security flaws in the library.
I really liked the suggestion to also pass the algorithm and not just the key when verifying the token. Any thoughts on that?

Release a new version

Can you please release a new version? The latest version in the gem repository does not include the exp claim implementation which is really practical. :)

verify_rsa no method 'verify' for class String

I recently switched my encoding algorithm from HS256 to RS256 and can no longer verify my tokens. Line 59 in jwt.rb seems to be the problem:

public_key.verify(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), signature, signing_input)

raises a no method error, no method 'verify' for type String. My public key is a string (no sure what else it should be?), and I don't see verify defined anywhere. What am I missing?

Thanks!

Update gem to get latest changes

Hello,

I must check the algorithm found in the token to avoid some errors, because you can encode with HMAC or RSA, but if we choose RSA, we use #encode where the shared secret is an instance of RSA, and the problem it's that is different it's a string when we choose HMAC.

Because I store the shared secret in my DB, I want to make restriction on the availables algorithms.

Could you please update your gem, because my current answer to this problem require to get access your latest added method #decoded_segments.

Semantic versioning

The last release included an incompatible change to JWT's interface which broke several of my projects. Any chance we could switch to semantic versioning so that consumers of this API don't unsuspectingly upgrade to incompatible versions?

Release

When will we get the next release?

The behavior using 'json' differs from 'multi_json'

Having in mind I just started with JWT a while ago, I see a difference between the two.

Back on node, I could save a simple integer as payload or even a string.

Here, I can do that also if I have multi_json but if not, it raises an exception so I am forced to save a hash.

It is not that important but it bugged me a while.

What do you think?

Support verifying signature signed using x5c header

It is currently possible to verify the signature of a jwt token using the x5c header by providing a key finder function. e.g.

jwt_token = ::JWT.decode(token) do |headers|
  OpenSSL::X509::Certificate.new((headers['x5c'].first)).public_key
end

In order to validate the x5c certificate chain in full, I must provide my own implementation. It would be great if ruby-jwt gem could support the validation of the x5c certificate chain natively.

Here is an excerpt from https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41#section-4.7

4.7. "x5c" (X.509 Certificate Chain) Parameter

The "x5c" (X.509 Certificate Chain) member contains a chain of one or
more PKIX certificates [RFC5280]. The certificate chain is
represented as a JSON array of certificate value strings. Each
string in the array is a base64 encoded ([RFC4648] Section 4 -- not
base64url encoded) DER [ITU.X690.1994] PKIX certificate value. The
PKIX certificate containing the key value MUST be the first
certificate. This MAY be followed by additional certificates, with
each subsequent certificate being the one used to certify the
previous one. The key in the first certificate MUST match the public
key represented by other members of the JWK. Use of this member is
OPTIONAL.

API request - JWT::decoded_header()

It would be useful is the different segments can be exposed like a public getter that returns header = MultiJson.decode(base64url_decode(header_segment)). I need the header to extract the thumbprint and use the right secret to verify signature.

Digest::Digest is deprecated; use Digest

In Rails 4.2.4, I see this warning from the OpenSSL call within encode when testing use rspec:

/opt/rubystack-2.2.3-2/ruby/lib/ruby/2.2.0/openssl/digest.rb:64
/opt/rubystack-2.2.3-2/ruby/lib/ruby/2.2.0/openssl/digest.rb:64:in `initialize'
/opt/rubystack-2.2.3-2/ruby/lib/ruby/gems/2.2.0/gems/jwt-0.1.8/lib/jwt.rb:33:in `new'
/opt/rubystack-2.2.3-2/ruby/lib/ruby/gems/2.2.0/gems/jwt-0.1.8/lib/jwt.rb:33:in `sign_hmac'
/opt/rubystack-2.2.3-2/ruby/lib/ruby/gems/2.2.0/gems/jwt-0.1.8/lib/jwt.rb:16:in `sign'
/opt/rubystack-2.2.3-2/ruby/lib/ruby/gems/2.2.0/gems/jwt-0.1.8/lib/jwt.rb:53:in `encode'
Digest::Digest is deprecated; use Digest

Incorrect readme for leeway

Readme incorrect parameter documentation, missing hash rocket

specs:
ln:155 decoded_payload = JWT.decode(jwt, secret, true, {:leeway => 3})
readme:
JWT.decode(jwt_payload, 'secret', true, leeway=10)

change to signature of JWT.decode method

JWT.decode can now, since the inclusion of MultiJson, raise a MultiJson::Decode error from lines 67 and 68. This means that he method signature of decode has changed to raise both JWT::DecodeError and MultiJson::DecodeError. Was this change intentional? It's breaking some test cases of mine that expect a JWT::DecodeError to be raised.

Options hash uses both symbols and strings as keys.

I tried to verify the issuer on a JWT that I was decoding today, and I found this line (and others like it) very ugly.

if options[:verify_iss] && options['iss']

This means that my code to decode the JWT looked like this:

JWT.decode(token, public_key, true, :verify_iss => true, 'iss' => 'my issuer')

In my opinion, the consumer of this API should be be able to do one of the following:

  1. Always use symbols as keys in the options hash.
  2. Always use strings as keys in the options hash.
  3. Be able to either use symbols or keys in the options in hash and have our library deal with it under the hood.

Thoughts?

ECDSA signature verification fails for valid tokens

ruby-jwt fails with a Signature verification failed (JWT::VerificationError) error when decoding a valid JWT signed with ES512. I believe this is due to an issue with improper ECDSA signature serialization format where the signature parameters are not concatenated in the proper order. The improper serialization results in an implementation being able to successfully verify its own JWTs but not those generated by other conforming libraries.

We encountered the same issue and fixed it on PyJWT a little while ago but some users are now reporting issues with ruby-jwt validating ECDSA-signed tokens and I wanted to pass along the information. PyJWT now has tests validating it against RFC 7520 test vectors to ensure all algorithms serialize properly. It may be a good idea to do a similar thing here.

Ruby test (using ruby-jwt):

require 'jwt'

token = 'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJoZWxsbyI6IndvcmxkIn0.AQx1MqdTni6KuzfOoedg2-7NUiwe-b88SWbdmviz40GTwrM0Mybp1i1tVtmTSQ91oEXGXBdtwsN6yalzP9J-sp2YATX_Tv4h-BednbdSvYxZsYnUoZ--ZUdL10t7g8Yt3y9hdY_diOjIptcha6ajX8yzkDGYG42iSe3f5LywSuD6FO5c'
pubkey_pem = "-----BEGIN PUBLIC KEY-----\nMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAcpkss6wI7PPlxj3t7A1RqMH3nvL4\nL5Tzxze/XeeYZnHqxiX+gle70DlGRMqqOq+PJ6RYX7vK0PJFdiAIXlyPQq0B3KaU\ne86IvFeQSFrJdCc0K8NfiH2G1loIk3fiR+YLqlXk6FAeKtpXJKxR1pCQCAM+vBCs\nmZudf1zCUZ8/4eodlHU=\n-----END PUBLIC KEY-----"

pubkey = OpenSSL::PKey::EC.new pubkey_pem
JWT.decode token, pubkey

Python test (using pyjwt):

import jwt

token = 'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJoZWxsbyI6IndvcmxkIn0.AQx1MqdTni6KuzfOoedg2-7NUiwe-b88SWbdmviz40GTwrM0Mybp1i1tVtmTSQ91oEXGXBdtwsN6yalzP9J-sp2YATX_Tv4h-BednbdSvYxZsYnUoZ--ZUdL10t7g8Yt3y9hdY_diOjIptcha6ajX8yzkDGYG42iSe3f5LywSuD6FO5c'
pubkey_pem = '-----BEGIN PUBLIC KEY-----\nMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAcpkss6wI7PPlxj3t7A1RqMH3nvL4\nL5Tzxze/XeeYZnHqxiX+gle70DlGRMqqOq+PJ6RYX7vK0PJFdiAIXlyPQq0B3KaU\ne86IvFeQSFrJdCc0K8NfiH2G1loIk3fiR+YLqlXk6FAeKtpXJKxR1pCQCAM+vBCs\nmZudf1zCUZ8/4eodlHU=\n-----END PUBLIC KEY-----'

jwt.decode(token, pubkey_pem)

What is audience?

What exactly is aud (audience)? Can this represent roles of the user session / owner of the token? i.e. admin, guest, etc?

JWT.encode({"exp": 10}, "secret")

This seems to be not working. I am using gem 'jwt', ~> 1.2.0

Error Message
SyntaxError: (irb):3: syntax error, unexpected ':'
JWT.encode({"exp": 10}, "ssss" )

decode fails with 'none' algorithm and verify

When providing a token that has the algorithm 'none' to the decode method, a decode error is raised from line 87 with the error message 'Not enough or too many segments'.

This can be suppressed by disabling verification when decoding, but that has knock-on effects of other claims not being verified.

I believe the correct behaviour should be that, when the algorithm is 'none' and the token is otherwise valid, the decode method should return successfully.

It is worth noting that this behaviour provides (accidentally, I believe) protection against certain attacks. To provide support for this without exposing users to additional vulnerabilities, I would suggest also adding some flag (that defaults safely) that allows the developer to 'turn on' acceptance of the 'none' algorithm.

JWT.encode({"exp": 10}, "secret")

This seems to be not working. I am using gem 'jwt', ~> 1.2.0

Error Message
SyntaxError: (irb):3: syntax error, unexpected ':'
JWT.encode({"exp": 10}, "ssss" )

aud verifies if aud is passed in, :sub does not

If you pass in :aud and :verify_aud, then it will fail if :aud is not in the payload.

the equivalent is not true for :sub. If you pass in :sub but it is not in the payload, it won't do anything. I would expect the behavior of :aud, which is if you ask to verify_sub, it will fail if it isn't in the payload.

if that sounds reasonable, I'll submit a patch. thanks!

jti verification not working per the spec

The jti verification implemented here supports a variant of the spec, but is far to limited to a specific use case.

The spec (see https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.7) stipulates that the claim should be a unique ID, but not an algorithm for generating such a unique ID. The supported verification here would enforce a specific algorithm, requiring an iat claim to be present as well as a key.

The iat claim is optional and unrelated to the jti claim in the spec and the key may either not exist in the case of an unsecured JWT or be unknown to the sender in the case of an asymmetric signing or encryption algorithm being used.

The iat claim is also defined as the integer number of seconds since epoch. This means that its use as a nonce to prevent replay isn't particularly valid. Given that it cannot be assumed that this is unique from an issuer, which may be issuing thousands of tokens with the same secret per second, adding this is quite limiting.

Further, the current implementation requires the developer to know the key, iat value for the JWT and also the algorithm used to generate the jti claim in order to decode the token.

The implementation provided for the jti verification is application-specific, so probably doesn't belong in a library such as this.

An alternative implementation might be to delegate verification of the uniqueness of the token to the application through a callback.

Suggest passing block to JWT.decode for claim verification

The current method for verifying the JTI field in the token payload is only useful when the JTI value to compare against is known a priori (when making the call to JWT.decode).

Summary: Using a block parameter or callback on JWT.decode to verify claims (passing the decoded payload/claims) would be more flexible and nicer API IMHO

When the JTI value is dependent on information in the token payload (for example a user object found using a user_id field in the payload), then we can't pass the expected JTI value in the options hash to JWT.decode. In this case we don't know the expected value until after the token has been decoded. The same goes for comparing a JTI value to a blacklist.

The usefulness of the options {verify_jti: true, jti: 'expected-value'} passed to JWT.decode is limited. Maybe the same goes for iss, aud and sub.

May I suggest an alternative API for verification of jti, iss, aud and sub which is to pass an (anonymous) block to JWT.decode for verification. The payload would be passed as parameters to the block. When the block returns falsey, then JWT.decode would raise a JWT::VerificationError.

For example: Given the following verification function ...

def valid_token?(payload)
  valid_user?(payload['user']['id']) && !blacklisted?(payload['jti'])
end

... with the current API I have to do:

payload, header = JWT.decode(token, 'my-jwt-secret')
valid_token?(payload) || raise AuthenticationError # application specific exception

... With a verification block this would become:

JWT.decode(token, 'my-jwt-secret') do |payload|
  valid_token?(payload)
end # when valid_token? return falsey raises JWT::VerificationError (for example)

The current verfication of the exp, nbf and iat claims is unambiguous so it can be handled in JWT.decode with the current flag-and-expected-value-in-options-hash method. But I would prefer the block method to be the only method to verfiy claims. Special 'build-in' methods could be used for verification of exp, nbf and iat claims.

JWT.decode(token, 'my-jwt-secret') do |payload, header|
  valid_exp?(payload['exp']) && \ # built-in
  valid_nbf?(payload['nbf']) && \ # built-in
  valid_iat?(payload['iat']) && \ # built-in
  valid_token?(payload) # user defined
end # when valid_token? return falsey raises JWT::ValidationError (for example)

This method doesn't require a separate flags to indicate which claims to verify.

Sorry this has gotten a bit long. I hope I explained well.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.