use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class OAuth2JWT method processToken.
@Override
public void processToken(HttpServletRequest request, HttpServletResponse response, AuthStep as, HttpSession session, HashMap<String, Attribute> authParams, AuthChainType act, String realmName, String scope, ConfigManager cfg, String lmToken) throws ServletException, IOException {
String issuer = authParams.get("issuer").getValues().get(0);
HashSet<String> audiences = new HashSet<String>();
if (authParams.get("audience") == null) {
logger.warn("No audience configuration, all requests will fail");
} else {
audiences.addAll(authParams.get("audience").getValues());
}
String fromWellKnown = authParams.get("fromWellKnown") != null ? authParams.get("fromWellKnown").getValues().get(0) : "false";
boolean useWellKnown = fromWellKnown.equalsIgnoreCase("true");
PublicKey pk = null;
if (useWellKnown) {
pk = keyCache.get(issuer);
if (pk == null) {
StringBuilder sb = new StringBuilder();
sb.append(issuer);
if (!issuer.endsWith("/")) {
sb.append("/");
}
sb.append(".well-known/openid-configuration");
String wellKnownURL = sb.toString();
HttpCon http = null;
try {
http = this.createClient();
HttpGet get = new HttpGet(wellKnownURL);
CloseableHttpResponse resp = http.getHttp().execute(get);
String json = EntityUtils.toString(resp.getEntity());
resp.close();
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(json);
String jwksUrl = (String) root.get("jwks_uri");
get = new HttpGet(jwksUrl);
resp = http.getHttp().execute(get);
json = EntityUtils.toString(resp.getEntity());
resp.close();
JsonWebKey jwk = null;
JsonWebKeySet jks = new JsonWebKeySet(json);
if (jks.getJsonWebKeys().size() == 0) {
jwk = jks.getJsonWebKeys().get(0);
} else {
for (JsonWebKey j : jks.getJsonWebKeys()) {
if (j.getUse().equalsIgnoreCase("sig")) {
jwk = j;
break;
}
}
}
if (jwk == null) {
throw new ServletException("No key found");
}
pk = (PublicKey) jwk.getKey();
keyCache.put(issuer, pk);
} catch (Exception e) {
throw new ServletException("Could not get oidc certs", e);
} finally {
if (http != null) {
http.getHttp().close();
http.getBcm().close();
}
}
}
} else {
String validationKey = authParams.get("validationKey").getValues().get(0);
pk = cfg.getCertificate(validationKey).getPublicKey();
}
boolean linkToDirectory = Boolean.parseBoolean(authParams.get("linkToDirectory").getValues().get(0));
String noMatchOU = authParams.get("noMatchOU").getValues().get(0);
String uidAttr = authParams.get("uidAttr").getValues().get(0);
String lookupFilter = authParams.get("lookupFilter").getValues().get(0);
String defaultObjectClass = authParams.get("defaultObjectClass").getValues().get(0);
UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);
RequestHolder reqHolder = ((AuthController) session.getAttribute(ProxyConstants.AUTH_CTL)).getHolder();
JsonWebSignature jws = new JsonWebSignature();
try {
jws.setCompactSerialization(lmToken);
jws.setKey(pk);
if (!jws.verifySignature()) {
as.setExecuted(true);
as.setSuccess(false);
logger.warn("Could not verify signature");
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
}
String json = jws.getPayload();
JSONObject obj = (JSONObject) new JSONParser().parse(json);
long exp = ((Long) obj.get("exp")) * 1000L;
long nbf = ((Long) obj.get("nbf")) * 1000L;
if (new DateTime(exp).isBeforeNow()) {
as.setExecuted(true);
as.setSuccess(false);
logger.warn("JWT not yet valid");
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
}
if (new DateTime(nbf).isAfterNow()) {
as.setExecuted(true);
as.setSuccess(false);
logger.warn("JWT expired");
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
}
if (!((String) obj.get("iss")).equals(issuer)) {
as.setExecuted(true);
as.setSuccess(false);
logger.warn("JWT invalid issuer");
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
}
Object aud = obj.get("aud");
if (aud == null) {
logger.warn("JWT has no aud");
as.setExecuted(true);
as.setSuccess(false);
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
} else if (aud instanceof JSONArray) {
JSONArray auds = (JSONArray) aud;
boolean found = false;
for (Object audVal : auds) {
if (audiences.contains((String) audVal)) {
found = true;
}
}
if (!found) {
as.setExecuted(true);
as.setSuccess(false);
logger.warn("Invalid audience");
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
}
} else {
if (!audiences.contains((String) aud)) {
as.setExecuted(true);
as.setSuccess(false);
logger.warn("Invalid audience");
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
super.sendFail(response, realmName, scope, null, null);
return;
}
}
if (!linkToDirectory) {
loadUnlinkedUser(session, noMatchOU, uidAttr, act, obj, defaultObjectClass);
as.setSuccess(true);
} else {
lookupUser(as, session, cfg.getMyVD(), noMatchOU, uidAttr, lookupFilter, act, obj, defaultObjectClass);
}
String redirectToURL = request.getParameter("target");
if (redirectToURL != null && !redirectToURL.isEmpty()) {
reqHolder.setURL(redirectToURL);
}
as.setExecuted(true);
as.setSuccess(true);
cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
} catch (JoseException | ParseException e) {
throw new ServletException("Could not process JWT", e);
}
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class Drupal8Target method syncUser.
@Override
public void syncUser(User user, boolean addOnly, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
if (user.getUserID().isEmpty()) {
this.createUser(user, attributes, request);
return;
}
int userID = 0;
int approvalID = 0;
int workflowID = 0;
if (request.containsKey("TREMOLO_USER_ID")) {
userID = (Integer) request.get("TREMOLO_USER_ID");
}
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
if (request.containsKey("WORKFLOW_ID")) {
workflowID = (Integer) request.get("WORKFLOW_ID");
}
User fromDrupal = this.findUser(user.getUserID(), attributes, request);
Workflow workflow = (Workflow) request.get("WORKFLOW");
StringBuilder sb = new StringBuilder();
JSONObject root = new JSONObject();
HashMap<String, String> attrsForAudit = new HashMap<String, String>();
if (syncAttribute("name", user, fromDrupal, attributes)) {
this.setJsonValue("name", user.getAttribs().get("name").getValues().get(0), root);
attrsForAudit.put("name", user.getAttribs().get("name").getValues().get(0));
}
if (syncAttribute("langcode", user, fromDrupal, attributes)) {
this.setJsonValue("langcode", user.getAttribs().get("langcode").getValues().get(0), root);
attrsForAudit.put("langcode", user.getAttribs().get("langcode").getValues().get(0));
}
if (syncAttribute("preferred_langcode", user, fromDrupal, attributes)) {
this.setJsonValue("preferred_langcode", user.getAttribs().get("preferred_langcode").getValues().get(0), root);
attrsForAudit.put("preferred_langcode", user.getAttribs().get("preferred_langcode").getValues().get(0));
}
if (syncAttribute("preferred_admin_langcode", user, fromDrupal, attributes)) {
this.setJsonValue("preferred_admin_langcode", user.getAttribs().get("preferred_admin_langcode").getValues().get(0), root);
attrsForAudit.put("preferred_admin_langcode", user.getAttribs().get("preferred_admin_langcode").getValues().get(0));
}
if (syncAttribute("mail", user, fromDrupal, attributes)) {
this.setJsonValue("mail", user.getAttribs().get("mail").getValues().get(0), root);
attrsForAudit.put("mail", user.getAttribs().get("mail").getValues().get(0));
}
if (syncAttribute("status", user, fromDrupal, attributes)) {
this.setJsonValueBoolean("status", user.getAttribs().get("status").getValues().get(0), root);
attrsForAudit.put("status", user.getAttribs().get("status").getValues().get(0));
}
for (String userAttributeName : user.getAttribs().keySet()) {
if (!defaultAttributes.contains(userAttributeName) && this.syncAttribute(userAttributeName, user, fromDrupal, attributes)) {
this.setJsonValue("field_" + userAttributeName, user.getAttribs().get(userAttributeName).getValues().get(0), root);
attrsForAudit.put("field_" + userAttributeName, user.getAttribs().get(userAttributeName).getValues().get(0));
}
}
JSONArray roles = new JSONArray();
List<String> addedRoles = new ArrayList<String>();
List<String> removedRoles = new ArrayList<String>();
for (String groupName : user.getGroups()) {
if (!fromDrupal.getGroups().contains(groupName)) {
addedRoles.add(groupName);
}
JSONObject group = new JSONObject();
group.put("target_id", groupName);
roles.add(group);
}
for (String groupName : fromDrupal.getGroups()) {
if (!user.getGroups().contains(groupName)) {
if (addOnly) {
JSONObject group = new JSONObject();
group.put("target_id", groupName);
roles.add(group);
} else {
removedRoles.add(groupName);
}
}
}
root.put("roles", roles);
HttpPatch post = new HttpPatch(this.url + "/user/" + user.getUserID() + "?_format=json");
post.setHeader(new BasicHeader("X-CSRF-Token", UUID.randomUUID().toString()));
post.addHeader("Content-Type", "application/json");
try {
post.setEntity(new StringEntity(root.toJSONString()));
} catch (UnsupportedEncodingException e) {
throw new ProvisioningException("Couldn't create user", e);
}
sb.setLength(0);
sb.append(this.user).append(":").append(this.password);
String azHeader = java.util.Base64.getEncoder().encodeToString(sb.toString().getBytes());
sb.setLength(0);
post.setHeader("Authorization", sb.append("Basic ").append(azHeader).toString());
HttpCon con = null;
try {
con = this.createClient();
} catch (Exception e) {
throw new ProvisioningException("Couldn't create user", e);
}
try {
CloseableHttpResponse resp = con.getHttp().execute(post);
if (resp.getStatusLine().getStatusCode() == 200) {
String json = EntityUtils.toString(resp.getEntity());
JSONParser parser = new JSONParser();
root = (JSONObject) parser.parse(json);
String uid = getJsonValue("uid", root);
for (String attr : attrsForAudit.keySet()) {
this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Replace, approvalID, workflow, attr, attrsForAudit.get(attr));
}
for (String groupName : addedRoles) {
this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "role", groupName);
}
for (String groupName : removedRoles) {
this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Delete, approvalID, workflow, "role", groupName);
}
user.setUserID(uid);
} else {
throw new ProvisioningException("Could not create user with code " + resp.getStatusLine().getStatusCode());
}
} catch (IOException | ParseException e) {
throw new ProvisioningException("Couldn't create user", e);
}
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class Drupal8Target method findUser.
@Override
public User findUser(String userID, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
StringBuilder sb = new StringBuilder();
sb.append(url).append("/user/").append(userID).append("?_format=json");
HttpCon con = null;
try {
con = this.createClient();
HttpGet req = new HttpGet(sb.toString());
sb.setLength(0);
sb.append(this.user).append(":").append(this.password);
String azHeader = java.util.Base64.getEncoder().encodeToString(sb.toString().getBytes());
sb.setLength(0);
req.setHeader("Authorization", sb.append("Basic ").append(azHeader).toString());
CloseableHttpResponse resp = con.getHttp().execute(req);
if (resp.getStatusLine().getStatusCode() != 200) {
logger.warn("User '" + userID + "' not found");
return null;
}
String json = EntityUtils.toString(resp.getEntity());
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(json);
String uid = getJsonValue("uid", root);
User user = new User(uid);
if (attributes.contains("uuid")) {
String uuid = getJsonValue("uuid", root);
user.getAttribs().put("uuid", new Attribute("uuid", uuid));
}
if (attributes.contains("name")) {
String uuid = getJsonValue("name", root);
user.getAttribs().put("name", new Attribute("name", uuid));
}
if (attributes.contains("langcode")) {
String uuid = getJsonValue("langcode", root);
user.getAttribs().put("langcode", new Attribute("langcode", uuid));
}
if (attributes.contains("preferred_langcode")) {
String uuid = getJsonValue("preferred_langcode", root);
user.getAttribs().put("preferred_langcode", new Attribute("preferred_langcode", uuid));
}
if (attributes.contains("preferred_admin_langcode")) {
String uuid = getJsonValue("preferred_admin_langcode", root);
user.getAttribs().put("preferred_admin_langcode", new Attribute("preferred_admin_langcode", uuid));
}
if (attributes.contains("mail")) {
String uuid = getJsonValue("mail", root);
user.getAttribs().put("mail", new Attribute("mail", uuid));
}
if (attributes.contains("status")) {
String uuid = getJsonValue("status", root);
user.getAttribs().put("status", new Attribute("status", uuid));
user.getAttribs().get("status").setDataType(DataType.booleanVal);
}
if (attributes.contains("created")) {
String uuid = getJsonValue("created", root);
user.getAttribs().put("created", new Attribute("created", uuid));
}
if (attributes.contains("changed")) {
String uuid = getJsonValue("changed", root);
user.getAttribs().put("changed", new Attribute("changed", uuid));
}
if (attributes.contains("access")) {
String uuid = getJsonValue("access", root);
user.getAttribs().put("access", new Attribute("access", uuid));
}
if (attributes.contains("default_langcode")) {
String uuid = getJsonValue("default_langcode", root);
user.getAttribs().put("default_langcode", new Attribute("default_langcode", uuid));
user.getAttribs().get("default_langcode").setDataType(DataType.booleanVal);
}
JSONArray roles = (JSONArray) root.get("roles");
for (Object o : roles) {
JSONObject role = (JSONObject) o;
user.getGroups().add((String) role.get("target_id"));
}
for (Object o : root.keySet()) {
String keyName = (String) o;
if (keyName.startsWith("field_")) {
String attributeName = keyName.substring(6);
if (attributes.contains(attributeName)) {
user.getAttribs().put(attributeName, new Attribute(attributeName, this.getJsonValue(keyName, root)));
}
}
}
return user;
} catch (Exception e) {
throw new ProvisioningException("Could not find user", e);
} finally {
if (con != null) {
try {
con.getHttp().close();
} catch (IOException e) {
}
con.getBcm().close();
}
}
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class ArgoCDTarget method createConnection.
public HttpCon createConnection() {
ArrayList<Header> defheaders = new ArrayList<Header>();
defheaders.add(new BasicHeader("Authorization", new StringBuilder().append("Bearer ").append(this.token).toString()));
BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager(GlobalEntries.getGlobalEntries().getConfigManager().getHttpClientSocketRegistry());
RequestConfig rc = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).setRedirectsEnabled(false).build();
CloseableHttpClient http = HttpClients.custom().setConnectionManager(bhcm).setDefaultHeaders(defheaders).setDefaultRequestConfig(rc).build();
return new HttpCon(http, bhcm);
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class AttributeChange method createUser.
@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
int approvalID = 0;
if (request.containsKey("APPROVAL_ID")) {
approvalID = (Integer) request.get("APPROVAL_ID");
}
Workflow workflow = (Workflow) request.get("WORKFLOW");
if (request.containsKey("tremolo.azuread.external") && request.get("tremolo.azuread.external").equals("true")) {
JSONObject root = new JSONObject();
root.put("invitedUserEmailAddress", user.getAttribs().get("mail").getValues().get(0));
root.put("inviteRedirectUrl", request.get("tremolo.azuread.invitation.redirect"));
root.put("sendInvitationMessage", true);
JSONObject invitation = new JSONObject();
invitation.put("ccRecipients", new JSONArray());
invitation.put("customizedMessageBody", request.get("tremolo.azuread.invitation.message"));
root.put("invitedUserMessageInfo", invitation);
HttpCon con = null;
try {
con = this.createClient();
String json = this.callWSPostJsonReesponseExpected(con, "/invitations", root.toString());
root = (JSONObject) new JSONParser().parse(json);
String id = ((JSONObject) root.get("invitedUser")).get("id").toString();
String userPrincipalName = this.getUpnFromId(con, id);
if (userPrincipalName == null) {
throw new ProvisioningException("user not created");
}
user.setUserID(userPrincipalName);
user.getAttribs().put("userPrincipalName", new Attribute("userPrincipalName", userPrincipalName));
user.getAttribs().put("id", new Attribute("id", id));
this.cfgMgr.getProvisioningEngine().logAction(this.name, true, ActionType.Add, approvalID, workflow, "userPrincipalName", user.getAttribs().get("userPrincipalName").getValues().get(0));
this.cfgMgr.getProvisioningEngine().logAction(this.name, false, ActionType.Add, approvalID, workflow, "userPrincipalName", user.getAttribs().get("userPrincipalName").getValues().get(0));
Thread.sleep(10000);
User fromAzure = this.findUser(userPrincipalName, attributes, request);
int i = 0;
while (fromAzure == null) {
if (i > 100) {
throw new ProvisioningException("New user not available");
}
Thread.sleep(1000);
try {
fromAzure = this.findUser(userPrincipalName, attributes, request);
} catch (ProvisioningException e) {
// do notthing
}
i++;
}
this.synUser(user, true, attributes, fromAzure, approvalID, workflow);
} catch (Exception e) {
throw new ProvisioningException("Could not create invitd user", e);
} finally {
try {
con.getHttp().close();
} catch (IOException e) {
}
con.getBcm().close();
}
} else {
createInternalUser(user, attributes, request, approvalID, workflow);
}
}
Aggregations