Search in sources :

Example 1 with ServerAuthorizationRequest

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

the class VerifierFactory method createVerifier.

@SuppressWarnings("rawtypes")
public Verifier createVerifier(List auths, Class<Script> scriptClass) throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException, URISyntaxException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {
    ArrayList<Verifier> verifiers = new ArrayList<Verifier>(auths.size());
    for (Object auth : auths) {
        if (auth instanceof Map) {
            Map conf = (Map) auth;
            Object policy = conf.get("policy");
            if (policy != null) {
                verifiers.add(processPolicy(conf, scriptClass));
            } else {
                String type = (String) conf.get("type");
                if ("signature".equals(type)) {
                    verifiers.add(processSignature(conf, scriptClass));
                } else if ("basic".equals(type)) {
                    verifiers.add(processBasic(conf, scriptClass));
                } else if ("digest".equals(type)) {
                    verifiers.add(processDigest(conf, scriptClass));
                } else {
                    throw new IllegalArgumentException("Unkown auth type: " + type);
                }
            }
        } else if (auth instanceof CharSequence) {
            verifiers.add((Verifier) fallbackConstruct(auth, scriptClass));
        } else if (auth instanceof Closure) {
            verifiers.add(new Verifier() {

                @Override
                public VerifierResult verify(ServerAuthorizationRequest request) throws Exception {
                    Object result = ((Closure) auth).call(request);
                    if (!(result instanceof VerifierResult)) {
                        result = DefaultTypeTransformation.castToType(result, VerifierResult.class);
                    }
                    return (VerifierResult) result;
                }
            });
        }
    }
    return new VerifierChain(verifiers);
}
Also used : Closure(groovy.lang.Closure) VerifierChain(com.disney.http.auth.server.VerifierChain) ArrayList(java.util.ArrayList) AbstractVerifier(com.disney.http.auth.server.AbstractVerifier) Verifier(com.disney.http.auth.server.Verifier) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) VerifierResult(com.disney.http.auth.server.VerifierResult) Map(java.util.Map) HashMap(java.util.HashMap) ServerAuthorizationRequest(com.disney.http.auth.server.ServerAuthorizationRequest)

Example 2 with ServerAuthorizationRequest

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

the class TestDigestAuth method testDigest.

@Test
public void testDigest() throws Exception {
    DigestVerifierImpl verifier = new DigestVerifierImpl();
    Map<String, String> pmap = new HashMap<String, String>();
    List<String> accessList = new ArrayList<String>();
    ACLAccessControllerImpl acl = new ACLAccessControllerImpl();
    acl.setAcl(accessList);
    pmap.put("mykey", "mypass");
    PasswordDigester pc = new MapPasswordDigester(pmap);
    verifier.setPasswordDigesters(Arrays.asList(pc));
    verifier.setAccessControllers(Arrays.asList((AccessController) acl));
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/");
    ServerAuthorizationRequest areq = new ServletAuthorizationRequest(request);
    VerifierResult result = verifier.verify(areq);
    Assert.assertEquals(ERROR_MISSING_CREDENTIALS, result.getMessage());
    String challenge = result.getChallenge();
    Pattern noncePattern = Pattern.compile("nonce=\"([^\"]+)\"");
    Matcher matcher = noncePattern.matcher(challenge);
    if (!matcher.find()) {
        throw new Exception("No nonce found in challenge");
    }
    String nonce = matcher.group(1);
    Pattern opaquePattern = Pattern.compile("opaque=\"([^\"]+)\"");
    matcher = opaquePattern.matcher(challenge);
    if (!matcher.find()) {
        throw new Exception("No opaque found in challenge");
    }
    String opaque = matcher.group(1);
    DigestAuthorization ad = new DigestAuthorization();
    ad.setNonce(nonce);
    ad.setCnonce("ClientNonce");
    ad.setNonceCount("000001");
    ad.setOpaque(opaque);
    ad.setQop("auth");
    ad.setUri("/");
    ad.setUsername("mykey");
    ad.setDigest(new byte[0]);
    ad.setRealm(verifier.getRealm());
    request.addHeader("Authorization", ad.toString());
    result = verifier.verify(areq);
    Assert.assertEquals(ERROR_UNKNOWN_CREDENTIALS, result.getMessage());
    // now fix the digest
    /*
		StringBuilder signingString = new StringBuilder();
		signingString.append(digest("mykey",verifier.getRealm(),"mypass"));
		signingString.append(":").append(nonce).append(":").append(ad.getNonceCount()).append(":").append(ad.getCnonce()).append(":auth:");
		signingString.append(digest("GET",ad.getUri()));
		*/
    request = new MockHttpServletRequest();
    areq = new ServletAuthorizationRequest(request);
    request.setMethod("GET");
    request.setRequestURI("/");
    String signingString = ad.generateSigningString("mykey", "mypass", new ServletAuthorizationRequest(request));
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    ad.setDigest(md5.digest(signingString.toString().getBytes()));
    request.addHeader("Authorization", ad.toString());
    result = verifier.verify(areq);
    Assert.assertTrue("Expected successful authentication", result.isAuthenticated());
    Assert.assertFalse("Expected failed authorization", result.isAuthorized());
    accessList.add("mykey");
    result = verifier.verify(areq);
    Assert.assertTrue("Expected successful authentication", result.isAuthenticated());
    Assert.assertTrue("Expected successful authorization", result.isAuthorized());
}
Also used : DigestAuthorization(com.disney.http.auth.DigestAuthorization) Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) MapPasswordDigester(com.disney.http.auth.server.digest.MapPasswordDigester) PasswordDigester(com.disney.http.auth.server.digest.PasswordDigester) Matcher(java.util.regex.Matcher) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ArrayList(java.util.ArrayList) ServletAuthorizationRequest(com.disney.http.auth.server.ServletAuthorizationRequest) MapPasswordDigester(com.disney.http.auth.server.digest.MapPasswordDigester) AccessController(com.disney.http.auth.server.AccessController) VerifierResult(com.disney.http.auth.server.VerifierResult) MessageDigest(java.security.MessageDigest) ACLAccessControllerImpl(com.disney.http.auth.server.ACLAccessControllerImpl) DigestVerifierImpl(com.disney.http.auth.server.digest.DigestVerifierImpl) ServerAuthorizationRequest(com.disney.http.auth.server.ServerAuthorizationRequest) Test(org.junit.Test)

