Skip to content

Decoding with x509 certs #77

Closed
Closed

Description

@gpit2286

I'm having a hard time authenticating a token using a x5c. (MS OAuth/Azure)

Below is the code...

// Trying to isolate the problem by only checking the signature. 
let validation_config = jsonwebtoken::Validation {
            algorithms: vec![jsonwebtoken::Algorithm::RS256],
            leeway: 0,
            validate_exp: false,
            validate_iat: false,
            validate_nbf: false,
            aud: None,
            iss: None,
            sub: None
        };
let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIn...";
let x5c_cert = "MIIDBTCCAe2gAwIBAgIQKOfEJNDyDplBSXKYcM..."; 

let raw_der = base64::decode_config(der, base64::STANDARD).unwrap();
let d = jsonwebtoken::decode::<MsOAuthPayload>(&token, &raw_der, &validation_config);

The above always returns InvalidSignature.

Anyone have some insight on what I'm doing wrong here?

Thanks

Activity

  1. maxburke commented on Mar 8, 2019

    @maxburke
    Contributor

    I'm running into the same issue, too. My use case is the same as yours; I'm attempting to validate a JWT provided by Microsoft's authentication system.

  2. Keats commented on Mar 8, 2019

    @Keats
    Owner

    You can try to clone jsonwebtoken locally to see where it is failing: InvalidSignature would be caused by any error in that fn https://github.com/Keats/jsonwebtoken/blob/master/src/crypto.rs#L100-L113

    A first thought on why it doesn't work could be that Microsoft maybe doesn't use URL safe base64?

  3. maxburke commented on Mar 8, 2019

    @maxburke
    Contributor

    I'm wondering, could it be because the x5c field has the x509 certificate chain and not just the public key?

  4. gpit2286 commented on Mar 8, 2019

    @gpit2286
    Author
  5. samuela commented on Mar 18, 2019

    @samuela

    I'm having the same issue with Auth0. Even with the correct certificate and a valid token (verified with jwt.io) jsonwebtoken reports InvalidSignature. (See #80 for more details.)

  6. samuela commented on Mar 18, 2019

    @samuela

    Side note: Can we change the name of this issue slightly? It doesn't really seem to be about x5c to der conversion at this point. I wasn't aware of it when I initially came across the same thing.

  7. Keats commented on Mar 18, 2019

    @Keats
    Owner

    From #80 it does look like it is a common failure with x509 certificates.

    Would anyone have some time to look into that? Can start with creating some test certificates and see what is happening.

    The current situation with all various combinations of algorithms/key types is becoming unwieldy, hopefully after something like #76 it will be easier to use

  8. changed the title [-]x5c to der[/-] [+]Decoding with x509 certs[/+] on Mar 18, 2019
  9. samuela commented on Mar 18, 2019

    @samuela

    @Keats I personally don't have time to look into it at the moment, but I'd be happy to help out/explain my setup/provide example test cases that are breaking for me for whoever would like to take a stab at it.

  10. Guara92 commented on Apr 9, 2019

    @Guara92

    I have the same issue with EC certificate, created with
    openssl ecparam -name secp384r1 -genkey -noout -out p384-private-key.pem
    openssl ec -in p384-private-key.pem -pubout -out p384-public-key.pem
    then converted to der format
    openssl pkcs8 -topk8 -inform PEM -outform DER -in p384-private-key.pem -out p384-private-key.der -nocrypt
    openssl ec -pubin -inform PEM -in p384-public-key.pem -outform DER -out p384-public-key.der

    I can verify the token with jwt.io using the pem file, i'm doing something wrong converting the keys?

  11. maxburke commented on May 9, 2019

    @maxburke
    Contributor

    @gpit2286 I'm not quite sure this will close the issue; it isn't that the input has the ----BEGIN xxx----- tags, it's that the validation doesn't succeed when a certificate (ie: identity information + public key) is provided to validate against.

  12. maxburke commented on May 11, 2019

    @maxburke
    Contributor

    I have more information now, at least with the Azure use case.

    The x5c field returned by the Azure keys endpoint does have both the certificate chain and public key. If the public key is extracted (ie: with openssl x509 -pubkey ...), verifying the JWT will still fail because the DER has an object ID field prepended to the public key. When the OID field and associated TLV data is stripped off, it works.

    I guess the question now is, should this parsing of the key from the cert and cleaning it up for ring's consumption be done by jsonwebtoken or by client code? I could provide a PR to do this, though it may introduce another package dependency.

    Thoughts? (@Keats ?)

  13. maxburke commented on May 14, 2019

    @maxburke
    Contributor

    For what it's worth, I'm using this code to extract the DER-formatted public key from an Azure ADB2C certificate and it seems to be working. It is depending on der-parser 1.1.1, nom 4.3.2, and rusticata-macros 1.1.0

    #[macro_use] extern crate nom;
    #[macro_use] extern crate rusticata_macros;
    
    use der_parser::*;
    use nom::{ErrorKind};
    
    /*
     * Test for a the sequence that contains the key (ie: modulus + exponent)
     *
     * TODO: Perhaps this should test the length of the modulus?
     */
    fn rsa_key_parser(seq: &[u8]) -> IResult<&[u8], DerObject> {
        parse_der_sequence_defined!(seq,
                                    parse_der_integer,
                                    parse_der_integer
                                    )
    }
    
    /*
     * The DER-encoded public key is stored within a bitstring embedded either
     * in a certificate or an x.509 public key.
     *
     * To find the bitstring we need to sift through the DER field sequences
     * recursively.
     */
    fn rec_extract_key(sequence: &Vec<DerObject>) -> Option<Vec<u8>> {
        for o in sequence {
            match &o.content {
                der_parser::DerObjectContent::BitString(_, bso) => {
                    match rsa_key_parser(bso.data) {
                        Ok(_) => { 
                            let mut key: Vec<u8> = Vec::new();
                            key.extend_from_slice(bso.data);
                            
                            return Some(key)
                        },
                        Err(_) => (),
                    };
                },
                der_parser::DerObjectContent::Sequence(s) => {
                    match rec_extract_key(s) {
                        Some(k) => return Some(k),
                        None => ()
                    }
                },
                _ => (),
            }
        }
    
        return None
    }
    
    /*
     * Extract a DER-formatted key from either a certificate or an x.509 public key
     */
    fn extract_key(cert: &[u8]) -> Option<Vec<u8>> {
        let result = parse_der(cert);
        let parsed = match result {
            Ok(p) => p,
            _ => return None
        };
    
        let (_, der_object) = parsed;
        match der_object.content {
            der_parser::DerObjectContent::Sequence(s) => rec_extract_key(&s),
            _ => None
        }
    }
    
    fn crack_token(jwks: JwksResponse, token: &Adb2cToken) -> Result<Claims, Box<Error>> {
        let header = decode_header(&token.access_token)?;
        let kid = match header.kid {
            Some(k) => k,
            None => return Err("Access token header does not have kid field".into())
        };
    
        let key = match jwks.keys.iter().find(|&k| k.kid == kid) {
            Some(k) => k,
            None => return Err(format!("Unable to find key id {}", kid).into())
        };
    
        let validation = Validation::new(header.alg);
        for cert in &key.x5c {
            let cert_der = base64::decode_config(&cert, base64::STANDARD)?;
            let key_vec = match extract_key(&cert_der) {
                Some(k) => k,
                None => return Err("Unable to extract key from provided certificate".into())
            };
    
            match decode::<Claims>(&token.access_token, &key_vec.as_slice(), &validation) {
                Ok(c) => return Ok(c.claims),
                Err(e) => { eprintln!("Error decoding: {}", e); }
            }
        }
    
        Err("No signing key successfully validated JWT claims".into())
    }
  14. Keats commented on May 14, 2019

    @Keats
    Owner

    Hmm that is adding quite a few dependencies :/

    Getting that added to ring is probably not going to happen so I think it would be to be in jsonwebtoken but need to consider API to match #76

    I think the first step to decide that would be to check how the JWT libraries in Python/Go/JS/etc handle x509 certs from Amazon/Google/Azure/others as well as generate some dummy x509 for testing.

  15. vmalloc commented on Jul 4, 2019

    @vmalloc

    I'm not sure my problem is related to the one here, but for me just trying to decode an example from jwt.io fails with Invalid Signature. For example, this fails:

    jsonwebtoken::decode::<String>(
            token,
            &openssl::rsa::Rsa::public_key_from_pem(pubkey.as_bytes())?.public_key_to_der()?,
            &jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::RS256),
        )?;

    Where both token and pubkey are a direct copy-paste from jwt.io (pubkey beginning with -----BEGIN PUBLIC KEY-----...)

    Is this related to this issue? Am I doing something wrong?

    Thanks in advance!

  16. 6 remaining items

  17. briansmith commented on Aug 12, 2019

    @briansmith
    Contributor

    Public key file from openssl:

    [30 82 1 22

    This is the wrapper header

    30 d 6 9 2a 86 48 86 f7 d 1 1 1 5 0 3 82 1 f 0

    This is the algorithm identifier.

    30 82 1 a 2 82 1 1 0 c4 d4 e5 fe a2 3e 5c 25 72 24 bd 4 f0 66 2e d0 59 f5 a0 b3 84 8 fd e7 6f 49 9c 9e db 4f 60 8c 0 c5 4d ae 20 72 e9 dc af 83 75 b0 9e 5d 55 6c a4 82 3b 7f c 95 b 35 a 73 e2 9e d b2 67 34 68 87 7a 52 3 5 50 ed e5 d 4a 24 1e a0 13 d6 25 fb 3c e1 7e 5e b3 da 93 e0 99 8c fa 63 9b bd ae d8 c3 d1 88 5e f6 6 73 f2 dc 16 1f 9a 6f e6 8d a5 e5 4a ed 8e 90 ec 22 6 a0 4d 89 4 1b 29 b0 24 a0 2 bc 28 f9 45 ed a4 73 8e f0 c4 21 d6 9f ad f6 33 83 50 bc eb cb bd bf 76 b9 47 cd 45 fc 46 fe 42 3a 13 46 3a 4c ee f4 c1 97 6d 99 68 c2 5e 82 dd 15 fc 3c 65 29 ec 41 e8 3f 88 cf 5a 8e 95 92 88 f3 ab 2d 2f 5f 59 c5 1c a8 d5 77 92 d 79 45 ef 72 be 26 7f 6c 6c b4 23 b2 d7 ab df ea cc 94 29 4 39 c4 e7 dd 4f e9 8 48 40 8c e0 8d e5 ee 83 8d 91 d9 42 e0 f8 89 a1 b1 ae e1 2b 2 3 1 0 1]

    This is the part that ring needs.

    [30 82 1 a 2 82 1 1 0 c4 d4 e5 fe a2 3e 5c 25 72 24 bd 4 f0 66 2e d0 59 f5 a0 b3 84 8 fd e7 6f 49 9c 9e db 4f 60 8c 0 c5 4d ae 20 72 e9 dc af 83 75 b0 9e 5d 55 6c a4 82 3b 7f c 95 b 35 a 73 e2 9e d b2 67 34 68 87 7a 52 3 5 50 ed e5 d 4a 24 1e a0 13 d6 25 fb 3c e1 7e 5e b3 da 93 e0 99 8c fa 63 9b bd ae d8 c3 d1 88 5e f6 6 73 f2 dc 16 1f 9a 6f e6 8d a5 e5 4a ed 8e 90 ec 22 6 a0 4d 89 4 1b 29 b0 24 a0 2 bc 28 f9 45 ed a4 73 8e f0 c4 21 d6 9f ad f6 33 83 50 bc eb cb bd bf 76 b9 47 cd 45 fc 46 fe 42 3a 13 46 3a 4c ee f4 c1 97 6d 99 68 c2 5e 82 dd 15 fc 3c 65 29 ec 41 e8 3f 88 cf 5a 8e 95 92 88 f3 ab 2d 2f 5f 59 c5 1c a8 d5 77 92 d 79 45 ef 72 be 26 7f 6c 6c b4 23 b2 d7 ab df ea cc 94 29 4 39 c4 e7 dd 4f e9 8 48 40 8c e0 8d e5 ee 83 8d 91 d9 42 e0 f8 89 a1 b1 ae e1 2b 2 3 1 0 1]

    Notice it is the same as this.

  18. Keats commented on Aug 12, 2019

    @Keats
    Owner

    Thanks for the info!
    I think it would be great for that to be in ring since it seems it fits better there than in webpki. Or it could be a stand-alone small crate but I am guessing it is common enough with RSA to warrant being in ring directly, at least for JWTs since it's almost always in .pem format.

  19. LeviSchuck commented on Aug 12, 2019

    @LeviSchuck
    Contributor

    Here's a proof of concept of a RS256 JWT with only ring, pem, and base64 as dependencies.
    a 2048 bit rsa PEM key is saved as private.pem

    extern crate base64;
    extern crate pem;
    extern crate ring;
    use ring::signature::KeyPair;
    
    const JWT_HEADER: &'static [u8] = b"{\"alg\": \"RS256\",\"typ\": \"JWT\"}";
    const PRIVATE_KEY: &'static str = include_str!("private.pem");
    
    #[derive(Debug)]
    pub enum MyError {
       BadPrivateKey,
       OOM,
    }
    
    pub fn jwt_none(payload: String) -> String {
      let body = base64::encode_config(payload.as_bytes(), base64::URL_SAFE_NO_PAD);
      let header = base64::encode_config(JWT_HEADER, base64::URL_SAFE_NO_PAD);
      format!("{}.{}", header, body)
    }
    
    pub fn key() -> Result<ring::signature::RsaKeyPair, MyError> {
      let private_key_content = pem::parse(PRIVATE_KEY).unwrap();
    
      ring::signature::RsaKeyPair::from_der(&private_key_content.contents)
          .map_err(|e| {
              println!("{}", e);
              MyError::BadPrivateKey
          })
    }
    
    fn jwt_signed(payload: String) -> String {
      let unsigned_jwt = jwt_none(payload);
      let key_pair = key().unwrap();
      let mut sig = vec![0; key_pair.public_modulus_len()];
      let rng = ring::rand::SystemRandom::new();
      key_pair.sign(&ring::signature::RSA_PKCS1_SHA256, &rng, unsigned_jwt.as_bytes(), &mut sig)
          .map_err(|_| MyError::OOM).unwrap();
      let signed = base64::encode_config(&sig, base64::URL_SAFE_NO_PAD);
      format!("{}.{}", unsigned_jwt, signed)
    }
    

    I do think it would be best if PEM support were in ring, but it can be done in the immediate like the above.

  20. brochington commented on Aug 31, 2019

    @brochington

    I'm not very familiar with the process of decode jwts in general, and while I'm trying to glean as much understanding I can from the issues in this repo, I am having a hard time understanding the current state of jsonwebtoken and x509. Would anyone be able to clarify the current status of using Auth0 (with RS256/x509) and this lib? I'm hitting the same problems that @samuela has hit, but would rather not jump ship to a something like Node. Thank you!

  21. upachler commented on Oct 3, 2019

    @upachler

    Looks like I'm having the same issue when attempting to validate JWTs issued by Keycloak. jsonwebtoken is unable to parse the public key....

  22. Keats commented on Oct 4, 2019

    @Keats
    Owner

    That's the same issue, the underlying crypto library is expecting the key to be in a specific format which is not the commonly used one.
    @LeviSchuck poc is interesting and a PR with that would be useful, even if we end up switching to the built-in ring function later on (briansmith/ring#370 (comment))

  23. LeviSchuck commented on Oct 4, 2019

    @LeviSchuck
    Contributor

    Sure, I can see if I can throw something together this weekend.

    Should this be feature gated, so pem isn't drawn in as a dependency unless requested?

  24. Keats commented on Oct 4, 2019

    @Keats
    Owner

    No need to feature gate it. Make sure you do the PR on the v7 PR in a standalone file since it still requires thinking about the UX and I have no clue what the usage would be like.

  25. Dowwie commented on Oct 29, 2019

    @Dowwie
    Contributor

    @LeviSchuck apologies if this has already been done but what is the status on the work for supporting PEM? this is blocking v7 release..

  26. LeviSchuck commented on Oct 29, 2019

    @LeviSchuck
    Contributor

    Hey there, sorry I had not gotten to this as planned.
    I should be able to get to this tonight.

  27. LeviSchuck commented on Oct 29, 2019

    @LeviSchuck
    Contributor

    So do I make a PR and then @Keats merges it into #91 ?

    EDIT: It looks like it would be merged onto next and then that'd be included on the 7.0.0 PR

  28. LeviSchuck commented on Oct 30, 2019

    @LeviSchuck
    Contributor

    There's absolutely no documentation on the functions yet. But I got tests that pass and I dabbled on the README a bit. LeviSchuck@755e4cb

    I would appreciate some feedback. It took more time than I anticipated with the nuances of PKCS1 and PKCS8 support with RSA and EC.

  29. Keats commented on Oct 30, 2019

    @Keats
    Owner

    Can you do a PR on the 7.0 PR? That will be easier to give feedback

  30. Keats commented on Jan 29, 2020

    @Keats
    Owner

    x509 is not supported and the issue changed topic quite a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions