Search in sources :

Example 61 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class KeystoneProvisioningTarget method createUser.

@Override
public void createUser(User user, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
    if (rolesOnly) {
        throw new ProvisioningException("Unsupported");
    }
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    KSUser newUser = new KSUser();
    newUser.setDomain_id(this.usersDomain);
    newUser.setName(user.getUserID());
    newUser.setEnabled(true);
    if (attributes.contains("email") && user.getAttribs().containsKey("email")) {
        newUser.setEmail(user.getAttribs().get("email").getValues().get(0));
    }
    if (attributes.contains("description") && user.getAttribs().containsKey("description")) {
        newUser.setEmail(user.getAttribs().get("description").getValues().get(0));
    }
    HttpCon con = null;
    KSUser fromKS = null;
    try {
        con = this.createClient();
        KSToken token = this.getToken(con);
        Gson gson = new Gson();
        UserHolder userHolder = new UserHolder();
        userHolder.setUser(newUser);
        String json = gson.toJson(userHolder);
        StringBuffer b = new StringBuffer();
        b.append(this.url).append("/users");
        json = this.callWSPost(token.getAuthToken(), con, b.toString(), json);
        if (json == null) {
            throw new Exception("Could not create user");
        }
        UserHolder createdUser = gson.fromJson(json, UserHolder.class);
        if (createdUser.getUser() == null) {
            throw new ProvisioningException("Could not create user :" + json);
        }
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), true, ActionType.Add, approvalID, workflow, "name", user.getUserID());
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "name", user.getUserID());
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "domain_id", this.usersDomain);
        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "enabled", "true");
        if (attributes.contains("email")) {
            this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "email", user.getAttribs().get("email").getValues().get(0));
        }
        if (attributes.contains("description")) {
            this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "description", user.getAttribs().get("description").getValues().get(0));
        }
        for (String group : user.getGroups()) {
            String groupID = this.getGroupID(token.getAuthToken(), con, group);
            b.setLength(0);
            b.append(this.url).append("/groups/").append(groupID).append("/users/").append(createdUser.getUser().getId());
            if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) {
                this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "group", group);
            } else {
                throw new ProvisioningException("Could not add group " + group);
            }
        }
        if (attributes.contains("roles")) {
            Attribute roles = user.getAttribs().get("roles");
            for (String roleJSON : roles.getValues()) {
                Role role = gson.fromJson(roleJSON, Role.class);
                if (role.getScope().equalsIgnoreCase("project")) {
                    String projectid = this.getProjectID(token.getAuthToken(), con, role.getProject());
                    if (projectid == null) {
                        throw new ProvisioningException("Project " + role.getDomain() + " does not exist");
                    }
                    String roleid = this.getRoleID(token.getAuthToken(), con, role.getName());
                    if (roleid == null) {
                        throw new ProvisioningException("Role " + role.getName() + " does not exist");
                    }
                    b.setLength(0);
                    b.append(this.url).append("/projects/").append(projectid).append("/users/").append(createdUser.getUser().getId()).append("/roles/").append(roleid);
                    if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) {
                        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "role", roleJSON);
                    } else {
                        throw new ProvisioningException("Could not add role " + roleJSON);
                    }
                } else {
                    String domainid = this.getDomainID(token.getAuthToken(), con, role.getDomain());
                    if (domainid == null) {
                        throw new ProvisioningException("Domain " + role.getDomain() + " does not exist");
                    }
                    String roleid = this.getRoleID(token.getAuthToken(), con, role.getName());
                    if (roleid == null) {
                        throw new ProvisioningException("Role " + role.getName() + " does not exist");
                    }
                    b.setLength(0);
                    b.append(this.url).append("/domains/").append(domainid).append("/users/").append(createdUser.getUser().getId()).append("/roles/").append(roleid);
                    if (this.callWSPutNoData(token.getAuthToken(), con, b.toString())) {
                        this.cfgMgr.getProvisioningEngine().logAction(user.getUserID(), false, ActionType.Add, approvalID, workflow, "role", roleJSON);
                    } else {
                        throw new ProvisioningException("Could not add role " + roleJSON);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not work with keystone", e);
    } finally {
        if (con != null) {
            con.getBcm().shutdown();
        }
    }
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) KSUser(com.tremolosecurity.unison.openstack.model.KSUser) Workflow(com.tremolosecurity.provisioning.core.Workflow) Gson(com.google.gson.Gson) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) KSRole(com.tremolosecurity.unison.openstack.model.KSRole) Role(com.tremolosecurity.unison.openstack.model.Role) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KSToken(com.tremolosecurity.unison.openstack.util.KSToken) UserHolder(com.tremolosecurity.unison.openstack.model.UserHolder)

