Search in sources :

Example 1 with SignatureVerifierImpl

use of com.disney.http.auth.server.signature.SignatureVerifierImpl in project groovity by disney.

the class VerifierFactory method processSignature.

@SuppressWarnings({ "unchecked", "rawtypes" })
private SignatureVerifierImpl processSignature(Map signature, Class<Script> scriptClass) throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException, URISyntaxException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
    SignatureVerifierImpl verifier = new SignatureVerifierImpl();
    processCommon(verifier, signature, scriptClass);
    List<KeyChain> keyChains = new ArrayList<KeyChain>();
    List headers = (List) signature.get("headers");
    if (headers != null) {
        verifier.setRequiredHeaders(headers);
    }
    Number drift = (Number) signature.get("drift");
    if (drift != null) {
        verifier.setMaxDateDrift(drift.longValue());
    }
    Map<Object, Map> keys = (Map) signature.get("keys");
    if (keys != null) {
        // we need to convert to proper Key objects
        Map<String, Key> realKeys = new HashMap<String, Key>();
        for (Entry<Object, Map> entry : keys.entrySet()) {
            String algorithm = (String) entry.getValue().get("algorithm");
            Object secret = entry.getValue().get("key");
            String signingAlg = Algorithms.getSecurityAlgorithm(algorithm);
            Key key;
            if (signingAlg.startsWith("Hmac")) {
                // expect base 64 encoding
                key = new SecretKeySpec(DatatypeConverter.parseBase64Binary(secret.toString()), signingAlg);
            } else {
                // expect x509 encoding
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
                Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(secret.toString())));
                key = certificate.getPublicKey();
            /*X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(DatatypeConverter.parseBase64Binary(secret.toString()));
					KeyFactory factory = KeyFactory.getInstance("rsa");
					key = factory.generatePublic(pubKeySpec);
					*/
            }
            realKeys.put(entry.getKey().toString(), key);
        }
        keyChains.add(new MapKeyChainImpl(realKeys));
    }
    Map keystore = (Map) signature.get("keystore");
    if (keystore != null) {
        keyChains.add(makeKeyStoreLoader(keystore));
    }
    List<Map> keystores = (List<Map>) signature.get("keystores");
    if (keystores != null) {
        for (Map k : keystores) {
            keyChains.add(makeKeyStoreLoader(k));
        }
    }
    Object keychain = signature.get("keychain");
    addKeychain(keychain, keyChains, scriptClass);
    List kcs = (List) signature.get("keychains");
    if (kcs != null) {
        for (Object kc : kcs) {
            addKeychain(kc, keyChains, scriptClass);
        }
    }
    verifier.setKeyChains(keyChains);
    return verifier;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) KeyChain(com.disney.http.auth.keychain.KeyChain) MapKeyChainImpl(com.disney.http.auth.keychain.MapKeyChainImpl) CertificateFactory(java.security.cert.CertificateFactory) SignatureVerifierImpl(com.disney.http.auth.server.signature.SignatureVerifierImpl) ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) PublicKey(java.security.PublicKey) Certificate(java.security.cert.Certificate)

Example 2 with SignatureVerifierImpl

use of com.disney.http.auth.server.signature.SignatureVerifierImpl in project groovity by disney.

the class XmlPolicyParser method processSignature.

private static SignatureVerifierImpl processSignature(Element sig, ServletContext context) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException, MalformedURLException, URISyntaxException {
    SignatureVerifierImpl config = new SignatureVerifierImpl();
    List<KeyChain> keyChains = new ArrayList<KeyChain>();
    processCommon(config, sig);
    NodeList bcnodes = sig.getChildNodes();
    for (int j = 0; j < bcnodes.getLength(); j++) {
        Node bcnode = bcnodes.item(j);
        if (bcnode instanceof Element) {
            Element bcel = (Element) bcnode;
            if (bcel.getNodeName().equals("drift")) {
                config.setMaxDateDrift(Long.parseLong(bcel.getTextContent().trim()));
            } else if (bcel.getNodeName().equals("headers")) {
                config.setRequiredHeaders(Arrays.asList(bcel.getTextContent().trim().split("(,\\s*|\\s+)")));
            } else if (bcel.getNodeName().equals("keys")) {
                keyChains.add(new MapKeyChainImpl(processKeys(bcel)));
            } else if (bcel.getNodeName().equals("keystore")) {
                keyChains.add(processKeystore(bcel, context));
            }
        }
    }
    config.setKeyChains(keyChains);
    return config;
}
Also used : SignatureVerifierImpl(com.disney.http.auth.server.signature.SignatureVerifierImpl) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) KeyChain(com.disney.http.auth.keychain.KeyChain) MapKeyChainImpl(com.disney.http.auth.keychain.MapKeyChainImpl)

