Search in sources :

Example 1 with OpenShiftTarget

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

the class AddGroupToRole method addToRBACRole.

private void addToRBACRole(OpenShiftTarget os, String token, HttpCon con, String localProjectName, String localPolicyName, String localGroupName, int approvalID) throws Exception {
    String roleBindingUri = new StringBuilder().append(this.openShiftVersion == 3.9 ? "/apis/rbac.authorization.k8s.io/v1/namespaces/" : "/apis/rbac.authorization.k8s.io/v1beta1/namespaces/").append(localProjectName).append("/rolebindings/").append(localPolicyName).toString();
    String json = os.callWS(token, con, roleBindingUri);
    if (logger.isDebugEnabled()) {
        logger.debug("Policy binding : '" + json + "'");
    }
    JSONParser parser = new JSONParser();
    JSONObject rb = (JSONObject) parser.parse(json);
    if (rb.get("status") != null && rb.get("status").equals("Failure")) {
        throw new ProvisioningException("Role binding : '" + localPolicyName + "' does not exist");
    }
    JSONArray subjects = (JSONArray) rb.get("subjects");
    if (subjects != null) {
        for (Object o : subjects) {
            JSONObject jo = (JSONObject) o;
            if (jo.get("kind").equals("Group") && jo.get("name").equals(localGroupName)) {
                logger.warn(localGroupName + " already in policy " + localPolicyName + " on project " + localProjectName);
                return;
            }
        }
    } else {
        subjects = new JSONArray();
        rb.put("subjects", subjects);
    }
    JSONObject binding = new JSONObject();
    binding.put("kind", "Group");
    binding.put("apiGroup", "rbac.authorization.k8s.io");
    binding.put("name", localGroupName);
    subjects.add(binding);
    String jsonResp = os.callWSPut(token, con, roleBindingUri, rb.toJSONString());
    Gson gson = new Gson();
    Response resp = gson.fromJson(jsonResp, Response.class);
    if (resp.getStatus() != null) {
        throw new ProvisioningException("Could not add '" + localGroupName + "' to '" + localPolicyName + "' in project '" + localProjectName + "' - " + jsonResp);
    } else {
        this.task.getConfigManager().getProvisioningEngine().logAction(this.targetName, true, ActionType.Add, approvalID, this.task.getWorkflow(), "openshift-project.role.group", new StringBuilder().append(localProjectName).append('.').append(localPolicyName).append('.').append(localGroupName).toString());
    }
}
Also used : Response(com.tremolosecurity.unison.openshiftv3.model.Response) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONArray(org.json.simple.JSONArray) Gson(com.google.gson.Gson) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject)

Example 2 with OpenShiftTarget

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

the class AddGroupToRole method addTo36Role.