Example 62 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class UserPrincipal method deleteGroup.

@Override
public void deleteGroup(String name, 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");
    IPACall groupSearch = new IPACall();
    groupSearch.setId(0);
    groupSearch.setMethod("group_del");
    ArrayList<String> groupArray = new ArrayList<String>();
    groupArray.add(name);
    groupSearch.getParams().add(groupArray);
    HashMap<String, String> additionalParams = new HashMap<String, String>();
    groupSearch.getParams().add(additionalParams);
    HttpCon con = null;
    try {
        con = this.createClient();
        IPAResponse resp = this.executeIPACall(groupSearch, con);
        this.cfgMgr.getProvisioningEngine().logAction(name, true, ActionType.Delete, approvalID, workflow, "group-object", name);
    } catch (Exception e) {
        throw new ProvisioningException("Could not find groups", e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
}
Also used : IPAResponse(com.tremolosecurity.unison.freeipa.json.IPAResponse) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) HashMap(java.util.HashMap) IPACall(com.tremolosecurity.unison.freeipa.json.IPACall) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ArrayList(java.util.ArrayList) Workflow(com.tremolosecurity.provisioning.core.Workflow) ClientProtocolException(org.apache.http.client.ClientProtocolException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) IPAException(com.tremolosecurity.unison.freeipa.util.IPAException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 63 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class UserPrincipal method createUser.

public void createUser(User user, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
    UserPrincipal principal = new UserPrincipal(user.getUserID(), multiDomain, primaryDomain);
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    try {
        HttpCon con = this.createClient();
        try {
            if (principal.isPrimaryDomain()) {
                IPACall createUser = new IPACall();
                createUser.setId(0);
                createUser.setMethod("user_add");
                ArrayList<String> userArray = new ArrayList<String>();
                userArray.add(principal.getUid());
                createUser.getParams().add(userArray);
                HashMap<String, Object> userAttrs = new HashMap<String, Object>();
                for (String attrName : attributes) {
                    Attribute attr = user.getAttribs().get(attrName);
                    if (attr != null && !attr.getName().equalsIgnoreCase("uid")) {
                        if (attr.getValues().size() == 1) {
                            userAttrs.put(attr.getName(), attr.getValues().get(0));
                        } else {
                            ArrayList vals = new ArrayList<String>();
                            vals.addAll(attr.getValues());
                            userAttrs.put(attr.getName(), vals);
                        }
                    }
                }
                createUser.getParams().add(userAttrs);
                IPAResponse resp = this.executeIPACall(createUser, con);
                this.cfgMgr.getProvisioningEngine().logAction(name, true, ActionType.Add, approvalID, workflow, "uid", user.getUserID());
                this.cfgMgr.getProvisioningEngine().logAction(name, false, ActionType.Add, approvalID, workflow, "uid", user.getUserID());
                for (String attrName : userAttrs.keySet()) {
                    Object o = userAttrs.get(attrName);
                    if (o instanceof String) {
                        this.cfgMgr.getProvisioningEngine().logAction(name, false, ActionType.Add, approvalID, workflow, attrName, (String) o);
                    } else {
                        List<String> vals = (List<String>) o;
                        for (String val : vals) {
                            this.cfgMgr.getProvisioningEngine().logAction(name, false, ActionType.Add, approvalID, workflow, attrName, val);
                        }
                    }
                }
                for (String group : user.getGroups()) {
                    this.addGroup(principal, group, con, approvalID, workflow);
                }
                if (this.createShadowAccount) {
                    String password = new BigInteger(130, random).toString(32);
                    password = PBKDF2.generateHash(password);
                    user.setPassword(password);
                    this.setUserPassword(user, request);
                }
            } else {
                IPACall idOveride = new IPACall();
                idOveride.setId(0);
                idOveride.setMethod("idoverrideuser_add");
                List<String> params = new ArrayList<String>();
                params.add(this.trustViewName);
                params.add(principal.getUPN());
                idOveride.getParams().add(params);
                Map<String, Object> param2 = new HashMap<String, Object>();
                for (String attrName : attributes) {
                    Attribute attr = user.getAttribs().get(attrName);
                    if (attr != null) {
                        if (attr.getName().equalsIgnoreCase("uid") && !attr.getValues().get(0).equals(user.getUserID())) {
                            param2.put(attr.getName(), attr.getValues().get(0));
                        } else if (!attr.getName().equalsIgnoreCase("uid")) {
                            param2.put(attr.getName(), attr.getValues().get(0));
                        }
                    }
                }
                idOveride.getParams().add(param2);
                IPAResponse resp = this.executeIPACall(idOveride, con);
                this.cfgMgr.getProvisioningEngine().logAction(name, true, ActionType.Add, approvalID, workflow, "uid", user.getUserID());
                this.cfgMgr.getProvisioningEngine().logAction(name, false, ActionType.Add, approvalID, workflow, "uid", user.getUserID());
                for (String attrName : attributes) {
                    Attribute attr = user.getAttribs().get(attrName);
                    if (attr != null) {
                        this.cfgMgr.getProvisioningEngine().logAction(name, false, ActionType.Add, approvalID, workflow, attrName, attr.getValues().get(0));
                    }
                }
                for (String group : user.getGroups()) {
                    this.addGroup(principal, group, con, approvalID, workflow);
                }
            }
        } finally {
            if (con != null) {
                con.getBcm().shutdown();
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not run search", e);
    }
}
Also used : IPAResponse(com.tremolosecurity.unison.freeipa.json.IPAResponse) HashMap(java.util.HashMap) Attribute(com.tremolosecurity.saml.Attribute) IPACall(com.tremolosecurity.unison.freeipa.json.IPACall) ArrayList(java.util.ArrayList) Workflow(com.tremolosecurity.provisioning.core.Workflow) ClientProtocolException(org.apache.http.client.ClientProtocolException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) IPAException(com.tremolosecurity.unison.freeipa.util.IPAException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) BigInteger(java.math.BigInteger) ArrayList(java.util.ArrayList) List(java.util.List)

Example 64 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class CreateGitFile 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");
    GitlabUserProvider gitlab = (GitlabUserProvider) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    GitLabApi api = gitlab.getApi();
    String localNamespace = task.renderTemplate(this.namespace, request);
    String localProjectName = task.renderTemplate(this.project, request);
    String localPath = task.renderTemplate(this.path, request);
    String localBranch = task.renderTemplate(this.branch, request);
    String localContent = task.renderTemplate(this.content, request);
    String localCommit = task.renderTemplate(this.commitMessage, request);
    try {
        Project existingProject = api.getProjectApi().getProject(localNamespace, localProjectName);
        RepositoryFile rf = new RepositoryFile();
        rf.setFilePath(localPath);
        rf.setContent(localContent);
        RepositoryFile result = api.getRepositoryFileApi().createFile(existingProject, rf, localBranch, localCommit);
        GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().logAction(gitlab.getName(), false, ActionType.Add, approvalID, workflow, "gitlab-file-" + existingProject.getNameWithNamespace() + "-file", localPath + " / " + result.getCommitId());
    } catch (GitLabApiException e) {
        throw new ProvisioningException("Error looking up project " + localNamespace + "/" + localProjectName, e);
    }
    return true;
}
Also used : GitlabUserProvider(com.tremolosecurity.unison.gitlab.provisioning.targets.GitlabUserProvider) Project(org.gitlab4j.api.models.Project) GitLabApi(org.gitlab4j.api.GitLabApi) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) Workflow(com.tremolosecurity.provisioning.core.Workflow) RepositoryFile(org.gitlab4j.api.models.RepositoryFile) GitLabApiException(org.gitlab4j.api.GitLabApiException)

Example 65 with Workflow

use of com.tremolosecurity.provisioning.core.Workflow in project OpenUnison by TremoloSecurity.

the class CreateProject 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");
    GitlabUserProvider gitlab = (GitlabUserProvider) GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().getTarget(this.targetName).getProvider();
    GitLabApi api = gitlab.getApi();
    String localNamespace = task.renderTemplate(this.namespace, request);
    String localName = task.renderTemplate(this.name, request);
    String localDescription = task.renderTemplate(this.description, request);
    try {
        try {
            Project existingProject = api.getProjectApi().getProject(localNamespace, localName);
            if (existingProject != null) {
                logger.warn("Project " + localNamespace + "/" + localName + " already exists, skipping");
                return true;
            }
        } catch (GitLabApiException e) {
            if (e.getHttpStatus() != 404) {
                throw new ProvisioningException("Error looking up project " + localNamespace + "/" + localName, e);
            }
        }
        Project projectSpec = new Project().withNamespace(api.getNamespaceApi().findNamespaces(localNamespace).get(0)).withName(localName).withDescription(localDescription).withIssuesEnabled(this.issuesEnabled).withMergeRequestsEnabled(this.mergeRequestsEnabled).withWikiEnabled(this.wikiEnabled).withSnippetsEnabled(this.snipitsEnabled).withVisibilityLevel(this.visibility);
        Project newProject = api.getProjectApi().createProject(projectSpec);
        GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().logAction(gitlab.getName(), false, ActionType.Add, approvalID, workflow, "gitlab-project-" + newProject.getNameWithNamespace() + "-name", newProject.getNameWithNamespace());
        // generate deployment key
        KeyPairGenerator generator;
        generator = KeyPairGenerator.getInstance("RSA");
        // or: generator = KeyPairGenerator.getInstance("DSA");
        generator.initialize(2048);
        KeyPair keyPair = generator.genKeyPair();
        String sshPubKey = "ssh-rsa " + Base64.encodeBase64String(encodePublicKey((RSAPublicKey) keyPair.getPublic())) + " openunison-deploy-key";
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        org.bouncycastle.openssl.PEMWriter genPrivKey = new org.bouncycastle.openssl.PEMWriter(new OutputStreamWriter(baos));
        genPrivKey.writeObject(keyPair.getPrivate());
        genPrivKey.close();
        String pem = new String(baos.toByteArray());
        api.getDeployKeysApi().addDeployKey(newProject, "openunison-deploy-key", sshPubKey, false);
        GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().logAction(gitlab.getName(), false, ActionType.Add, approvalID, workflow, "gitlab-project-" + newProject.getNameWithNamespace() + "-deploykey", "openunison-deploy-key");
        try {
            String base64PrivKey = java.util.Base64.getEncoder().encodeToString(pem.getBytes("UTF-8"));
            request.put("base64SshPrivateKey", base64PrivKey);
        } catch (UnsupportedEncodingException e) {
            throw new ProvisioningException("Could get key", e);
        }
        String gitUrl = newProject.getSshUrlToRepo();
        String prefix = gitUrl.substring(0, gitUrl.indexOf("@") + 1);
        String suffix = gitUrl.substring(gitUrl.indexOf(":"));
        String newGitUrl = new StringBuilder().append(prefix).append(this.gitSshHost).append(suffix).toString();
        request.put("gitSshInternalURL", newGitUrl);
        request.put("gitSshUrl", newProject.getSshUrlToRepo());
        request.put("gitPrivateKey", pem);
        request.put("newProjectJSON", newProject.toString());
        if (createWebHook) {
            String webhookToken = new GenPasswd(50).getPassword();
            String b64WebhookToken = java.util.Base64.getEncoder().encodeToString(webhookToken.getBytes("UTF-8"));
            request.put(webhookSecretRequestName, webhookToken);
            request.put("b64" + webhookSecretRequestName, b64WebhookToken);
            String webhookUrl = new StringBuilder().append("https://").append(localName).append(".").append(this.webhookDomainSuffix).toString();
            ProjectHook hook = new ProjectHook().withPushEvents(true).withPushEventsBranchFilter(this.webhookBranchFilter);
            api.getProjectApi().addHook(newProject, webhookUrl, hook, false, webhookToken);
            GlobalEntries.getGlobalEntries().getConfigManager().getProvisioningEngine().logAction(gitlab.getName(), false, ActionType.Add, approvalID, workflow, "gitlab-project-" + newProject.getNameWithNamespace() + "-webhook", this.webhookBranchFilter);
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not create project", e);
    }
    return true;
}
Also used : GenPasswd(com.tremolosecurity.provisioning.util.GenPasswd) GitLabApi(org.gitlab4j.api.GitLabApi) KeyPair(java.security.KeyPair) ProjectHook(org.gitlab4j.api.models.ProjectHook) Workflow(com.tremolosecurity.provisioning.core.Workflow) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GitLabApiException(org.gitlab4j.api.GitLabApiException) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) IOException(java.io.IOException) GitLabApiException(org.gitlab4j.api.GitLabApiException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) GitlabUserProvider(com.tremolosecurity.unison.gitlab.provisioning.targets.GitlabUserProvider) Project(org.gitlab4j.api.models.Project) RSAPublicKey(java.security.interfaces.RSAPublicKey) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) OutputStreamWriter(java.io.OutputStreamWriter)

Aggregations

Workflow (com.tremolosecurity.provisioning.core.Workflow)78 ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)68 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)32 IOException (java.io.IOException)30 UnsupportedEncodingException (java.io.UnsupportedEncodingException)22 ClientProtocolException (org.apache.http.client.ClientProtocolException)21 Attribute (com.tremolosecurity.saml.Attribute)19 ArrayList (java.util.ArrayList)18 LDAPException (com.novell.ldap.LDAPException)17 HashMap (java.util.HashMap)17 User (com.tremolosecurity.provisioning.core.User)16 HashSet (java.util.HashSet)15 ParseException (org.json.simple.parser.ParseException)14 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)12 JSONObject (org.json.simple.JSONObject)12 Gson (com.google.gson.Gson)11 LDAPEntry (com.novell.ldap.LDAPEntry)11 LDAPAttribute (com.novell.ldap.LDAPAttribute)10 GitLabApiException (org.gitlab4j.api.GitLabApiException)10 SQLException (java.sql.SQLException)9