Example 3 with SignatureVerifierImpl

use of com.disney.http.auth.server.signature.SignatureVerifierImpl in project groovity by disney.

the class TestHttpSignature method testSigning.

@Test
public void testSigning() throws Exception {
    SignatureVerifierImpl verifier = new SignatureVerifierImpl();
    verifier.setMaxDateDrift(5000);
    final KeyStore testStore = KeyStore.getInstance("JCEKS");
    testStore.load(null);
    Key hmac256key = new SecretKeySpec("hello world".getBytes(), "HmacSHA256");
    testStore.setKeyEntry("hmac256key", hmac256key, new char[0], null);
    verifier.setKeyChains(Arrays.asList((KeyChain) new KeyStoreKeyChainImpl(new Callable<KeyStore>() {

        @Override
        public KeyStore call() throws Exception {
            return testStore;
        }
    }, new char[0])));
    DateFormat headerDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
    verifier.setRequiredHeaders(Arrays.asList(REQUEST_TARGET, "date"));
    MockHttpServletRequest request = new MockHttpServletRequest();
    ServerAuthorizationRequest areq = new ServletAuthorizationRequest(request);
    // FIRST TEST: missing signature
    VerifierResult result = verifier.verify(areq);
    Assert.assertEquals(ERROR_MISSING_SIGNATURE, result.getMessage());
    SignatureAuthorization signature = new SignatureAuthorization();
    signature.setAlgorithm("rsa-sha256");
    signature.setKeyId("rsa256key");
    signature.setHeaders(new ArrayList<String>());
    signature.setSignature(new byte[0]);
    request.addHeader("Authorization", "Signature " + signature.toString());
    // SECOND TEST: missing REQUEST_TARGET
    result = verifier.verify(areq);
    Assert.assertEquals(MessageFormat.format(ERROR_MISSING_HEADER_FORMAT, REQUEST_TARGET), result.getMessage());
    signature.setHeaders(Arrays.asList(REQUEST_TARGET));
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.addHeader("Authorization", "Signature " + signature.toString());
    // THIRD TEST: missing date
    result = verifier.verify(areq);
    Assert.assertEquals(MessageFormat.format(ERROR_MISSING_HEADER_FORMAT, "date"), result.getMessage());
    signature.setHeaders(Arrays.asList(REQUEST_TARGET, "date"));
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.addHeader("Authorization", "Signature " + signature.toString());
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 6000)));
    // FOURTH TEST: out-of-range date
    result = verifier.verify(areq);
    Assert.assertEquals(ERROR_INVALID_DATE, result.getMessage());
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.addHeader("Authorization", "Signature " + signature.toString());
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 3000)));
    // FIFTH TEST: unknown key ID
    result = verifier.verify(areq);
    Assert.assertEquals(MessageFormat.format(ERROR_UNKOWN_KEY_ID_FORMAT, signature.getKeyId()), result.getMessage());
    signature.setKeyId("hmac256key");
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.addHeader("Authorization", "Signature " + signature.toString());
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 3000)));
    // SIXTH TEST: rsa mismatch
    result = verifier.verify(areq);
    Assert.assertEquals(MessageFormat.format(ERROR_EXPECTED_RSA_FORMAT, signature.getKeyId()), result.getMessage());
    KeyPair keypair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    X509Certificate certificate = generateCertificate(keypair);
    testStore.setKeyEntry("rsa256key", keypair.getPrivate(), new char[0], new Certificate[] { certificate });
    signature.setKeyId("rsa256key");
    signature.setAlgorithm("hmac-sha256");
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.addHeader("Authorization", "Signature " + signature.toString());
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 3000)));
    // Seventh TEST: hmac mismatch
    result = verifier.verify(areq);
    Assert.assertEquals(MessageFormat.format(ERROR_EXPECTED_HMAC_FORMAT, signature.getKeyId()), result.getMessage());
    signature.setAlgorithm("rsa-sha256");
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.addHeader("Authorization", "Signature " + signature.toString());
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 3000)));
    // EIGHT test: invalid signature
    Exception sigEx = null;
    try {
        verifier.verify(areq);
    } catch (Exception e) {
        sigEx = e;
    }
    Assert.assertNotNull(sigEx);
    // NINTH test: good signature
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.setMethod("GET");
    request.setRequestURI("/");
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 3000)));
    String signingString = "(request-target): get /\ndate: " + request.getHeader("date");
    byte[] sigBytes = signMessage(keypair.getPrivate(), signingString, "rsa-sha256");
    signature.setSignature(sigBytes);
    request.addHeader("Authorization", "Signature " + signature.toString());
    result = verifier.verify(areq);
    Assert.assertTrue("Verification failed", result.isAuthenticated());
    // TENTH test: bad signature
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.setMethod("GET");
    request.setRequestURI("/nogood");
    request.addHeader("Date", headerDateFormat.format(new Date(System.currentTimeMillis() - 3000)));
    signingString = "(request-target): get /\ndate: " + request.getHeader("date");
    sigBytes = signMessage(keypair.getPrivate(), signingString, "rsa-sha256");
    signature.setSignature(sigBytes);
    request.addHeader("Authorization", "Signature " + signature.toString());
    result = verifier.verify(areq);
    Assert.assertFalse("Verification succeed when it should have failed", result.isAuthenticated());
    Assert.assertEquals(ERROR_VERIFICATION_FAILED, result.getMessage());
}
Also used : KeyPair(java.security.KeyPair) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ServletAuthorizationRequest(com.disney.http.auth.server.ServletAuthorizationRequest) KeyChain(com.disney.http.auth.keychain.KeyChain) KeyStore(java.security.KeyStore) Callable(java.util.concurrent.Callable) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SignatureVerifierImpl(com.disney.http.auth.server.signature.SignatureVerifierImpl) KeyStoreKeyChainImpl(com.disney.http.auth.keychain.KeyStoreKeyChainImpl) VerifierResult(com.disney.http.auth.server.VerifierResult) SignatureAuthorization(com.disney.http.auth.SignatureAuthorization) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SimpleDateFormat(java.text.SimpleDateFormat) Key(java.security.Key) PrivateKey(java.security.PrivateKey) ServerAuthorizationRequest(com.disney.http.auth.server.ServerAuthorizationRequest) Test(org.junit.Test)

Aggregations

KeyChain (com.disney.http.auth.keychain.KeyChain)3 SignatureVerifierImpl (com.disney.http.auth.server.signature.SignatureVerifierImpl)3 MapKeyChainImpl (com.disney.http.auth.keychain.MapKeyChainImpl)2 Key (java.security.Key)2 PrivateKey (java.security.PrivateKey)2 ArrayList (java.util.ArrayList)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 SignatureAuthorization (com.disney.http.auth.SignatureAuthorization)1 KeyStoreKeyChainImpl (com.disney.http.auth.keychain.KeyStoreKeyChainImpl)1 ServerAuthorizationRequest (com.disney.http.auth.server.ServerAuthorizationRequest)1 ServletAuthorizationRequest (com.disney.http.auth.server.ServletAuthorizationRequest)1 VerifierResult (com.disney.http.auth.server.VerifierResult)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InvalidKeyException (java.security.InvalidKeyException)1 KeyPair (java.security.KeyPair)1 KeyStore (java.security.KeyStore)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 PublicKey (java.security.PublicKey)1 SignatureException (java.security.SignatureException)1