private void addTo36Role(OpenShiftTarget os, String token, HttpCon con, String localProjectName, String localPolicyName, String localGroupName, int approvalID) throws Exception {
    String roleBindingUri = new StringBuilder().append("/oapi/v1/namespaces/").append(localProjectName).append("/policybindings").toString();
    String json = os.callWS(token, con, roleBindingUri);
    if (logger.isDebugEnabled()) {
        logger.debug("All policy bindings : '" + json + "'");
    }
    JSONParser parser = new JSONParser();
    JSONObject pbl = (JSONObject) parser.parse(json);
    JSONArray items = (JSONArray) pbl.get("items");
    JSONArray rb = (JSONArray) ((JSONObject) items.get(0)).get("roleBindings");
    JSONObject foundRoleBinding = null;
    boolean foundInGroupName = false;
    boolean foundInSubjects = false;
    boolean foundPolicy = false;
    for (Object o : rb) {
        JSONObject binding = (JSONObject) o;
        if (binding.get("name").equals(localPolicyName)) {
            foundPolicy = true;
            JSONObject rbx = (JSONObject) binding.get("roleBinding");
            foundRoleBinding = rbx;
            JSONArray groupNames = (JSONArray) rbx.get("groupNames");
            if (groupNames != null) {
                for (Object o1 : groupNames) {
                    String groupName = (String) o1;
                    if (groupName.equalsIgnoreCase(localGroupName)) {
                        foundInGroupName = true;
                    }
                }
            }
            JSONArray subjects = (JSONArray) rbx.get("subjects");
            if (subjects != null) {
                for (Object o1 : subjects) {
                    JSONObject subj = (JSONObject) o1;
                    if (subj.get("kind").equals("group") && subj.get("name").equals(localGroupName)) {
                        foundInSubjects = true;
                    }
                }
            }
        }
    }
    if (foundInGroupName || foundInSubjects) {
        logger.warn(localGroupName + " already in policy " + localPolicyName + " on project " + localProjectName);
    } else {
        if (foundRoleBinding != null) {
            JSONArray groupNames = (JSONArray) foundRoleBinding.get("groupNames");
            if (groupNames == null) {
                groupNames = new JSONArray();
                foundRoleBinding.put("groupNames", groupNames);
            }
            groupNames.add(localGroupName);
            JSONArray subjects = (JSONArray) foundRoleBinding.get("subjects");
            if (subjects == null) {
                subjects = new JSONArray();
                foundRoleBinding.put("subjects", subjects);
            }
            JSONObject subject = new JSONObject();
            subject.put("kind", "Group");
            subject.put("name", localGroupName);
            subjects.add(subject);
            foundRoleBinding.put("kind", "RoleBinding");
            foundRoleBinding.put("apiVersion", "v1");
            if (logger.isDebugEnabled()) {
                logger.debug("new policy : '" + foundRoleBinding + "'");
            }
            String saveURI = new StringBuilder().append("/oapi/v1/namespaces/").append(localProjectName).append("/rolebindings/").append(localPolicyName).toString();
            String jsonResp = os.callWSPut(token, con, saveURI, foundRoleBinding.toJSONString());
            Gson gson = new Gson();
            Response resp = gson.fromJson(jsonResp, Response.class);
            if (!resp.getKind().equals("RoleBinding")) {
                throw new ProvisioningException("Could not add '" + localGroupName + "' to '" + localPolicyName + "' in project '" + localProjectName + "' - " + jsonResp);
            } else {
                this.task.getConfigManager().getProvisioningEngine().logAction(this.targetName, true, ActionType.Add, approvalID, this.task.getWorkflow(), "openshift-project.role.group", new StringBuilder().append(localProjectName).append('.').append(localPolicyName).append('.').append(localGroupName).toString());
            }
        } else {
            foundRoleBinding = new JSONObject();
            foundRoleBinding.put("kind", "RoleBinding");
            foundRoleBinding.put("apiVersion", "v1");
            JSONObject metadata = new JSONObject();
            metadata.put("name", localPolicyName);
            metadata.put("namespace", localProjectName);
            foundRoleBinding.put("metadata", metadata);
            JSONArray groupNames = new JSONArray();
            foundRoleBinding.put("groupNames", groupNames);
            groupNames.add(localGroupName);
            JSONArray subjects = new JSONArray();
            foundRoleBinding.put("subjects", subjects);
            JSONObject subject = new JSONObject();
            subject.put("kind", "Group");
            subject.put("name", localGroupName);
            subjects.add(subject);
            JSONObject roleRef = new JSONObject();
            roleRef.put("name", localPolicyName);
            foundRoleBinding.put("roleRef", roleRef);
            String saveURI = new StringBuilder().append("/oapi/v1/namespaces/").append(localProjectName).append("/rolebindings").toString();
            String jsonResp = os.callWSPost(token, con, saveURI, foundRoleBinding.toJSONString());
            Gson gson = new Gson();
            if (logger.isDebugEnabled()) {
                logger.debug("response json  - " + jsonResp);
            }
            Response resp = gson.fromJson(jsonResp, Response.class);
            if (!resp.getKind().equals("RoleBinding")) {
                throw new ProvisioningException("Could not add '" + localGroupName + "' to '" + localPolicyName + "' in project '" + localProjectName + "' - " + resp.getStatus());
            } else {
                this.task.getConfigManager().getProvisioningEngine().logAction(this.targetName, true, ActionType.Add, approvalID, this.task.getWorkflow(), "openshift-project.role.group", new StringBuilder().append(localProjectName).append('.').append(localPolicyName).append('.').append(localGroupName).toString());
            }
        }
    }
}
Also used : Response(com.tremolosecurity.unison.openshiftv3.model.Response) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONArray(org.json.simple.JSONArray) Gson(com.google.gson.Gson) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject)

Example 3 with OpenShiftTarget

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

