Search in sources :

Example 6 with ProvisioningException

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

the class OpenShiftTarget method findUser.

@Override
public User findUser(String userID, Set<String> attributes, Map<String, Object> request) throws ProvisioningException {
    try {
        User user = null;
        String token = this.getAuthToken();
        // users aren't bound to groups and there's no way to directly lookup what groups a user has
        // so we need to read all groups and see if the user exists
        ArrayList<String> groupsForUser = new ArrayList<String>();
        HttpCon con = this.createClient();
        StringBuffer b = new StringBuffer();
        com.tremolosecurity.unison.openshiftv3.model.List<GroupItem> groupList = null;
        try {
            String json = callWS(token, con, "/apis/user.openshift.io/v1/groups");
            Gson gson = new Gson();
            TypeToken<com.tremolosecurity.unison.openshiftv3.model.List<GroupItem>> tokenType = new TypeToken<com.tremolosecurity.unison.openshiftv3.model.List<GroupItem>>() {
            };
            groupList = gson.fromJson(json, tokenType.getType());
            b.append("/apis/user.openshift.io/v1/users/").append(userID);
            json = callWS(token, con, b.toString());
            com.tremolosecurity.unison.openshiftv3.model.users.User osUser = gson.fromJson(json, com.tremolosecurity.unison.openshiftv3.model.users.User.class);
            if (osUser.getKind().equalsIgnoreCase("User")) {
                user = new User(userID);
                for (String attrName : osUser.getMetadata().keySet()) {
                    if (!attrName.equalsIgnoreCase("fullName") && attributes.contains(attrName)) {
                        user.getAttribs().put(attrName, new Attribute(attrName, (String) osUser.getMetadata().get(attrName)));
                    }
                }
                if (attributes.contains("fullName") && osUser.getFullName() != null) {
                    user.getAttribs().put("fullName", new Attribute("fullName", osUser.getFullName()));
                }
            }
        } finally {
            if (con != null) {
                con.getBcm().shutdown();
            }
        }
        for (GroupItem group : groupList.getItems()) {
            if (group.getUsers() != null && group.getUsers().contains(userID)) {
                groupsForUser.add((String) group.getMetadata().get("name"));
            }
        }
        if (groupsForUser.isEmpty()) {
            return user;
        } else {
            if (user == null) {
                // user = new User(userID);
                return null;
            }
            user.getGroups().addAll(groupsForUser);
            return user;
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not load " + userID, e);
    }
}
Also used : User(com.tremolosecurity.provisioning.core.User) Attribute(com.tremolosecurity.saml.Attribute) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) KeyStoreException(java.security.KeyStoreException) StreamException(org.cryptacular.StreamException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KeyManagementException(java.security.KeyManagementException) JoseException(org.jose4j.lang.JoseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) EncodingException(org.cryptacular.EncodingException) IOException(java.io.IOException) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) TypeToken(com.google.gson.reflect.TypeToken) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) GroupItem(com.tremolosecurity.unison.openshiftv3.model.groups.GroupItem) List(java.util.List) ArrayList(java.util.ArrayList)

Example 7 with ProvisioningException

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

the class OpenShiftTarget method getAuthToken.

public String getAuthToken() throws Exception {
    HttpCon con = this.createClient();
    try {
        if (!this.useToken) {
            StringBuffer b = new StringBuffer();
            b.append(this.getUrl()).append("/oauth/authorize?response_type=token&client_id=openshift-challenging-client");
            HttpGet get = new HttpGet(b.toString());
            b.setLength(0);
            b.append(this.userName).append(':').append(this.password);
            String b64 = Base64.encodeBase64String(b.toString().getBytes("UTF-8"));
            b.setLength(0);
            b.append("Basic ").append(b64.substring(0, b64.length() - 2));
            get.addHeader(new BasicHeader("Authorization", b.toString()));
            HttpResponse resp = con.getHttp().execute(get);
            String token = "";
            if (resp.getStatusLine().getStatusCode() == 302) {
                String url = resp.getFirstHeader("Location").getValue();
                int start = url.indexOf("access_token") + "access_token=".length();
                int end = url.indexOf("&", start + 1);
                token = url.substring(start, end);
            } else {
                throw new Exception("Unable to obtain token : " + resp.getStatusLine().toString());
            }
            return token;
        } else {
            switch(this.tokenType) {
                case NONE:
                    return null;
                case TOKENAPI:
                    this.checkProjectedToken();
                case LEGACY:
                case STATIC:
                    return this.osToken;
                case OIDC:
                    return this.generateOidcToken();
                default:
                    throw new ProvisioningException("Unknown tokenType");
            }
        }
    } finally {
        if (con != null) {
            con.getBcm().shutdown();
        }
    }
}
Also used : HttpCon(com.tremolosecurity.provisioning.util.HttpCon) HttpGet(org.apache.http.client.methods.HttpGet) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicHeader(org.apache.http.message.BasicHeader) KeyStoreException(java.security.KeyStoreException) StreamException(org.cryptacular.StreamException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KeyManagementException(java.security.KeyManagementException) JoseException(org.jose4j.lang.JoseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) EncodingException(org.cryptacular.EncodingException) IOException(java.io.IOException)

Example 8 with ProvisioningException

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

the class LoadApplicationsFromK8s method addObject.

@Override
public void addObject(TremoloType cfg, JSONObject item) throws ProvisioningException {
    String rawJson = item.toJSONString();
    StringBuffer b = new StringBuffer();
    b.setLength(0);
    OpenUnisonConfigLoader.integrateIncludes(b, rawJson);
    try {
        JSONObject newRoot = (JSONObject) new JSONParser().parse(b.toString());
        JSONObject metadata = (JSONObject) newRoot.get("metadata");
        if (metadata == null) {
            throw new ProvisioningException("No metadata");
        }
        String name = (String) metadata.get("name");
        logger.info("Adding application " + name);
        try {
            synchronized (GlobalEntries.getGlobalEntries().getConfigManager()) {
                ApplicationType app = this.createApplication(item, name);
                GlobalEntries.getGlobalEntries().getConfigManager().initializeUrls(GlobalEntries.getGlobalEntries().getConfigManager().addApplication(app));
            }
        } catch (Exception e) {
            logger.warn("Could not initialize application " + name, e);
        }
    } catch (ParseException e) {
        throw new ProvisioningException("Could not parse application", e);
    }
}
Also used : ApplicationType(com.tremolosecurity.config.xml.ApplicationType) JSONObject(org.json.simple.JSONObject) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) ParseException(org.json.simple.parser.ParseException)

