Search in sources :

Example 11 with OpenShiftTarget

use of com.tremolosecurity.unison.openshiftv3.OpenShiftTarget 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 12 with OpenShiftTarget

use of com.tremolosecurity.unison.openshiftv3.OpenShiftTarget 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)

Example 13 with OpenShiftTarget

use of com.tremolosecurity.unison.openshiftv3.OpenShiftTarget in project OpenUnison by TremoloSecurity.

the class K8sWatcher method initalRun.

public void initalRun() throws ProvisioningException {
    OpenShiftTarget k8s = (OpenShiftTarget) provisioningEngine.getTarget(k8sTarget).getProvider();
    if (k8s == null) {
        throw new ProvisioningException("Target " + k8sTarget + " does not exist");
    }
    HttpCon http;
    try {
        http = k8s.createClient();
    } catch (Exception e1) {
        throw new ProvisioningException("Could not create http connection", e1);
    }
    this.resourceVersions = new HashSet<String>();
    try {
        String token = k8s.getAuthToken();
        String json = null;
        try {
            json = k8s.callWS(token, http, uri);
        } catch (HttpResponseException e) {
            logger.warn("Could not retrieve urls, dynamic urls will not be supported", e);
            return;
        }
        JSONObject list = (JSONObject) new JSONParser().parse(json);
        JSONArray items = (JSONArray) list.get("items");
        if (items == null) {
            logger.error("Invalid JSON Response : '" + json + "'");
            return;
        }
        for (Object o : items) {
            JSONObject jsonObj = (JSONObject) o;
            String strjson = jsonObj.toString();
            if (logger.isDebugEnabled())
                logger.debug("json before includes : " + strjson);
            StringBuffer b = new StringBuffer();
            b.setLength(0);
            OpenUnisonConfigLoader.integrateIncludes(b, strjson);
            if (logger.isDebugEnabled())
                logger.debug("json after includes : " + b.toString());
            jsonObj = (JSONObject) new JSONParser().parse(b.toString());
            JSONObject metadata = (JSONObject) jsonObj.get("metadata");
            String resourceVersion = (String) metadata.get("resourceVersion");
            if (this.resourceVersions.contains(resourceVersion)) {
                logger.info("Resource " + resourceVersion + " already processed, skipping");
            } else {
                this.resourceVersions.add(resourceVersion);
                this.watchee.addObject(cfgMgr.getCfg(), jsonObj);
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not get urls", e);
    } finally {
        try {
            http.getHttp().close();
        } catch (IOException e) {
            logger.warn(e);
        }
        http.getBcm().close();
    }
    this.keepRunning = true;
    logger.info("Adding stoppable thread");
    GlobalEntries.getGlobalEntries().getConfigManager().addThread(this);
    logger.info("Starting watch");
    new Thread(this).start();
}
Also used : JSONArray(org.json.simple.JSONArray) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseException(org.apache.http.client.HttpResponseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException) StopableThread(com.tremolosecurity.server.StopableThread) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject)

Example 14 with OpenShiftTarget

use of com.tremolosecurity.unison.openshiftv3.OpenShiftTarget in project OpenUnison by TremoloSecurity.

the class OAuth2K8sServiceAccount 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 k8sTarget = authParams.get("k8sTarget").getValues().get(0);
    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();
    JSONObject root = new JSONObject();
    root.put("kind", "TokenReview");
    root.put("apiVersion", "authentication.k8s.io/v1");
    root.put("spec", new JSONObject());
    ((JSONObject) root.get("spec")).put("token", lmToken);
    String json = root.toJSONString();
    OpenShiftTarget target = null;
    HttpCon con = null;
    try {
        target = (OpenShiftTarget) cfg.getProvisioningEngine().getTarget(k8sTarget).getProvider();
        con = target.createClient();
        String respJSON = target.callWSPost(target.getAuthToken(), con, "/apis/authentication.k8s.io/v1/tokenreviews", json);
        if (logger.isDebugEnabled()) {
            logger.debug("JSON - " + respJSON);
        }
        JSONParser parser = new JSONParser();
        JSONObject resp = (JSONObject) parser.parse(respJSON);
        JSONObject status = (JSONObject) resp.get("status");
        if (status.get("error") != null) {
            logger.error("Could not validate token : " + status.get("error"));
            as.setExecuted(true);
            as.setSuccess(false);
            cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
            super.sendFail(response, realmName, scope, null, null);
            return;
        } else {
            Boolean authenticated = (Boolean) status.get("authenticated");
            if (authenticated != null && authenticated) {
                JSONObject user = (JSONObject) status.get("user");
                if (!linkToDirectory) {
                    loadUnlinkedUser(session, noMatchOU, uidAttr, act, user, defaultObjectClass);
                    as.setSuccess(true);
                } else {
                    lookupUser(as, session, cfg.getMyVD(), noMatchOU, uidAttr, lookupFilter, act, user, 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);
            } else {
                as.setExecuted(true);
                as.setSuccess(false);
                cfg.getAuthManager().nextAuth(request, response, request.getSession(), false);
                super.sendFail(response, realmName, scope, null, null);
                return;
            }
        }
    } catch (Exception e) {
        throw new ServletException("Could not validate token", e);
    } finally {
        con.getHttp().close();
        con.getBcm().close();
    }
}
Also used : UrlHolder(com.tremolosecurity.config.util.UrlHolder) ServletException(javax.servlet.ServletException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) JSONParser(org.json.simple.parser.JSONParser) RequestHolder(com.tremolosecurity.proxy.auth.RequestHolder) AuthController(com.tremolosecurity.proxy.auth.AuthController) LDAPException(com.novell.ldap.LDAPException) ServletException(javax.servlet.ServletException) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) JoseException(org.jose4j.lang.JoseException)

