use of com.tremolosecurity.idp.providers.oidc.model.OidcSessionState in project OpenUnison by TremoloSecurity.
the class ClientCredentialsGrantPostAuth method runAfterSuccessfulAuthentication.
@Override
public void runAfterSuccessfulAuthentication(HttpServletRequest req, HttpServletResponse resp, UrlHolder holder, AuthChainType act, RequestHolder reqHolder, AuthController actl, NextSys next) throws IOException, ServletException {
HttpSession session = req.getSession();
AuthInfo authData = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
if (!azSys.checkRules(authData, GlobalEntries.getGlobalEntries().getConfigManager(), trust.getClientAzRules(), new HashMap<String, Object>())) {
AccessLog.log(AccessEvent.AzFail, holder.getApp(), req, authData, new StringBuilder().append("client not authorized for client_credentials grant on trust '").append(trust.getClientID()).append("'").toString());
resp.sendError(403);
return;
}
JSONObject existingClaims = new JSONObject();
for (String attrName : authData.getAttribs().keySet()) {
Attribute attr = authData.getAttribs().get(attrName);
if (attr.getValues().size() == 1) {
existingClaims.put(attrName, attr.getValues().get(0));
} else {
JSONArray vals = new JSONArray();
vals.addAll(attr.getValues());
existingClaims.put(attrName, vals);
}
}
OpenIDConnectAccessToken access = new OpenIDConnectAccessToken();
OidcSessionState oidcSession = idp.createUserSession(req, trust.getClientID(), holder, trust, authData.getUserDN(), GlobalEntries.getGlobalEntries().getConfigManager(), access, UUID.randomUUID().toString(), authData.getAuthChain(), existingClaims, null);
Gson gson = new Gson();
String json = gson.toJson(access);
resp.setContentType("application/json");
resp.getOutputStream().write(json.getBytes("UTF-8"));
resp.getOutputStream().flush();
if (logger.isDebugEnabled()) {
logger.debug("Token JSON : '" + json + "'");
}
AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), req, authData, "");
}
use of com.tremolosecurity.idp.providers.oidc.model.OidcSessionState in project OpenUnison by TremoloSecurity.
the class K8sSessionStore method getSession.
@Override
public OidcSessionState getSession(String sessionId) throws Exception {
String sessionIdName = new StringBuilder().append("x").append(sessionId).append("x").toString();
OpenShiftTarget k8s = null;
try {
k8s = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.k8sTarget).getProvider();
} catch (ProvisioningException e1) {
logger.error("Could not retrieve kubernetes target", e1);
throw new ProvisioningException("Could not connect to kubernetes", e1);
}
String url = new StringBuilder().append("/apis/openunison.tremolo.io/v1/namespaces/").append(this.nameSpace).append("/oidc-sessions/").append(sessionIdName).toString();
try {
HttpCon con = k8s.createClient();
try {
String jsonResp = k8s.callWS(k8s.getAuthToken(), con, url);
if (logger.isDebugEnabled()) {
logger.debug("json response from deleting object : " + jsonResp);
}
Map ret = gson.fromJson(jsonResp, Map.class);
Map spec = (Map) ret.get("spec");
if (spec == null) {
return null;
}
OidcSessionState session = new OidcSessionState();
session.setSessionID(spec.get("session_id").toString());
session.setClientID(spec.get("client_id").toString());
session.setEncryptedAccessToken(spec.get("encrypted_access_token").toString());
session.setEncryptedIdToken(spec.get("encrypted_id_token").toString());
session.setRefreshToken(spec.get("refresh_token").toString());
session.setUserDN(spec.get("user_dn").toString());
session.setExpires(ISODateTimeFormat.dateTime().parseDateTime(spec.get("expires").toString()));
return session;
} finally {
con.getHttp().close();
con.getBcm().close();
}
} catch (Exception e) {
logger.error("Could not search k8s", e);
throw new Exception("Error searching kubernetes", e);
}
}
use of com.tremolosecurity.idp.providers.oidc.model.OidcSessionState in project OpenUnison by TremoloSecurity.
the class TokenData method processUserInfoRequest.
private void processUserInfoRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
AuthController ac = (AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL);
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
holder.getApp().getCookieConfig().getTimeout();
String header = request.getHeader("Authorization");
if (header == null) {
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(), "NONE");
response.sendError(401);
return;
}
String accessToken = header.substring("Bearer ".length());
OidcSessionState dbSession = this.getSessionByAccessToken(accessToken);
if (dbSession == null) {
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(), "NONE");
response.sendError(401);
return;
}
OpenIDConnectTrust trust = trusts.get(dbSession.getClientID());
JsonWebSignature jws = new JsonWebSignature();
jws.setCompactSerialization(this.decryptToken(this.trusts.get(dbSession.getClientID()).getCodeLastmileKeyName(), new Gson(), dbSession.getEncryptedIdToken()));
jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName).getPublicKey());
if (!jws.verifySignature()) {
logger.warn("id_token tampered with");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, ac.getAuthInfo(), "NONE");
response.sendError(401);
return;
}
JwtClaims claims = JwtClaims.parse(jws.getPayload());
response.setContentType("application/jwt");
String jwt = null;
if (trust.isSignedUserInfo()) {
jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
jwt = jws.getCompactSerialization();
} else {
jwt = claims.toJson();
}
response.getOutputStream().write(jwt.getBytes("UTF-8"));
AuthInfo remUser = new AuthInfo();
remUser.setUserDN(dbSession.getUserDN());
AccessLog.log(AccessEvent.AuSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
}
use of com.tremolosecurity.idp.providers.oidc.model.OidcSessionState in project OpenUnison by TremoloSecurity.
the class TokenData method refreshToken.
private void refreshToken(HttpServletResponse response, String clientID, String clientSecret, String refreshToken, UrlHolder holder, HttpServletRequest request, AuthInfo authData) throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException, JoseException, InvalidJwtException, UnsupportedEncodingException {
Gson gson = new Gson();
String json = this.inflate(refreshToken);
Token token = gson.fromJson(json, Token.class);
byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());
IvParameterSpec spec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(this.trusts.get(clientID).getCodeLastmileKeyName()), spec);
byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
String decryptedRefreshToken = new String(cipher.doFinal(encBytes));
OidcSessionState session = this.getSessionByRefreshToken(decryptedRefreshToken);
if (session == null) {
logger.warn("Session does not exist from refresh_token");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
response.sendError(401);
return;
}
if (!session.getRefreshToken().equals(refreshToken)) {
logger.warn("Session does not exist from refresh_token");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
response.sendError(401);
return;
}
OpenIDConnectTrust trust = this.trusts.get(session.getClientID());
if (!trust.isPublicEndpoint()) {
if (!trust.getClientSecret().equals(clientSecret)) {
logger.warn("Invalid client_secret");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
response.sendError(401);
return;
}
}
if (session.getExpires().isBeforeNow()) {
logger.warn("Session expired");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
response.sendError(401);
this.sessionStore.deleteSession(session.getSessionID());
return;
}
JsonWebSignature jws = new JsonWebSignature();
jws.setCompactSerialization(this.decryptToken(this.trusts.get(session.getClientID()).getCodeLastmileKeyName(), gson, session.getEncryptedIdToken()));
jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName).getPublicKey());
if (!jws.verifySignature()) {
logger.warn("id_token tampered with");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
response.sendError(401);
return;
}
JwtClaims claims = JwtClaims.parse(jws.getPayload());
// a unique identifier for the token
claims.setGeneratedJwtId();
// when the token was issued/created (now)
claims.setIssuedAtToNow();
// time before which the token is not yet valid (2 minutes ago)
claims.setNotBeforeMinutesInThePast(trusts.get(clientID).getAccessTokenSkewMillis() / 1000 / 60);
// time when the token will expire (10 minutes from now)
claims.setExpirationTimeMinutesInTheFuture(trusts.get(clientID).getAccessTokenTimeToLive() / 1000 / 60);
jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
String newIdToken = jws.getCompactSerialization();
session.setEncryptedIdToken(this.encryptToken(this.trusts.get(session.getClientID()).getCodeLastmileKeyName(), gson, newIdToken));
jws = new JsonWebSignature();
jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName).getPublicKey());
jws.setCompactSerialization(this.decryptToken(this.trusts.get(session.getClientID()).getCodeLastmileKeyName(), gson, session.getEncryptedAccessToken()));
if (!jws.verifySignature()) {
logger.warn("access_token tampered with");
AccessLog.log(AccessEvent.AzFail, holder.getApp(), (HttpServletRequest) request, authData, "NONE");
response.sendError(401);
return;
}
claims = JwtClaims.parse(jws.getPayload());
// a unique identifier for the token
claims.setGeneratedJwtId();
// when the token was issued/created (now)
claims.setIssuedAtToNow();
// time before which the token is not yet valid (2 minutes ago)
claims.setNotBeforeMinutesInThePast(trusts.get(clientID).getAccessTokenSkewMillis() / 1000 / 60);
// time when the token will expire (10 minutes from now)
claims.setExpirationTimeMinutesInTheFuture(trusts.get(clientID).getAccessTokenTimeToLive() / 1000 / 60);
jws = new JsonWebSignature();
jws.setPayload(claims.toJson());
jws.setKey(GlobalEntries.getGlobalEntries().getConfigManager().getPrivateKey(this.jwtSigningKeyName));
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
jws.setKeyIdHeaderValue(this.buildKID(GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(this.jwtSigningKeyName)));
String newAccessToken = jws.getCompactSerialization();
session.setEncryptedAccessToken(this.encryptToken(trust.getCodeLastmileKeyName(), gson, newAccessToken));
String b64 = encryptToken(trusts.get(clientID).getCodeLastmileKeyName(), gson, session.getSessionID());
session.setRefreshToken(b64);
session.setExpires(new DateTime().plusSeconds(holder.getApp().getCookieConfig().getTimeout()));
this.sessionStore.resetSession(session);
OpenIDConnectAccessToken access = new OpenIDConnectAccessToken();
access.setAccess_token(newAccessToken);
access.setExpires_in((int) (trusts.get(clientID).getAccessTokenTimeToLive() / 1000));
access.setId_token(newIdToken);
access.setToken_type("Bearer");
access.setRefresh_token(session.getRefreshToken());
json = gson.toJson(access);
response.setContentType("text/json");
response.getOutputStream().write(json.getBytes());
response.getOutputStream().flush();
AuthInfo remUser = new AuthInfo();
remUser.setUserDN(session.getUserDN());
AccessLog.log(AccessEvent.AzSuccess, holder.getApp(), (HttpServletRequest) request, remUser, "NONE");
}
use of com.tremolosecurity.idp.providers.oidc.model.OidcSessionState in project OpenUnison by TremoloSecurity.
the class TokenData method storeSession.
public OidcSessionState storeSession(OpenIDConnectAccessToken access, ApplicationType app, String codeTokenKeyName, String clientID, String userDN, String sessionID) throws Exception {
Gson gson = new Gson();
OidcSessionState sessionState = new OidcSessionState();
sessionState.setSessionID(sessionID);
sessionState.setEncryptedIdToken(encryptToken(codeTokenKeyName, gson, access.getId_token()));
sessionState.setEncryptedAccessToken(encryptToken(codeTokenKeyName, gson, access.getAccess_token()));
sessionState.setExpires(new DateTime().plusSeconds(app.getCookieConfig().getTimeout()));
sessionState.setUserDN(userDN);
sessionState.setRefreshToken(this.encryptToken(codeTokenKeyName, gson, sessionID));
sessionState.setClientID(clientID);
this.sessionStore.saveUserSession(sessionState);
return sessionState;
}
Aggregations