Skip to content

Commit d4cee91

Browse files
author
Ramgopal Nagaboina
committed
oauth2: add OIDC nonce and a per-attempt CSRF state
Binds the generic OIDC login to the authorization request: - the UI generates a random nonce and state per attempt, sends the nonce in the authorization request, and rejects the callback when the returned state does not match before the code is exchanged - the id_token nonce claim is verified against the nonce from the request (generic OIDC only; the built-in providers ignore it) Follow-up to apache#14205.
1 parent af7f0ce commit d4cee91

10 files changed

Lines changed: 112 additions & 8 deletions

File tree

‎api/src/main/java/org/apache/cloudstack/api/ApiConstants.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,7 @@ public class ApiConstants {
442442
public static final String NEW_NAME = "newname";
443443
public static final String NIC = "nic";
444444
public static final String NICS = "nics";
445+
public static final String NONCE = "nonce";
445446
public static final String NIC_NETWORK_LIST = "nicnetworklist";
446447
public static final String NIC_NETWORKS_LIST = "nicnetworkslist";
447448
public static final String NIC_IP_ADDRESS_LIST = "nicipaddresslist";

‎api/src/main/java/org/apache/cloudstack/auth/UserOAuth2Authenticator.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,16 @@ default String verifySecretCodeAndFetchEmail(String secretCode, Long domainId, S
7474
return verifySecretCodeAndFetchEmail(secretCode, domainId);
7575
}
7676

77+
/**
78+
* Verifies the secret code against the registration identified by providerName and fetches email,
79+
* additionally binding the id_token to the nonce sent in the authorization request. Implementations
80+
* that do not support a nonce ignore it.
81+
* @return email for the specified registration
82+
*/
83+
default String verifySecretCodeAndFetchEmail(String secretCode, Long domainId, String providerName, String nonce) {
84+
return verifySecretCodeAndFetchEmail(secretCode, domainId, providerName);
85+
}
86+
7787
/**
7888
* Fetches email using the accessToken
7989
* @return returns email

‎plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManager.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ public interface OAuth2AuthManager extends PluggableAPIAuthenticator, PluggableS
6767

6868
String verifySecretCodeAndFetchEmail(String code, String provider, Long domainId);
6969

70+
String verifySecretCodeAndFetchEmail(String code, String provider, Long domainId, String nonce);
71+
7072
OauthProviderVO registerOauthProvider(RegisterOAuthProviderCmd cmd);
7173

7274
List<OauthProviderVO> listOauthProviders(String provider, String uuid, Long domainId);

‎plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/OAuth2AuthManagerImpl.java‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,13 @@ protected void initializeUserOAuth2AuthenticationProvidersMap() {
169169

170170
@Override
171171
public String verifySecretCodeAndFetchEmail(String code, String provider, Long domainId) {
172-
UserOAuth2Authenticator authenticator = getUserOAuth2AuthenticationProvider(provider, domainId);
173-
String email = authenticator.verifySecretCodeAndFetchEmail(code, domainId, provider);
172+
return verifySecretCodeAndFetchEmail(code, provider, domainId, null);
173+
}
174174

175-
return email;
175+
@Override
176+
public String verifySecretCodeAndFetchEmail(String code, String provider, Long domainId, String nonce) {
177+
UserOAuth2Authenticator authenticator = getUserOAuth2AuthenticationProvider(provider, domainId);
178+
return authenticator.verifySecretCodeAndFetchEmail(code, domainId, provider, nonce);
176179
}
177180

178181
@Override

‎plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/api/command/VerifyOAuthCodeAndGetUserCmd.java‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,10 @@ public class VerifyOAuthCodeAndGetUserCmd extends BaseListCmd implements APIAuth
6767
description = "Domain path for domain-specific OAuth provider lookup. Ignored when Domain ID is passed.", since = "4.23.0")
6868
private String domainPath;
6969

70+
@Parameter(name = ApiConstants.NONCE, type = CommandType.STRING,
71+
description = "Nonce sent in the authorization request, verified against the id_token for OpenID Connect providers", since = "24.0.0")
72+
private String nonce;
73+
7074
/////////////////////////////////////////////////////
7175
/////////////////// Accessors ///////////////////////
7276
/////////////////////////////////////////////////////
@@ -110,9 +114,13 @@ public String authenticate(String command, Map<String, Object[]> params, HttpSes
110114
if (ArrayUtils.isNotEmpty(providerArray)) {
111115
provider = providerArray[0];
112116
}
117+
final String[] nonceArray = (String[])params.get(ApiConstants.NONCE);
118+
if (ArrayUtils.isNotEmpty(nonceArray)) {
119+
nonce = nonceArray[0];
120+
}
113121
domainId = _oauth2mgr.resolveDomainId(params);
114122

115-
String email = _oauth2mgr.verifySecretCodeAndFetchEmail(secretCode, provider, domainId);
123+
String email = _oauth2mgr.verifySecretCodeAndFetchEmail(secretCode, provider, domainId, nonce);
116124
if (email != null) {
117125
UserResponse response = new UserResponse();
118126
response.setEmail(email);

‎plugins/user-authenticators/oauth2/src/main/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2Provider.java‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,17 +166,26 @@ public boolean verifyUser(String email, String secretCode, Long domainId, String
166166

167167
@Override
168168
public String verifySecretCodeAndFetchEmail(String secretCode, Long domainId, String providerName) {
169-
String email = resolveEmail(secretCode, domainId, providerName);
169+
return verifySecretCodeAndFetchEmail(secretCode, domainId, providerName, null);
170+
}
171+
172+
@Override
173+
public String verifySecretCodeAndFetchEmail(String secretCode, Long domainId, String providerName, String nonce) {
174+
String email = resolveEmail(secretCode, domainId, providerName, nonce);
170175
verifiedEmailCache.put(verifiedEmailKey(providerName, secretCode, domainId), email);
171176
return email;
172177
}
173178

174179
protected String resolveEmail(String secretCode, Long domainId, String providerName) {
180+
return resolveEmail(secretCode, domainId, providerName, null);
181+
}
182+
183+
protected String resolveEmail(String secretCode, Long domainId, String providerName, String nonce) {
175184
OauthProviderVO provider = findRegistration(providerName, domainId);
176185
OIDCMetadata metadata = getMetadata(provider);
177186
String idToken = exchangeAuthorizationCode(secretCode, provider, metadata);
178187

179-
return validateAndExtractEmail(idToken, provider, metadata);
188+
return validateAndExtractEmail(idToken, provider, metadata, nonce);
180189
}
181190

182191
@Override
@@ -262,6 +271,10 @@ protected String exchangeAuthorizationCode(String secretCode, OauthProviderVO pr
262271
}
263272

264273
protected String validateAndExtractEmail(String idToken, OauthProviderVO provider, OIDCMetadata metadata) {
274+
return validateAndExtractEmail(idToken, provider, metadata, null);
275+
}
276+
277+
protected String validateAndExtractEmail(String idToken, OauthProviderVO provider, OIDCMetadata metadata, String nonce) {
265278
JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(idToken);
266279

267280
verifySignature(consumer, metadata, provider);
@@ -275,6 +288,10 @@ protected String validateAndExtractEmail(String idToken, OauthProviderVO provide
275288
}
276289
JwtUtils.validateJwtExpiry(claims, CLOCK_SKEW_SECONDS, true);
277290

291+
if (StringUtils.isNotBlank(nonce) && !nonce.equals(claims.getClaim("nonce"))) {
292+
throw new CloudAuthenticationException("The id_token nonce does not match the login request");
293+
}
294+
278295
String email = (String) claims.getClaim("email");
279296
if (StringUtils.isBlank(email)) {
280297
throw new CloudAuthenticationException("The id_token carries no email claim");

‎plugins/user-authenticators/oauth2/src/test/java/org/apache/cloudstack/oauth2/oidc/GenericOIDCOAuth2ProviderTest.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,38 @@ public void testUnverifiedEmailIsRejected() throws Exception {
264264
provider.validateAndExtractEmail(token, registration, metadata());
265265
}
266266

267+
@Test
268+
public void testMatchingNonceIsAccepted() throws Exception {
269+
KeyPair keys = rsaKeyPair();
270+
publishKey(keys, "key-1");
271+
272+
assertEquals("user@example.com",
273+
provider.validateAndExtractEmail(signedTokenWithNonce(keys, "n-123"), registration, metadata(), "n-123"));
274+
}
275+
276+
@Test(expected = CloudAuthenticationException.class)
277+
public void testMismatchedNonceIsRejected() throws Exception {
278+
KeyPair keys = rsaKeyPair();
279+
publishKey(keys, "key-1");
280+
281+
provider.validateAndExtractEmail(signedTokenWithNonce(keys, "n-123"), registration, metadata(), "different");
282+
}
283+
284+
private String signedTokenWithNonce(KeyPair keys, String nonce) {
285+
JwtClaims claims = new JwtClaims();
286+
claims.setIssuer(ISSUER);
287+
claims.setAudiences(Collections.singletonList(CLIENT_ID));
288+
claims.setSubject("12345");
289+
claims.setExpiryTime(System.currentTimeMillis() / 1000L + 3600);
290+
claims.setClaim("email", "user@example.com");
291+
claims.setClaim("email_verified", true);
292+
claims.setClaim("nonce", nonce);
293+
JwsHeaders headers = new JwsHeaders(SignatureAlgorithm.RS256);
294+
headers.setKeyId("key-1");
295+
return new JwsJwtCompactProducer(headers, claims)
296+
.signWith(JwsUtils.getPrivateKeySignatureProvider(keys.getPrivate(), SignatureAlgorithm.RS256));
297+
}
298+
267299
@Test(expected = CloudAuthenticationException.class)
268300
public void testTokenWithAlteredClaimsIsRejected() throws Exception {
269301
KeyPair keys = rsaKeyPair();

‎ui/src/permission.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,16 @@ router.beforeEach((to, from, next) => {
177177
currentURL = new URL(window.location.href)
178178
urlParams = new URLSearchParams(currentURL.search)
179179
code = urlParams.get('code')
180+
const returnedOauthState = urlParams.get('state')
181+
let expectedOauthState = null
182+
try { expectedOauthState = sessionStorage.getItem('oauthState') } catch (ignored) { /* sessionStorage may be unavailable */ }
183+
if (expectedOauthState) {
184+
try { sessionStorage.removeItem('oauthState') } catch (ignored) { /* sessionStorage may be unavailable */ }
185+
if (returnedOauthState !== expectedOauthState) {
186+
next({ path: '/user/login' })
187+
return
188+
}
189+
}
180190
urlParams.delete('verifyOauth')
181191
urlParams.delete('state')
182192
currentURL.search = '?code=' + code