Example 9 with ProvisioningException

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

the class OpenShiftTarget method init.

@Override
public void init(Map<String, Attribute> cfg, ConfigManager cfgMgr, String name) throws ProvisioningException {
    this.url = this.loadOption("url", cfg, false);
    this.useDefaultCaPath = false;
    String tmpUseToken = this.loadOptionalAttributeValue("useToken", "Use Token", cfg, null);
    this.useToken = tmpUseToken != null && tmpUseToken.equalsIgnoreCase("true");
    if (!useToken) {
        this.userName = this.loadOption("userName", cfg, false);
        this.password = this.loadOption("password", cfg, true);
    } else {
        String localTokenType = this.loadOptionalAttributeValue("tokenType", "tokenType", cfg, null);
        if (localTokenType == null || localTokenType.trim().isEmpty()) {
            localTokenType = "LEGACY";
        }
        this.tokenType = TokenType.valueOf(localTokenType.toUpperCase());
        switch(tokenType) {
            case STATIC:
                this.osToken = this.loadOptionalAttributeValue("token", "Token", cfg, "***************************");
                break;
            case LEGACY:
                try {
                    this.osToken = new String(Files.readAllBytes(Paths.get("/var/run/secrets/kubernetes.io/serviceaccount/token")), StandardCharsets.UTF_8);
                } catch (IOException e) {
                    throw new ProvisioningException("Could not load token", e);
                }
                // check if token is projected, starting in 1.21 this is the default
                int firstPeriod = this.osToken.indexOf('.');
                int lastPeriod = this.osToken.lastIndexOf('.');
                String json = new String(Base64.decodeBase64(this.osToken.substring(firstPeriod + 1, lastPeriod)));
                try {
                    JSONObject claims = (JSONObject) new JSONParser().parse(json);
                    if (claims.containsKey("exp")) {
                        logger.info("Default token is projected, switching to TokenAPI");
                        this.tokenType = TokenType.TOKENAPI;
                        this.tokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token";
                        this.useDefaultCaPath = true;
                        this.checkProjectedToken();
                    }
                } catch (ParseException e1) {
                    throw new ProvisioningException("Could not load token", e1);
                }
                break;
            case TOKENAPI:
                this.tokenPath = this.loadOption("tokenPath", cfg, false);
                this.checkProjectedToken();
                break;
            case NONE:
                break;
            case OIDC:
                this.initRemoteOidc(cfg, cfgMgr, localTokenType);
                break;
        }
        if (this.url.isEmpty()) {
            this.localToken = true;
            String certAlias = this.loadOptionalAttributeValue("caCertAlias", "caCertAlias", cfg, null);
            if (certAlias == null) {
                certAlias = "k8s-master";
            }
            try {
                logger.info("Cert Alias Storing - '" + certAlias + "'");
                X509Certificate cert = null;
                if (tokenType == TokenType.LEGACY || this.useDefaultCaPath) {
                    cert = CertUtil.readCertificate("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");
                } else if (tokenType == TokenType.TOKENAPI) {
                    // -\("/)/-
                    cert = CertUtil.readCertificate(this.loadOption("certPath", cfg, false));
                }
                logger.info("Certificate - " + cert);
                cfgMgr.getKeyStore().setCertificateEntry(certAlias, cert);
            } catch (KeyStoreException | EncodingException | StreamException e) {
                throw new ProvisioningException("Could not load ca cert", e);
            }
        }
    }
    this.cfgMgr = cfgMgr;
    this.name = name;
    if (cfg.get("certificate") != null) {
        String certificate = cfg.get("certificate").getValues().get(0);
        try {
            X509Certificate cert = this.pem2cert(certificate);
            cfgMgr.getKeyStore().setCertificateEntry("k8s-certificate-" + this.name, cert);
        } catch (Exception e) {
            throw new ProvisioningException("Could not load certificate", e);
        }
    }
    try {
        cfgMgr.buildHttpConfig();
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new ProvisioningException("Could not rebuild http configuration", e);
    }
    this.label = this.loadOptionalAttributeValue("label", "label", cfg, null);
    if (this.label == null) {
        this.label = this.name;
    }
    this.gitUrl = this.loadOptionalAttributeValue("gitUrl", "gitUrl", cfg, null);
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) EncodingException(org.cryptacular.EncodingException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) StreamException(org.cryptacular.StreamException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KeyManagementException(java.security.KeyManagementException) JoseException(org.jose4j.lang.JoseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) EncodingException(org.cryptacular.EncodingException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) StreamException(org.cryptacular.StreamException) JSONObject(org.json.simple.JSONObject) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 10 with ProvisioningException

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

the class OpenShiftTarget method addGroup.

@Override
public void addGroup(String name, Map<String, String> additionalAttributes, User user, Map<String, Object> request) throws ProvisioningException {
    HttpCon con = null;
    int approvalID = 0;
    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }
    Workflow workflow = (Workflow) request.get("WORKFLOW");
    try {
        String token = this.getAuthToken();
        con = this.createClient();
        Gson gson = new Gson();
        // first lets see if the group exists
        StringBuilder sb = new StringBuilder();
        sb.append("/apis/user.openshift.io/v1/groups/").append(name);
        com.tremolosecurity.unison.openshiftv3.model.groups.Group group = new com.tremolosecurity.unison.openshiftv3.model.groups.Group();
        group.setKind("Group");
        group.setApiVersion("user.openshift.io/v1");
        group.setMetadata(new HashMap<String, Object>());
        group.getMetadata().put("name", name);
        group.getMetadata().put("creationTimestamp", null);
        group.setUsers(null);
        String jsonInput = gson.toJson(group);
        if (!this.isObjectExists(token, con, "/apis/user.openshift.io/v1/groups", jsonInput)) {
            String json = this.callWSPost(token, con, "/apis/user.openshift.io/v1/groups", jsonInput);
            Response resp = gson.fromJson(json, Response.class);
            if (resp.getKind().equalsIgnoreCase("Group")) {
                this.cfgMgr.getProvisioningEngine().logAction(name, true, ActionType.Add, approvalID, workflow, "group-object", name);
            } else {
                throw new ProvisioningException("Unknown response : '" + json + "'");
            }
        }
    } catch (Exception e) {
        throw new ProvisioningException("Could not load group", e);
    } finally {
        if (con != null) {
            con.getBcm().close();
        }
    }
}
Also used : UserStoreProviderWithAddGroup(com.tremolosecurity.provisioning.core.UserStoreProviderWithAddGroup) Workflow(com.tremolosecurity.provisioning.core.Workflow) Gson(com.google.gson.Gson) KeyStoreException(java.security.KeyStoreException) StreamException(org.cryptacular.StreamException) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) KeyManagementException(java.security.KeyManagementException) JoseException(org.jose4j.lang.JoseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ParseException(org.json.simple.parser.ParseException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) EncodingException(org.cryptacular.EncodingException) IOException(java.io.IOException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Response(com.tremolosecurity.unison.openshiftv3.model.Response) HttpResponse(org.apache.http.HttpResponse) HttpCon(com.tremolosecurity.provisioning.util.HttpCon) ProvisioningException(com.tremolosecurity.provisioning.core.ProvisioningException) JSONObject(org.json.simple.JSONObject)

Aggregations

ProvisioningException (com.tremolosecurity.provisioning.core.ProvisioningException)265 IOException (java.io.IOException)91 HttpCon (com.tremolosecurity.provisioning.util.HttpCon)79 Attribute (com.tremolosecurity.saml.Attribute)75 Workflow (com.tremolosecurity.provisioning.core.Workflow)67 JSONObject (org.json.simple.JSONObject)67 UnsupportedEncodingException (java.io.UnsupportedEncodingException)57 ClientProtocolException (org.apache.http.client.ClientProtocolException)57 LDAPException (com.novell.ldap.LDAPException)56 ArrayList (java.util.ArrayList)54 ParseException (org.json.simple.parser.ParseException)51 HashMap (java.util.HashMap)50 Gson (com.google.gson.Gson)45 User (com.tremolosecurity.provisioning.core.User)44 JSONParser (org.json.simple.parser.JSONParser)42 SQLException (java.sql.SQLException)39 LDAPAttribute (com.novell.ldap.LDAPAttribute)33 LDAPEntry (com.novell.ldap.LDAPEntry)33 LDAPSearchResults (com.novell.ldap.LDAPSearchResults)30 OpenShiftTarget (com.tremolosecurity.unison.openshiftv3.OpenShiftTarget)28