the class CreateK8sObject 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);
    String localTemplateJSON = "";
    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();
        if (this.yaml) {
            Yaml yaml = new Yaml();
            Map<String, Object> map = (Map<String, Object>) yaml.load(new ByteArrayInputStream(localTemplate.getBytes("UTF-8")));
            JSONObject jsonObject = new JSONObject(map);
            localTemplateJSON = jsonObject.toJSONString();
        } else {
            localTemplateJSON = localTemplate;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Write To Request  : '" + this.writeToRequestConfig + "'");
        }
        boolean writeToRequest = false;
        if (this.writeToRequestConfig != null) {
            writeToRequest = task.renderTemplate(this.writeToRequestConfig, request).equalsIgnoreCase("true");
        }
        if (writeToRequest) {
            logger.debug("Writing to secret");
            if (!os.isObjectExists(token, con, localURL, localTemplateJSON)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Url '" + localURL + "' doesn't exist");
                }
                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("data", Base64.getEncoder().encodeToString(localTemplate.getBytes("UTF-8")));
                GitFile gitFile = new GitFile(fileName, dirName, localTemplate);
                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 {
            writeToAPIServer(localTemplateJSON, approvalID, localURL, con, os, token, localTarget);
        }
    } 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) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) Yaml(org.yaml.snakeyaml.Yaml) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) ParseException(org.json.simple.parser.ParseException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) JSONObject(org.json.simple.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map)

Example 4 with OpenShiftTarget

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

the class K8sInjectImpersonation 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");
    AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)).getAuthInfo();
    request.addHeader(new Attribute("Impersonate-User", userData.getAttribs().get(this.userNameAttribute).getValues().get(0)));
    Attribute groups = new Attribute("Impersonate-Group");
    groups.getValues().add("system:authenticated");
    Attribute fromUser = userData.getAttribs().get(this.groupAttribute);
    if (fromUser != null) {
        groups.getValues().addAll(fromUser.getValues());
    }
    if (groups.getValues().size() > 0) {
        request.addHeader(groups);
    }
    OpenShiftTarget target = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    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 : AuthInfo(com.tremolosecurity.proxy.auth.AuthInfo) Attribute(com.tremolosecurity.saml.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) AuthController(com.tremolosecurity.proxy.auth.AuthController)

Example 5 with OpenShiftTarget

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

the class K8sProjectCheck method createTremoloUser.

@Override
public String createTremoloUser(NewUserRequest newUser, List<String> errors, AuthInfo userData) throws ProvisioningException {
    if (errors.size() == 0) {
        String targetName = newUser.getAttributes().get("cluster");
        if (targetName == null) {
            targetName = this.targetName;
        }
        OpenShiftTarget target = (OpenShiftTarget) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(targetName).getProvider();
        HttpCon con = null;
        try {
            String token = target.getAuthToken();
            con = target.createClient();
            if (target.isObjectExistsByName(token, con, "/api/v1/namespaces", newUser.getAttributes().get(this.projectAttributeName))) {
                errors.add("Namespace name already exists");
                return "";
            }
        } catch (Exception e) {
            throw new ProvisioningException("Could not check if namespace exists", e);
        } finally {
            if (con != null) {
                try {
                    con.getHttp().close();
                } catch (IOException e) {
                // doesn't matter
                }
                con.getBcm().close();
            }
        }
        if (target.getGitUrl() != null && !target.getGitUrl().isEmpty()) {
            String gitUrlForNs = newUser.getAttributes().get("gitUrl");
            String sshPrivKey = newUser.getAttributes().get("gitSshKey");
            if (gitUrlForNs == null || gitUrlForNs.isEmpty()) {
                errors.add("Git URL is required for clusters configured to use git");
            }
            if (sshPrivKey == null || sshPrivKey.isEmpty()) {
                errors.add("Git SSH Private Key is required for clusters configured to use git");
            }
            if (errors.size() > 0) {
                return "";
            }
            GitUtils gitUtil = new GitUtils(gitUrlForNs, sshPrivKey);
            try {
                gitUtil.checkOut();
            } catch (Throwable t) {
                logger.warn("Could not checkout '" + gitUrlForNs + "'", t);
                errors.add(t.getMessage());
            } finally {
                gitUtil.cleanup();
            }
        }
        return this.workflowName;
    } else {
        return "";
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) GitUtils(com.tremolosecurity.git.GitUtils) OpenShiftTarget(com.tremolosecurity.unison.openshiftv3.OpenShiftTarget) IOException(java.io.IOException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException)

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