Search in sources :

Example 11 with Response

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

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

Example 13 with Response

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

the class K8sToken method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    Iterator<String> it = request.getHeaderNames();
    List<String> toRemove = new ArrayList<String>();
    while (it.hasNext()) {
        String headerName = it.next();
        if (headerName.toLowerCase().startsWith("impersonate-") || headerName.equalsIgnoreCase("Authorization")) {
            toRemove.add(headerName);
        }
    }
    for (String headerToRemove : toRemove) {
        request.removeHeader(headerToRemove);
    }
    request.removeHeader("Authorization");
    OpenShiftTarget target = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    String token = target.getAuthToken();
    if (token != null) {
        request.addHeader(new Attribute("Authorization", new StringBuilder().append("Bearer ").append(target.getAuthToken()).toString()));
    }
    HashMap<String, String> uriParams = (HashMap<String, String>) request.getAttribute("TREMOLO_URI_PARAMS");
    uriParams.put("k8s_url", target.getUrl());
    chain.nextFilter(request, response, chain);
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)

Example 14 with Response

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

the class DeleteK8sObject 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 localURL = task.renderTemplate(this.url, request);
    HttpCon con = null;
    String localTarget = task.renderTemplate(this.targetName, request);
    OpenShiftTarget os = (OpenShiftTarget) task.getConfigManager().getProvisioningEngine().getTarget(localTarget).getProvider();
    try {
        String token = os.getAuthToken();
        con = os.createClient();
        boolean writeToRequest = false;
        if (this.writeToRequestConfig != null) {
            writeToRequest = task.renderTemplate(this.writeToRequestConfig, request).equalsIgnoreCase("true");
        }
        if (writeToRequest) {
            logger.debug("Writing to secret");
            String localPath = task.renderTemplate(this.path, request);
            String dirName;
            String fileName;
            int lastSlash = localPath.lastIndexOf('/');
            if (lastSlash == -1) {
                dirName = "";
                fileName = localPath;
            } else {
                dirName = localPath.substring(0, lastSlash);
                fileName = localPath.substring(lastSlash + 1);
            }
            JSONObject fileInfo = new JSONObject();
            fileInfo.put("fileName", fileName);
            fileInfo.put("dirName", dirName);
            fileInfo.put("delete", true);
            GitFile gitFile = new GitFile(fileName, dirName, true, kind.equalsIgnoreCase("Namespace"));
            List<GitFile> gitFiles = (List<GitFile>) request.get(this.requestAttribute);
            if (gitFiles == null) {
                gitFiles = new ArrayList<GitFile>();
                request.put(this.requestAttribute, gitFiles);
            }
            gitFiles.add(gitFile);
        } else {
            String respJSON = os.callWSDelete(token, con, localURL);
            if (logger.isDebugEnabled()) {
                logger.debug("Response for deleting object : '" + 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 (logger.isDebugEnabled()) {
                logger.debug("kind : '" + kind + "' / '" + this.kind + "'");
            }
            if (kind.equalsIgnoreCase(this.kind)) {
                this.task.getConfigManager().getProvisioningEngine().logAction(localTarget, true, ProvisioningUtil.ActionType.Delete, approvalID, this.task.getWorkflow(), label, projectName);
            } else if (resp.get("status") != null) {
                String status = (String) resp.get("status");
                logger.info("status : '" + status + "'");
                if (status != null && status.equalsIgnoreCase("success")) {
                    this.task.getConfigManager().getProvisioningEngine().logAction(localTarget, true, ProvisioningUtil.ActionType.Delete, approvalID, this.task.getWorkflow(), label, projectName);
                } else {
                    throw new ProvisioningException("Could not delete " + kind + " with url '" + localURL + "' - '" + respJSON + "'");
                }
            } else {
                throw new ProvisioningException("Could not delete " + kind + " with url '" + localURL + "' - '" + respJSON + "'");
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not delete " + kind + " - " + localURL, e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
    return true;
}
Also used : GitFile(com.tremolosecurity.provisioning.tasks.dataobj.GitFile) Workflow(com.tremolosecurity.provisioning.core.Workflow) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ArrayList(java.util.ArrayList) List(java.util.List) JSONParser(org.json.simple.parser.JSONParser)

Example 15 with Response

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

the class PatchK8sObject method doTask.

@Override
public boolean doTask(User user, Map<String, Object> request) throws ProvisioningException {
    String localTemplate = task.renderTemplate(template, request);
    if (logger.isDebugEnabled()) {
        logger.debug("localTemplate : '" + localTemplate + "'");
    }
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    String localURL = task.renderTemplate(this.url, request);
    HttpCon con = null;
    String localTarget = task.renderTemplate(this.targetName, request);
    OpenShiftTarget os = (OpenShiftTarget) task.getConfigManager().getProvisioningEngine().getTarget(localTarget).getProvider();
    try {
        String token = os.getAuthToken();
        con = os.createClient();
        boolean writeToRequest = false;
        if (this.writeToRequestConfig != null) {
            writeToRequest = task.renderTemplate(this.writeToRequestConfig, request).equalsIgnoreCase("true");
        }
        if (writeToRequest) {
            logger.debug("Writing to secret");
            String localPath = task.renderTemplate(this.path, request);
            String dirName;
            String fileName;
            int lastSlash = localPath.lastIndexOf('/');
            if (lastSlash == -1) {
                dirName = "";
                fileName = localPath;
            } else {
                dirName = localPath.substring(0, lastSlash);
                fileName = localPath.substring(lastSlash + 1);
            }
            GitFile gitFile = new GitFile(fileName, dirName, false, false);
            gitFile.setData(localTemplate);
            gitFile.setPatch(true);
            gitFile.setPatchType(this.patchType);
            List<GitFile> gitFiles = (List<GitFile>) request.get(this.requestAttribute);
            if (gitFiles == null) {
                gitFiles = new ArrayList<GitFile>();
                request.put(this.requestAttribute, gitFiles);
            }
            gitFiles.add(gitFile);
        } else {
            if (this.isObjectExists(os, token, con, localURL, localTemplate)) {
                String respJSON = os.callWSPatchJson(token, con, localURL, localTemplate, this.patchContentType);
                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(this.kind)) {
                    throw new ProvisioningException("Could not create " + kind + " with json '" + localTemplate + "' - '" + respJSON + "'");
                } else {
                    this.task.getConfigManager().getProvisioningEngine().logAction(localTarget, true, ActionType.Replace, approvalID, this.task.getWorkflow(), label, projectName);
                }
            } else {
                throw new ProvisioningException("Object '" + localURL + "' does not exist");
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not create " + kind, e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
    return true;
}
Also used : GitFile(com.tremolosecurity.provisioning.tasks.dataobj.GitFile) Workflow(com.tremolosecurity.provisioning.core.Workflow) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ArrayList(java.util.ArrayList) List(java.util.List) JSONParser(org.json.simple.parser.JSONParser)

Aggregations

ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)17 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)14 OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)14 JSONObject (org.json.simple.JSONObject)12 JSONParser (org.json.simple.parser.JSONParser)9 IOException (java.io.IOException)8 ParseException (org.json.simple.parser.ParseException)8 Gson (com.google.gson.Gson)7 Workflow (com.tremolosecurity.provisioning.core.Workflow)7 Response (com.tremolosecurity.unison.openshiftv3.model.Response)7 ClientProtocolException (org.apache.http.client.ClientProtocolException)7 JoseException (org.jose4j.lang.JoseException)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 KeyManagementException (java.security.KeyManagementException)5 KeyStoreException (java.security.KeyStoreException)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 UnrecoverableKeyException (java.security.UnrecoverableKeyException)5 HashMap (java.util.HashMap)5 HttpResponse (org.apache.http.HttpResponse)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5