use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class AddtoRBAC method doTask.
@Override
public boolean doTask(User user, 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");
HttpCon con = null;
OpenShiftTarget os = (OpenShiftTarget) task.getConfigManager().getProvisioningEngine().getTarget(this.k8sTarget).getProvider();
try {
String token = os.getAuthToken();
con = os.createClient();
String rbacCfgMapJson = os.callWS(token, con, "/api/v1/namespaces/argocd/configmaps/argocd-rbac-cm");
JSONObject rbacCfgMap = (JSONObject) new JSONParser().parse(rbacCfgMapJson);
JSONObject data = (JSONObject) rbacCfgMap.get("data");
StringBuilder newRbac = new StringBuilder();
if (data != null) {
newRbac.append(data.get("policy.csv")).append('\n');
}
String policiesToAdd = this.task.renderTemplate(this.toAdd, request);
newRbac.append(policiesToAdd);
JSONObject patch = new JSONObject();
JSONObject pdata = new JSONObject();
patch.put("data", pdata);
pdata.put("policy.csv", newRbac.toString());
String json = patch.toString();
String respJSON = os.callWSPatchJson(token, con, "/api/v1/namespaces/argocd/configmaps/argocd-rbac-cm", json);
if (logger.isDebugEnabled()) {
logger.debug("Response for creating project : '" + respJSON + "'");
}
JSONParser parser = new JSONParser();
JSONObject resp = (JSONObject) parser.parse(respJSON);
String kind = (String) resp.get("kind");
String projectName = (String) ((JSONObject) resp.get("metadata")).get("name");
if (!kind.equalsIgnoreCase("ConfigMap")) {
throw new ProvisioningException("Could not update the ArgoCD RBAC ConfigMap - '" + respJSON + "'");
} else {
this.task.getConfigManager().getProvisioningEngine().logAction(this.k8sTarget, true, ActionType.Replace, approvalID, this.task.getWorkflow(), "argocd-rbac-cm", projectName);
}
} catch (Exception e) {
throw new ProvisioningException("Could not update argocd rbac", e);
} finally {
if (con != null) {
con.getBcm().close();
}
}
return true;
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class CreateGitRepository method doTask.
@Override
public boolean doTask(User user, 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");
String localType = task.renderTemplate(this.type, request);
String localName = task.renderTemplate(this.name, request);
String localRepoUrl = task.renderTemplate(this.repoUrl, request);
String localSshPrivateKey = task.renderTemplate(this.sshPrivateKey, request);
GitRepo repo = new GitRepo();
repo.setType(localType);
repo.setName(localName);
repo.setRepo(localRepoUrl);
repo.setSshPrivateKey(localSshPrivateKey);
Gson gson = new Gson();
String json = gson.toJson(repo);
// System.out.println(json);
ArgoCDTarget argo = (ArgoCDTarget) task.getConfigManager().getProvisioningEngine().getTarget(this.target).getProvider();
HttpCon con = null;
try {
con = argo.createConnection();
String url = new StringBuilder().append(argo.getUrl()).append("/api/v1/repositories").toString();
HttpPost post = new HttpPost(url);
StringEntity str = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(str);
HttpResponse resp = con.getHttp().execute(post);
json = EntityUtils.toString(resp.getEntity());
if (resp.getStatusLine().getStatusCode() < 200 || resp.getStatusLine().getStatusCode() >= 300) {
throw new ProvisioningException("Could not create repository - " + resp.getStatusLine().getStatusCode() + " / " + json);
}
task.getConfigManager().getProvisioningEngine().logAction(argo.getName(), true, ActionType.Add, approvalID, workflow, localName, localRepoUrl);
} catch (IOException e) {
throw new ProvisioningException("Could not create repository", e);
} finally {
if (con != null) {
try {
con.getHttp().close();
} catch (IOException e) {
}
con.getBcm().close();
}
}
return true;
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class LoadJobsFromK8s method createJob.
private void createJob(JSONObject item, String name) throws ProvisioningException {
HttpCon nonwatchHttp = null;
JobType job = new JobType();
job.setName(name);
JSONObject spec = (JSONObject) item.get("spec");
StringBuffer b = new StringBuffer();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) spec.get("className"));
job.setClassName(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) spec.get("group"));
job.setGroup(b.toString());
JSONArray params = (JSONArray) spec.get("params");
for (Object o : params) {
JSONObject param = (JSONObject) o;
ParamWithValueType pt = new ParamWithValueType();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("name"));
pt.setName(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("value"));
pt.setValue(b.toString());
job.getParam().add(pt);
}
JSONArray secretParams = (JSONArray) spec.get("secretParams");
if (secretParams != null) {
try {
nonwatchHttp = this.k8sWatch.getK8s().createClient();
String token = this.k8sWatch.getK8s().getAuthToken();
for (Object o : secretParams) {
JSONObject secretParam = (JSONObject) o;
String paramName = (String) secretParam.get("name");
String secretName = (String) secretParam.get("secretName");
String secretKey = (String) secretParam.get("secretKey");
String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
ParamWithValueType pt = new ParamWithValueType();
pt.setName(paramName);
pt.setValue(secretValue);
job.getParam().add(pt);
}
} catch (Exception e) {
throw new ProvisioningException("Could not load secrets for '" + name + "'");
} finally {
if (nonwatchHttp != null) {
try {
nonwatchHttp.getHttp().close();
} catch (IOException e) {
}
nonwatchHttp.getBcm().close();
}
}
}
job.setCronSchedule(new CronScheduleType());
JSONObject cron = (JSONObject) spec.get("cronSchedule");
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("seconds"));
job.getCronSchedule().setSeconds(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("minutes"));
job.getCronSchedule().setMinutes(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("hours"));
job.getCronSchedule().setHours(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("dayOfMonth"));
job.getCronSchedule().setDayOfMonth(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("month"));
job.getCronSchedule().setMonth(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("dayOfWeek"));
job.getCronSchedule().setDayOfWeek(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) cron.get("year"));
job.getCronSchedule().setYear(b.toString());
try {
this.cfgMgr.getProvisioningEngine().addNewJob(jobKeys, job);
} catch (ClassNotFoundException | SchedulerException | ProvisioningException e) {
throw new ProvisioningException("Could not add job '" + name + "'", e);
}
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class LoadQueueListenersFromK8s method createQueue.
private void createQueue(TremoloType tremolo, String name, JSONObject item) throws ProvisioningException {
JSONObject spec = (JSONObject) item.get("spec");
MessageListenerType mlt = new MessageListenerType();
mlt.setQueueName(name);
StringBuffer b = new StringBuffer();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) spec.get("className"));
mlt.setClassName(b.toString());
JSONArray params = (JSONArray) spec.get("params");
for (Object o : params) {
JSONObject param = (JSONObject) o;
ParamType pt = new ParamType();
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("name"));
pt.setName(b.toString());
b.setLength(0);
OpenUnisonConfigLoader.integrateIncludes(b, (String) param.get("value"));
pt.setValue(b.toString());
mlt.getParams().add(pt);
}
HttpCon nonwatchHttp = null;
JSONArray secretParams = (JSONArray) spec.get("secretParams");
if (secretParams != null) {
try {
nonwatchHttp = this.k8sWatch.getK8s().createClient();
String token = this.k8sWatch.getK8s().getAuthToken();
for (Object o : secretParams) {
JSONObject secretParam = (JSONObject) o;
String paramName = (String) secretParam.get("name");
String secretName = (String) secretParam.get("secretName");
String secretKey = (String) secretParam.get("secretKey");
String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue(secretValue);
mlt.getParams().add(pt);
}
} catch (Exception e) {
throw new ProvisioningException("Could not load secrets for '" + name + "'");
} finally {
if (nonwatchHttp != null) {
try {
nonwatchHttp.getHttp().close();
} catch (IOException e) {
}
nonwatchHttp.getBcm().close();
}
}
}
try {
this.cfgMgr.getProvisioningEngine().addMessageListener(mlt);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ProvisioningException | JMSException e) {
logger.warn("Could not create listener " + name, e);
}
}
use of com.tremolosecurity.provisioning.util.HttpCon in project OpenUnison by TremoloSecurity.
the class CheckSamlIdPs method execute.
@Override
public void execute(ConfigManager configManager, JobExecutionContext context) throws ProvisioningException {
if (logger.isDebugEnabled())
logger.debug("Checking IdPs");
String selfLink = context.getJobDetail().getJobDataMap().getString("selfLink");
if (logger.isDebugEnabled())
logger.debug("Self Link : '" + selfLink + "'");
String targetName = context.getJobDetail().getJobDataMap().getString("target");
if (logger.isDebugEnabled())
logger.debug("Target : '" + targetName + "'");
OpenShiftTarget target = (OpenShiftTarget) configManager.getProvisioningEngine().getTarget(targetName).getProvider();
HttpCon con = null;
try {
con = target.createClient();
String rawJson = target.callWS(target.getAuthToken(), con, selfLink);
if (logger.isDebugEnabled())
logger.debug("JSON : '" + rawJson + "'");
JSONParser parser = new JSONParser();
JSONObject ouCr = (JSONObject) parser.parse(rawJson);
JSONObject spec = (JSONObject) ouCr.get("spec");
JSONObject status = (JSONObject) ouCr.get("status");
JSONObject fingerPrints = (JSONObject) status.get("idpCertificateFingerprints");
JSONArray remoteIdps = (JSONArray) spec.get("saml_remote_idp");
for (Object o : remoteIdps) {
if (logger.isDebugEnabled())
logger.debug("Checking IdP");
JSONObject idpCfg = (JSONObject) o;
JSONObject source = (JSONObject) idpCfg.get("source");
String url = (String) source.get("url");
if (logger.isDebugEnabled())
logger.debug("URL : '" + url + "'");
if (url != null) {
if (logger.isDebugEnabled())
logger.debug("Pulling metadata");
String metadataXml = this.downloadFile(url, con.getHttp());
DocumentBuilderFactory dbFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new java.io.ByteArrayInputStream(metadataXml.getBytes("UTF-8")));
XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
Element ed = (Element) xpath.compile("/*[local-name() = 'EntityDescriptor']").evaluate(doc, javax.xml.xpath.XPathConstants.NODE);
String entityId = ed.getAttribute("entityID");
List<String> sigCerts = new ArrayList<String>();
String xpathexpr = "//*[local-name() = 'IDPSSODescriptor']";
Element idp = (Element) xpath.compile(xpathexpr).evaluate(ed, javax.xml.xpath.XPathConstants.NODE);
xpathexpr = "//*[local-name() = 'KeyDescriptor']";
NodeList keys = (NodeList) xpath.compile(xpathexpr).evaluate(idp, javax.xml.xpath.XPathConstants.NODESET);
for (int i = 0; i < keys.getLength(); i++) {
Element key = (Element) keys.item(i);
if (key.getAttribute("use").equalsIgnoreCase("signing")) {
xpathexpr = "//*[local-name() = 'X509Certificate']";
Element certTag = (Element) xpath.compile(xpathexpr).evaluate(key, javax.xml.xpath.XPathConstants.NODE);
logger.debug(certTag.getTextContent());
sigCerts.add(certTag.getTextContent());
}
}
MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
int i = 0;
for (String certStr : sigCerts) {
X509Certificate currentCert = string2cert(certStr);
if (logger.isDebugEnabled()) {
logger.debug("Cert " + i + " : " + currentCert.getSubjectDN());
}
i++;
digest.update(currentCert.getEncoded(), 0, currentCert.getEncoded().length);
}
byte[] digest_bytes = digest.digest();
String digest_base64 = java.util.Base64.getEncoder().encodeToString(digest_bytes);
String digestFromStatus = (String) fingerPrints.get(entityId);
if (logger.isDebugEnabled())
logger.debug("Digest from Metadata : '" + digest_base64 + "'");
if (logger.isDebugEnabled())
logger.debug("Digest from status : '" + digestFromStatus + "'");
if (!digest_base64.equals(digestFromStatus)) {
JSONObject patch = new JSONObject();
JSONObject metaData = new JSONObject();
patch.put("metadata", metaData);
JSONObject annotations = new JSONObject();
metaData.put("annotations", annotations);
annotations.put("tremolo.io/samlupdate", new DateTime().toString());
String jsonPatch = patch.toJSONString();
logger.info("Patching OpenUnison CR");
target.callWSPatchJson(target.getAuthToken(), con, selfLink, jsonPatch);
return;
}
}
}
} catch (Exception e) {
throw new ProvisioningException("Could not check idps", e);
} finally {
if (con != null) {
try {
con.getHttp().close();
} catch (IOException e) {
}
con.getBcm().close();
}
}
}
Aggregations