Example 3 with ServerAuthorizationRequest

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

the class TestBasicAuth method testBasic.

@Test
public void testBasic() throws Exception {
    BasicVerifierImpl verifier = new BasicVerifierImpl();
    Map<String, String> pmap = new HashMap<String, String>();
    List<String> accessList = new ArrayList<String>();
    ACLAccessControllerImpl acl = new ACLAccessControllerImpl();
    acl.setAcl(accessList);
    pmap.put("mykey", "mypass");
    PasswordChecker pc = new MapPasswordChecker(pmap);
    verifier.setPasswordCheckers(Arrays.asList(pc));
    verifier.setAccessControllers(Arrays.asList((AccessController) acl));
    MockHttpServletRequest request = new MockHttpServletRequest();
    ServerAuthorizationRequest areq = new ServletAuthorizationRequest(request);
    VerifierResult result = verifier.verify(areq);
    Assert.assertEquals(ERROR_MISSING_CREDENTIALS, result.getMessage());
    request.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary("mykey:wrongpass".getBytes()));
    result = verifier.verify(areq);
    Assert.assertEquals(ERROR_UNKNOWN_CREDENTIALS, result.getMessage());
    request = new MockHttpServletRequest();
    request.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary("mykey:mypass".getBytes()));
    areq = new ServletAuthorizationRequest(request);
    result = verifier.verify(areq);
    Assert.assertTrue("Expected successful authentication", result.isAuthenticated());
    Assert.assertFalse("Expected failed authorization", result.isAuthorized());
    accessList.add("mykey");
    result = verifier.verify(areq);
    Assert.assertTrue("Expected successful authentication", result.isAuthenticated());
    Assert.assertTrue("Expected successful authorization", result.isAuthorized());
}
Also used : HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) ArrayList(java.util.ArrayList) ServletAuthorizationRequest(com.disney.http.auth.server.ServletAuthorizationRequest) PasswordChecker(com.disney.http.auth.server.basic.PasswordChecker) MapPasswordChecker(com.disney.http.auth.server.basic.MapPasswordChecker) AccessController(com.disney.http.auth.server.AccessController) VerifierResult(com.disney.http.auth.server.VerifierResult) ACLAccessControllerImpl(com.disney.http.auth.server.ACLAccessControllerImpl) MapPasswordChecker(com.disney.http.auth.server.basic.MapPasswordChecker) ServerAuthorizationRequest(com.disney.http.auth.server.ServerAuthorizationRequest) BasicVerifierImpl(com.disney.http.auth.server.basic.BasicVerifierImpl) Test(org.junit.Test)

Example 4 with ServerAuthorizationRequest

use of com.disney.http.auth.server.ServerAuthorizationRequest 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

ServerAuthorizationRequest (com.disney.http.auth.server.ServerAuthorizationRequest)4 VerifierResult (com.disney.http.auth.server.VerifierResult)4 ServletAuthorizationRequest (com.disney.http.auth.server.ServletAuthorizationRequest)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 ACLAccessControllerImpl (com.disney.http.auth.server.ACLAccessControllerImpl)2 AccessController (com.disney.http.auth.server.AccessController)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 DigestAuthorization (com.disney.http.auth.DigestAuthorization)1 SignatureAuthorization (com.disney.http.auth.SignatureAuthorization)1 KeyChain (com.disney.http.auth.keychain.KeyChain)1 KeyStoreKeyChainImpl (com.disney.http.auth.keychain.KeyStoreKeyChainImpl)1 AbstractVerifier (com.disney.http.auth.server.AbstractVerifier)1 Verifier (com.disney.http.auth.server.Verifier)1 VerifierChain (com.disney.http.auth.server.VerifierChain)1 BasicVerifierImpl (com.disney.http.auth.server.basic.BasicVerifierImpl)1 MapPasswordChecker (com.disney.http.auth.server.basic.MapPasswordChecker)1