Example 15 with OpenShiftTarget

use of com.tremolosecurity.unison.openshiftv3.OpenShiftTarget in project OpenUnison by TremoloSecurity.

the class CheckK8sTargetMetadata method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    request.getServletRequest().setAttribute("com.tremolosecurity.unison.proxy.noRedirectOnError", "com.tremolosecurity.unison.proxy.noRedirectOnError");
    if (logger.isDebugEnabled()) {
        logger.debug("URI : " + request.getRequestURI());
    }
    String name = request.getRequestURI().substring(request.getRequestURI().lastIndexOf('/') + 1);
    if (logger.isDebugEnabled()) {
        logger.debug("Looking up for target '" + name + "'");
    }
    OpenShiftTarget k8s = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(name).getProvider();
    if (logger.isDebugEnabled()) {
        if (k8s == null) {
            logger.debug(name + " not found");
        } else {
            logger.debug(name + " found");
        }
    }
    JSONObject root = new JSONObject();
    root.put("isGit", k8s.getGitUrl() != null && !k8s.getGitUrl().isEmpty());
    if (logger.isDebugEnabled()) {
        logger.debug("Response for " + name + " - " + root.toString());
    }
    response.setContentType("application/json");
    response.getWriter().println(root.toString());
    response.getWriter().flush();
}
Also used : JSONObject(org.json.simple.JSONObject) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)

Aggregations

OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)36 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)30 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)27 JSONObject (org.json.simple.JSONObject)18 ArrayList (java.util.ArrayList)13 JSONParser (org.json.simple.parser.JSONParser)13 HashMap (java.util.HashMap)12 IOException (java.io.IOException)11 Workflow (com.tremolosecurity.provisioning.core.Workflow)9 LDAPException (com.novell.ldap.LDAPException)7 List (java.util.List)7 Map (java.util.Map)7 Attribute (com.tremolosecurity.saml.Attribute)6 GitFile (com.tremolosecurity.provisioning.tasks.dataobj.GitFile)5 JSONArray (org.json.simple.JSONArray)4 ParseException (org.json.simple.parser.ParseException)4 Gson (com.google.gson.Gson)3 LDAPEntry (com.novell.ldap.LDAPEntry)3 K8sUser (com.tremolosecurity.myvd.dataObj.K8sUser)3 User (com.tremolosecurity.provisioning.core.User)3