Search in sources :

Example 1 with ServletAuthorizationRequest

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

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

the class WebSocketAuthFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    if (factory == null) {
        this.factory = (GroovityScriptViewFactory) req.getServletContext().getAttribute(GroovityServlet.SERVLET_CONTEXT_GROOVITY_VIEW_FACTORY);
    }
    if (req instanceof HttpServletRequest) {
        HttpServletRequest hreq = (HttpServletRequest) req;
        HttpServletResponse hres = (HttpServletResponse) res;
        if ("websocket".equalsIgnoreCase(hreq.getHeader(UPGRADE_HEADER))) {
            String requestPath = hreq.getPathInfo();
            if (requestPath == null) {
                // when running as default servlet fall back
                requestPath = hreq.getServletPath();
            }
            String socketName = null;
            if (requestPath.startsWith("ws/")) {
                socketName = requestPath.substring(3);
            } else if (requestPath.startsWith("/ws/")) {
                socketName = requestPath.substring(4);
            }
            if (socketName != null) {
                if (log.isLoggable(Level.FINE)) {
                    log.fine("VALIDATING WEB SOCKET REQUEST for socket " + socketName + " " + hreq.getHeader("authorization"));
                }
                try {
                    GroovityScriptView gsv = factory.getSocketByName(socketName);
                    if (gsv != null) {
                        if (gsv.getVerifier() != null) {
                            VerifierResult vf = gsv.getVerifier().verify(new ServletAuthorizationRequest(hreq));
                            if (vf.getAuthenticationInfo() != null) {
                                hres.setHeader(AuthConstants.AUTHENTICATION_INFO, vf.getAuthenticationInfo());
                            }
                            if (vf.isAuthenticated()) {
                                if (vf.isAuthorized()) {
                                    if (vf.getPrincipal() != null) {
                                        hreq = new AuthenticatedRequestWrapper(hreq, vf.getPrincipal());
                                    }
                                } else {
                                    if (log.isLoggable(Level.FINE)) {
                                        log.fine("Verification failed 403 " + vf.getMessage() + ", challenge " + vf.getChallenge());
                                    }
                                    hres.sendError(403, vf.getMessage());
                                    return;
                                }
                            } else {
                                if (vf.getChallenge() != null) {
                                    hres.setHeader(AuthConstants.WWW_AUTHENTICATE_HEADER, vf.getChallenge());
                                }
                                if (log.isLoggable(Level.FINE)) {
                                    log.fine("Verification failed 401 " + vf.getMessage() + ", challenge " + vf.getChallenge());
                                }
                                hres.sendError(401, vf.getMessage());
                                return;
                            }
                            if (log.isLoggable(Level.FINE)) {
                                log.fine("Verification succeeded for " + vf.getPrincipal());
                            }
                        }
                        String origin = hreq.getHeader(ORIGIN_HEADER);
                        String host = hreq.getHeader(HOST_HEADER);
                        if (hreq.isSecure()) {
                            host = "https://".concat(host);
                        } else {
                            host = "http://".concat(host);
                        }
                        if (host.equals(origin)) {
                            // default CORS behavior, allow same-origin requests
                            if (log.isLoggable(Level.FINE)) {
                                log.fine("WebSocket Origin " + origin + " matches host " + host);
                            }
                        } else {
                            AtomicBoolean allowed = new AtomicBoolean(false);
                            CORSProcessor cp = gsv.getCORSProcessor();
                            if (cp != null) {
                                cp.process(hreq, new HttpServletResponseWrapper(hres) {

                                    public void setHeader(String name, String value) {
                                        if (ACCESS_CONTROL_ALLOW_ORIGIN.equals(name)) {
                                            allowed.set(true);
                                        }
                                        super.setHeader(name, value);
                                    }
                                });
                            }
                            if (!allowed.get()) {
                                if (log.isLoggable(Level.FINE)) {
                                    log.fine("Disallowing websocket due to cors violation from " + origin + " to host " + host);
                                }
                                hres.sendError(403, "Origin not allowed");
                                return;
                            }
                        }
                    }
                } catch (Exception e) {
                    throw new ServletException(e);
                }
            }
        }
        chain.doFilter(hreq, hres);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GroovityScriptView(com.disney.groovity.servlet.GroovityScriptView) VerifierResult(com.disney.http.auth.server.VerifierResult) AuthenticatedRequestWrapper(com.disney.http.auth.server.AuthenticatedRequestWrapper) ServletAuthorizationRequest(com.disney.http.auth.server.ServletAuthorizationRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) CORSProcessor(com.disney.groovity.servlet.cors.CORSProcessor) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 3 with ServletAuthorizationRequest

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

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

ServletAuthorizationRequest (com.disney.http.auth.server.ServletAuthorizationRequest)4 VerifierResult (com.disney.http.auth.server.VerifierResult)4 ServerAuthorizationRequest (com.disney.http.auth.server.ServerAuthorizationRequest)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 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 GroovityScriptView (com.disney.groovity.servlet.GroovityScriptView)1 CORSProcessor (com.disney.groovity.servlet.cors.CORSProcessor)1 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 AuthenticatedRequestWrapper (com.disney.http.auth.server.AuthenticatedRequestWrapper)1 BasicVerifierImpl (com.disney.http.auth.server.basic.BasicVerifierImpl)1 MapPasswordChecker (com.disney.http.auth.server.basic.MapPasswordChecker)1 PasswordChecker (com.disney.http.auth.server.basic.PasswordChecker)1 DigestVerifierImpl (com.disney.http.auth.server.digest.DigestVerifierImpl)1