Skip to content

Commit

Permalink
[BackPort]: Upgrade pac4j-oidc to 4.5.7 to address CVE-2021-44878 (#185)
Browse files Browse the repository at this point in the history
* Upgrade pac4j-oidc to 4.5.7 to address CVE-2021-44878 (apache#15522)

* Upgrade org.pac4j:pac4j-oidc to 4.5.5 to address CVE-2021-44878
* add CVE suppression and notes, since vulnerability scan still shows this CVE
* Add tests to improve coverage

* pac4j: fix incompatible dependencies + authorization regression (apache#15753)

- After upgrading the pac4j version in: apache#15522. We were not able to access the druid ui. 
- Upgraded the Nimbus libraries version to a compatible version to pac4j.
- In the older pac4j version, when we return RedirectAction there we also update the webcontext Response status code and add the authentication URL to the header. But in the newer pac4j version, we just simply return the RedirectAction. So that's why it was not getting redirected to the generated authentication URL.
- To fix the above, I have updated the NOOP_HTTP_ACTION_ADAPTER to JEE_HTTP_ACTION_ADAPTER and it updates the HTTP Response in context as per the HTTP Action.

---------

Co-authored-by: Keerthana Srikanth <ksrikanth@confluent.io>
  • Loading branch information
Pankaj260100 and KeerthanaSrikanth authored Feb 6, 2024
1 parent 6db7f5f commit 62d8a38
Show file tree
Hide file tree
Showing 7 changed files with 208 additions and 39 deletions.
13 changes: 9 additions & 4 deletions extensions-core/druid-pac4j/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@
</parent>

<properties>
<pac4j.version>3.8.3</pac4j.version>
<pac4j.version>4.5.7</pac4j.version>

<!-- Following must be updated along with any updates to pac4j version -->
<!-- Following must be updated along with any updates to pac4j version. One can find the compatible version of nimbus libraries in org.pac4j:pac4j-oidc dependencies-->
<nimbus.lang.tag.version>1.7</nimbus.lang.tag.version>
<nimbus.jose.jwt.version>7.9</nimbus.jose.jwt.version>
<oauth2.oidc.sdk.version>6.5</oauth2.oidc.sdk.version>
<nimbus.jose.jwt.version>8.22.1</nimbus.jose.jwt.version>
<oauth2.oidc.sdk.version>8.22</oauth2.oidc.sdk.version>
</properties>

<dependencies>
Expand Down Expand Up @@ -145,6 +145,11 @@
<artifactId>easymock</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@
import org.apache.druid.server.security.AuthConfig;
import org.apache.druid.server.security.AuthenticationResult;
import org.pac4j.core.config.Config;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.context.JEEContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.engine.CallbackLogic;
import org.pac4j.core.engine.DefaultCallbackLogic;
import org.pac4j.core.engine.DefaultSecurityLogic;
import org.pac4j.core.engine.SecurityLogic;
import org.pac4j.core.http.adapter.HttpActionAdapter;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.http.adapter.JEEHttpActionAdapter;
import org.pac4j.core.profile.UserProfile;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
Expand All @@ -47,12 +47,10 @@ public class Pac4jFilter implements Filter
{
private static final Logger LOGGER = new Logger(Pac4jFilter.class);

private static final HttpActionAdapter<String, J2EContext> NOOP_HTTP_ACTION_ADAPTER = (int code, J2EContext ctx) -> null;

private final Config pac4jConfig;
private final SecurityLogic<String, J2EContext> securityLogic;
private final CallbackLogic<String, J2EContext> callbackLogic;
private final SessionStore<J2EContext> sessionStore;
private final SecurityLogic<Object, JEEContext> securityLogic;
private final CallbackLogic<Object, JEEContext> callbackLogic;
private final SessionStore<JEEContext> sessionStore;

private final String name;
private final String authorizerName;
Expand Down Expand Up @@ -88,32 +86,34 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo

HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
J2EContext context = new J2EContext(httpServletRequest, httpServletResponse, sessionStore);
JEEContext context = new JEEContext(httpServletRequest, httpServletResponse, sessionStore);

if (Pac4jCallbackResource.SELF_URL.equals(httpServletRequest.getRequestURI())) {
callbackLogic.perform(
context,
pac4jConfig,
NOOP_HTTP_ACTION_ADAPTER,
JEEHttpActionAdapter.INSTANCE,
"/",
true, false, false, null);
} else {
String uid = securityLogic.perform(
Object uid = securityLogic.perform(
context,
pac4jConfig,
(J2EContext ctx, Collection<CommonProfile> profiles, Object... parameters) -> {
(JEEContext ctx, Collection<UserProfile> profiles, Object... parameters) -> {
if (profiles.isEmpty()) {
LOGGER.warn("No profiles found after OIDC auth.");
return null;
} else {
return profiles.iterator().next().getId();
}
},
NOOP_HTTP_ACTION_ADAPTER,
null, null, null, null);

JEEHttpActionAdapter.INSTANCE,
null, "none", null, null);
// Changed the Authorizer from null to "none".
// In the older version, if it is null, it simply grant access and returns authorized.
// But in the newer pac4j version, it uses CsrfAuthorizer as default, And because of this, It was returning 403 in API calls.
if (uid != null) {
AuthenticationResult authenticationResult = new AuthenticationResult(uid, authorizerName, name, null);
AuthenticationResult authenticationResult = new AuthenticationResult(uid.toString(), authorizerName, name, null);
servletRequest.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, authenticationResult);
filterChain.doFilter(servletRequest, servletResponse);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,20 @@
import org.apache.druid.java.util.common.logger.Logger;
import org.pac4j.core.context.ContextHelper;
import org.pac4j.core.context.Cookie;
import org.pac4j.core.context.Pac4jConstants;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.util.JavaSerializationHelper;
import org.pac4j.core.util.Pac4jConstants;

import javax.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.Optional;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

Expand Down Expand Up @@ -78,15 +79,15 @@ public String getOrCreateSessionId(WebContext context)

@Nullable
@Override
public Object get(WebContext context, String key)
public Optional<Object> get(WebContext context, String key)
{
final Cookie cookie = ContextHelper.getCookie(context, PAC4J_SESSION_PREFIX + key);
Object value = null;
if (cookie != null) {
value = uncompressDecryptBase64(cookie.getValue());
}
LOGGER.debug("Get from session: [%s] = [%s]", key, value);
return value;
return Optional.ofNullable(value);
}

@Override
Expand Down Expand Up @@ -142,7 +143,7 @@ private Serializable uncompressDecryptBase64(final String v)
if (v != null && !v.isEmpty()) {
byte[] bytes = StringUtils.decodeBase64String(v);
if (bytes != null) {
return javaSerializationHelper.unserializeFromBytes(unCompress(cryptoService.decrypt(bytes)));
return javaSerializationHelper.deserializeFromBytes(unCompress(cryptoService.decrypt(bytes)));
}
}
return null;
Expand Down Expand Up @@ -176,19 +177,19 @@ private Object clearUserProfile(final Object value)
{
if (value instanceof Map<?, ?>) {
final Map<String, CommonProfile> profiles = (Map<String, CommonProfile>) value;
profiles.forEach((name, profile) -> profile.clearSensitiveData());
profiles.forEach((name, profile) -> profile.removeLoginData());
return profiles;
} else {
final CommonProfile profile = (CommonProfile) value;
profile.clearSensitiveData();
profile.removeLoginData();
return profile;
}
}

@Override
public SessionStore buildFromTrackableSession(WebContext arg0, Object arg1)
public Optional<SessionStore<T>> buildFromTrackableSession(WebContext arg0, Object arg1)
{
return null;
return Optional.empty();
}

@Override
Expand All @@ -198,9 +199,9 @@ public boolean destroySession(WebContext arg0)
}

@Override
public Object getTrackableSession(WebContext arg0)
public Optional getTrackableSession(WebContext arg0)
{
return null;
return Optional.empty();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

package org.apache.druid.security.pac4j;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.pac4j.core.context.JEEContext;
import org.pac4j.core.exception.http.ForbiddenAction;
import org.pac4j.core.exception.http.FoundAction;
import org.pac4j.core.exception.http.HttpAction;
import org.pac4j.core.exception.http.WithLocationAction;
import org.pac4j.core.http.adapter.JEEHttpActionAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.mockito.ArgumentMatchers.any;

@RunWith(MockitoJUnitRunner.class)
public class Pac4jFilterTest
{

@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
private JEEContext context;

@Before
public void setUp()
{
context = new JEEContext(request, response);
}

@Test
public void testActionAdapterForRedirection()
{
HttpAction httpAction = new FoundAction("testUrl");
Mockito.doReturn(httpAction.getCode()).when(response).getStatus();
Mockito.doReturn(((WithLocationAction) httpAction).getLocation()).when(response).getHeader(any());
JEEHttpActionAdapter.INSTANCE.adapt(httpAction, context);
Assert.assertEquals(response.getStatus(), 302);
Assert.assertEquals(response.getHeader("Location"), "testUrl");
}

@Test
public void testActionAdapterForForbidden()
{
HttpAction httpAction = ForbiddenAction.INSTANCE;
Mockito.doReturn(httpAction.getCode()).when(response).getStatus();
JEEHttpActionAdapter.INSTANCE.adapt(httpAction, context);
Assert.assertEquals(response.getStatus(), HttpServletResponse.SC_FORBIDDEN);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,23 @@
import org.junit.Test;
import org.pac4j.core.context.Cookie;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.definition.CommonProfileDefinition;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public class Pac4jSessionStoreTest
{
private static final String COOKIE_PASSPHRASE = "test-cookie-passphrase";

@Test
public void testSetAndGet()
{
Pac4jSessionStore<WebContext> sessionStore = new Pac4jSessionStore("test-cookie-passphrase");
Pac4jSessionStore<WebContext> sessionStore = new Pac4jSessionStore(COOKIE_PASSPHRASE);

WebContext webContext1 = EasyMock.mock(WebContext.class);
EasyMock.expect(webContext1.getScheme()).andReturn("https");
Expand All @@ -54,7 +62,73 @@ public void testSetAndGet()
WebContext webContext2 = EasyMock.mock(WebContext.class);
EasyMock.expect(webContext2.getRequestCookies()).andReturn(Collections.singletonList(cookie));
EasyMock.replay(webContext2);
Assert.assertEquals("value", Objects.requireNonNull(sessionStore.get(webContext2, "key")).orElse(null));
}

@Test
public void testSetAndGetClearUserProfile()
{
Pac4jSessionStore<WebContext> sessionStore = new Pac4jSessionStore(COOKIE_PASSPHRASE);

WebContext webContext1 = EasyMock.mock(WebContext.class);
EasyMock.expect(webContext1.getScheme()).andReturn("https");
Capture<Cookie> cookieCapture = EasyMock.newCapture();

webContext1.addResponseCookie(EasyMock.capture(cookieCapture));
EasyMock.replay(webContext1);

CommonProfile profile = new CommonProfile();
profile.addAttribute(CommonProfileDefinition.DISPLAY_NAME, "name");
sessionStore.set(webContext1, "pac4jUserProfiles", profile);

Cookie cookie = cookieCapture.getValue();
Assert.assertTrue(cookie.isSecure());
Assert.assertTrue(cookie.isHttpOnly());
Assert.assertTrue(cookie.isSecure());
Assert.assertEquals(900, cookie.getMaxAge());


WebContext webContext2 = EasyMock.mock(WebContext.class);
EasyMock.expect(webContext2.getRequestCookies()).andReturn(Collections.singletonList(cookie));
EasyMock.replay(webContext2);
Optional<Object> value = sessionStore.get(webContext2, "pac4jUserProfiles");
Assert.assertTrue(Objects.requireNonNull(value).isPresent());
Assert.assertEquals("name", ((CommonProfile) value.get()).getAttribute(CommonProfileDefinition.DISPLAY_NAME));
}

@Test
public void testSetAndGetClearUserMultipleProfile()
{
Pac4jSessionStore<WebContext> sessionStore = new Pac4jSessionStore(COOKIE_PASSPHRASE);

WebContext webContext1 = EasyMock.mock(WebContext.class);
EasyMock.expect(webContext1.getScheme()).andReturn("https");
Capture<Cookie> cookieCapture = EasyMock.newCapture();

webContext1.addResponseCookie(EasyMock.capture(cookieCapture));
EasyMock.replay(webContext1);

Assert.assertEquals("value", sessionStore.get(webContext2, "key"));
CommonProfile profile1 = new CommonProfile();
profile1.addAttribute(CommonProfileDefinition.DISPLAY_NAME, "name1");
CommonProfile profile2 = new CommonProfile();
profile2.addAttribute(CommonProfileDefinition.DISPLAY_NAME, "name2");
Map<String, CommonProfile> profiles = new HashMap<>();
profiles.put("profile1", profile1);
profiles.put("profile2", profile2);
sessionStore.set(webContext1, "pac4jUserProfiles", profiles);

Cookie cookie = cookieCapture.getValue();
Assert.assertTrue(cookie.isSecure());
Assert.assertTrue(cookie.isHttpOnly());
Assert.assertTrue(cookie.isSecure());
Assert.assertEquals(900, cookie.getMaxAge());


WebContext webContext2 = EasyMock.mock(WebContext.class);
EasyMock.expect(webContext2.getRequestCookies()).andReturn(Collections.singletonList(cookie));
EasyMock.replay(webContext2);
Optional<Object> value = sessionStore.get(webContext2, "pac4jUserProfiles");
Assert.assertTrue(Objects.requireNonNull(value).isPresent());
Assert.assertEquals(2, ((Map<String, CommonProfile>) value.get()).size());
}
}
Loading

0 comments on commit 62d8a38

Please sign in to comment.