‎ui/src/views/auth/Login.vue‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -522,17 +522,29 @@ export default {
522522
this.handleDomain()
523523
this.$store.commit('SET_OAUTH_PROVIDER_USED_TO_LOGIN', 'keycloak')
524524
},
525+
randomToken () {
526+
const bytes = new Uint8Array(16)
527+
window.crypto.getRandomValues(bytes)
528+
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
529+
},
525530
loginWithGenericOidc (provider) {
526531
this.handleDomain()
527532
this.$store.commit('SET_OAUTH_PROVIDER_USED_TO_LOGIN', provider.provider)
528533
const discoveryUrl = provider.issuerurl.replace(/\/$/, '') + '/.well-known/openid-configuration'
529534
return fetch(discoveryUrl).then(response => response.json()).then(config => {
535+
const state = this.randomToken()
536+
const nonce = this.randomToken()
537+
try {
538+
sessionStorage.setItem('oauthState', state)
539+
sessionStorage.setItem('oauthNonce', nonce)
540+
} catch (ignored) { /* sessionStorage may be unavailable */ }
530541
const options = {
531542
client_id: provider.clientid,
532543
redirect_uri: provider.redirecturi,
533544
response_type: 'code',
534545
scope: 'openid email',
535-
state: this.from || 'cloudstack'
546+
state: state,
547+
nonce: nonce
536548
}
537549
window.location.href = `${config.authorization_endpoint}?${new URLSearchParams(options).toString()}`
538550
}).catch(() => {

‎ui/src/views/dashboard/VerifyOauth.vue‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,17 @@ export default {
4646
const params = new URLSearchParams(window.location.search)
4747
const code = params.get('code')
4848
const provider = this.$localStorage.get(OAUTH_PROVIDER)
49+
let nonce = null
50+
try {
51+
nonce = sessionStorage.getItem('oauthNonce')
52+
sessionStorage.removeItem('oauthNonce')
53+
} catch (ignored) { /* sessionStorage may be unavailable */ }
4954
this.state.loginBtn = true
50-
getAPI('verifyOAuthCodeAndGetUser', { provider: provider, secretcode: code, domain: this.$localStorage.get(OAUTH_DOMAIN) }).then(response => {
55+
const verifyParams = { provider: provider, secretcode: code, domain: this.$localStorage.get(OAUTH_DOMAIN) }
56+
if (nonce) {
57+
verifyParams.nonce = nonce
58+
}
59+
getAPI('verifyOAuthCodeAndGetUser', verifyParams).then(response => {
5160
const email = response.verifyoauthcodeandgetuserresponse.oauthemail.email
5261
const loginParams = {}
5362
loginParams.email = email

0 commit comments

Comments
 (0)