Search in sources :

Example 36 with HttpCon

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;
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Workflow(com.tremolosecurity.provisioning.core.Workflow) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) JSONParser(org.json.simple.parser.JSONParser) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 37 with HttpCon

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;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Workflow(com.tremolosecurity.provisioning.core.Workflow) Gson(com.google.gson.Gson) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ArgoCDTarget(com.tremolosecurity.argocd.targets.ArgoCDTarget) StringEntity(org.apache.http.entity.StringEntity) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) GitRepo(com.tremolosecurity.argocd.tasks.obj.GitRepo) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException)

Example 38 with HttpCon

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);
    }
}
Also used : SchedulerException(org.quartz.SchedulerException) JSONArray(org.json.simple.JSONArray) IOException(java.io.IOException) SchedulerException(org.quartz.SchedulerException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JobType(com.tremolosecurity.config.xml.JobType) JSONObject(org.json.simple.JSONObject) CronScheduleType(com.tremolosecurity.config.xml.CronScheduleType) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONObject(org.json.simple.JSONObject) ParamWithValueType(com.tremolosecurity.config.xml.ParamWithValueType)

Example 39 with HttpCon

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);
    }
}
Also used : JSONArray(org.json.simple.JSONArray) JMSException(javax.jms.JMSException) IOException(java.io.IOException) ParamType(com.tremolosecurity.config.xml.ParamType) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) HttpResponseException(org.apache.http.client.HttpResponseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) JMSException(javax.jms.JMSException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONObject(org.json.simple.JSONObject) MessageListenerType(com.tremolosecurity.config.xml.MessageListenerType)

Example 40 with HttpCon

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();
        }
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) DateTime(org.joda.time.DateTime) ByteArrayInputStream(java.io.ByteArrayInputStream) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) MessageDigest(java.security.MessageDigest) XPath(javax.xml.xpath.XPath) NodeList(org.w3c.dom.NodeList) JSONArray(org.json.simple.JSONArray) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) DocumentBuilder(javax.xml.parsers.DocumentBuilder) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject)

Aggregations

HttpCon (com.tremolosecurity.provisioning.util.HttpCon)104 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)82 IOException (java.io.IOException)70 ClientProtocolException (org.apache.http.client.ClientProtocolException)49 JSONObject (org.json.simple.JSONObject)43 ParseException (org.json.simple.parser.ParseException)33 Workflow (com.tremolosecurity.provisioning.core.Workflow)32 ArrayList (java.util.ArrayList)32 UnsupportedEncodingException (java.io.UnsupportedEncodingException)31 OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)27 JSONParser (org.json.simple.parser.JSONParser)25 HashMap (java.util.HashMap)24 JSONArray (org.json.simple.JSONArray)22 User (com.tremolosecurity.provisioning.core.User)18 Attribute (com.tremolosecurity.saml.Attribute)17 Gson (com.google.gson.Gson)16 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 HashSet (java.util.HashSet)13 List (java.util.List)13 KSToken (com.tremolosecurity.unison.openstack.util.KSToken)12