Search in sources :

Example 1 with GatekeeperException

use of org.finra.gatekeeper.exception.GatekeeperException in project Gatekeeper by FINRAOS.

the class GrantAccessServiceTask method execute.

/**
 * This makes the calls (keypair, ssm, and email) for granting access.
 *
 * @param execution the Activiti object
 * @throws Exception for anything that goes wrong
 */
public void execute(DelegateExecution execution) throws Exception {
    if (execution.getVariable("attempts") == null) {
        execution.setVariable("attempts", 1);
    } else {
        execution.setVariable("attempts", (Integer) execution.getVariable("attempts") + 1);
    }
    AccessRequest accessRequest = (AccessRequest) execution.getVariable("accessRequest");
    logger.info("Granting Access to " + accessRequest);
    try {
        // Prepare parameters
        AWSEnvironment env = new AWSEnvironment(accessRequest.getAccount(), accessRequest.getRegion());
        logger.info("Environment for this access request is " + env.getAccount() + " ( " + env.getRegion() + " )");
        // bundle up the role -> db -> schema/table offerings
        Map<String, Map<RoleType, List<String>>> schemasForRequest = new HashMap<>();
        for (AWSRdsDatabase db : accessRequest.getAwsRdsInstances()) {
            schemasForRequest.put(db.getName(), databaseConnectionService.getAvailableSchemasForDb(db));
        }
        // Do all of this for each user in the request
        for (User u : accessRequest.getUsers()) {
            // have to apply the roles to each user in the request
            for (UserRole role : accessRequest.getRoles()) {
                // Generate keypair
                String password = passwordGenerationService.generatePassword();
                if (password == null) {
                    throw new GatekeeperException("Could not generate Password");
                }
                RoleType roleType = RoleType.valueOf(role.getRole().toUpperCase());
                Map<String, Boolean> createStatus = databaseConnectionService.grantAccess(accessRequest.getAwsRdsInstances(), u.getUserId(), roleType, password, accessRequest.getDays());
                if (createStatus.values().stream().allMatch(item -> item == Boolean.FALSE)) {
                    throw new GatekeeperException("Could not create user account on any DB instances");
                }
                // Send email with private key
                emailServiceWrapper.notifyOfCredentials(accessRequest, u, roleType, password, schemasForRequest);
            }
        }
    } catch (Exception e) {
        emailServiceWrapper.notifyAdminsOfFailure(accessRequest, e);
        execution.setVariable("requestStatus", RequestStatus.APPROVAL_ERROR);
        throw e;
    }
    if (execution.getVariable("requestStatus") == null) {
        execution.setVariable("requestStatus", RequestStatus.GRANTED);
    }
}
Also used : HashMap(java.util.HashMap) AWSEnvironment(org.finra.gatekeeper.services.aws.model.AWSEnvironment) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with GatekeeperException

use of org.finra.gatekeeper.exception.GatekeeperException in project Gatekeeper by FINRAOS.

the class MySQLDBConnection method createUser.

private void createUser(String address, String user, String password, RoleType role, String expirationTime) throws Exception {
    JdbcTemplate conn = connect(address);
    // 16 is the maximum length for a user in MySQL, if there's a user hitting this limit, a shorter suffix shall be used
    String userRole = getGkUserName(user, role);
    // revoke the user if they exist
    revokeAccess(user, role, address);
    logger.info("Creating User " + userRole + " if they dont already exist");
    boolean wasUserCreated = conn.execute(new MySqlStatement("CREATE USER " + userRole + " IDENTIFIED BY '" + password + "'"));
    logger.info(wasUserCreated ? "User " + userRole + " successfully created on database" + address : "Failed to create " + userRole + " on database " + address);
    List<String> schemasToGrant = getSchemasForDb(conn);
    logger.info("User " + userRole + " has role " + role + " granting him those privs");
    String privs;
    switch(role) {
        case READONLY:
            privs = "SELECT";
            break;
        case DATAFIX:
            privs = "SELECT, INSERT, DELETE, UPDATE";
            break;
        case DBA:
            privs = "SELECT, CREATE, ALTER, DROP ";
            break;
        default:
            throw new GatekeeperException("Unknown Role provided: " + role);
    }
    logger.info("Granting roles to all of the non mysql schemas (" + schemasToGrant + ")");
    schemasToGrant.forEach(schema -> {
        logger.info("Granting " + privs + " for " + userRole + " on " + schema);
        conn.execute(generateQuery(privs, userRole, schema));
        logger.info("Done!");
    });
    logger.info("Successfully Created " + userRole + " with " + role + " for the following schemas " + schemasToGrant);
}
Also used : JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException)

Example 3 with GatekeeperException

use of org.finra.gatekeeper.exception.GatekeeperException in project Gatekeeper by FINRAOS.

the class AwsSessionService method getRoleArn.

private String getRoleArn(String alias) throws GatekeeperException {
    Account account = accountInformationService.getAccountByAlias(alias);
    if (account == null) {
        logger.error("No account found with alias: " + alias);
        throw new GatekeeperException("No account found with alias: " + alias);
    }
    account.getAccountId();
    StringBuffer sb = new StringBuffer();
    sb.append("arn:aws:iam::");
    sb.append(account.getAccountId());
    sb.append(":role/");
    sb.append(roleToAssume);
    return sb.toString();
}
Also used : Account(org.finra.gatekeeper.common.services.account.model.Account) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException)

Example 4 with GatekeeperException

use of org.finra.gatekeeper.exception.GatekeeperException in project Gatekeeper by FINRAOS.

the class GrantAccessServiceTask method createLinuxUser.

/**
 * Grants access to users on Linux instances. Creates a key pair, sends private to user and public key off
 * to SSM along with user and instance
 * @param accessRequest The access request being handled. Contains the user info
 * @param env The environment object used by the ssm document for client creation
 * @param instances the instances that the user is being created on
 * @param platform - used to determine document, should always be Linux on this call
 * @throws GatekeeperException
 */
private void createLinuxUser(AccessRequest accessRequest, AWSEnvironment env, List<String> instances, String platform) throws GatekeeperException {
    Map<String, Boolean> userStatus = new HashMap<>();
    for (User u : accessRequest.getUsers()) {
        // Generate keypair
        KeyPair kp = keypairService.createKeypair();
        if (kp == null) {
            throw new GatekeeperException("Could not generate Keypair");
        }
        // Form public and private key strings
        PublicKey publicKey = kp.getPublic();
        String publicKeyString = keypairService.getPublicKeyString(publicKey);
        if (publicKeyString == null) {
            throw new GatekeeperException("Could not encode public key");
        }
        PrivateKey privKey = kp.getPrivate();
        String privateKeyString = keypairService.getPEM(privKey);
        // Call SSM to create account (one call does all instances)
        Map<String, String> createStatus = ssmService.createUserAccount(env, instances, u.getUserId(), publicKeyString, platform);
        userStatus.put(u.getName(), createStatus.containsValue(CommandStatus.Success.toString()));
        // Send email with private key
        if (userStatus.get(u.getName())) {
            emailServiceWrapper.notifyOfCredentials(accessRequest, u, privateKeyString, createStatus);
        }
    }
    if (!userStatus.containsValue(true)) {
        throw new GatekeeperException("Could not create user account on one or more " + platform + " instances");
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) PublicKey(java.security.PublicKey) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException)

Example 5 with GatekeeperException

use of org.finra.gatekeeper.exception.GatekeeperException in project Gatekeeper by FINRAOS.

the class AccessRequestService method storeAccessRequest.

/**
 * Store the Access Request and either grant or require approval. Before the access request is written to the database the users
 * provided will be checked against each DB to make sure that the users can be successfully created.
 *
 * @param request
 * @return AccessRequest - if the user/db check succeeds, Map - if theres any
 * @throws GatekeeperException
 */
public AccessRequestCreationResponse storeAccessRequest(AccessRequestWrapper request) throws GatekeeperException {
    GatekeeperUserEntry requestor = gatekeeperRoleService.getUserProfile();
    Integer maxDays = overridePolicy.getMaxDaysForRequest(gatekeeperRoleService.getRole(), request.getRoles(), request.getAccountSdlc());
    if (request.getDays() > maxDays) {
        throw new GatekeeperException("Days requested (" + request.getDays() + ") exceeded the maximum of " + maxDays + " for roles " + request.getRoles() + " on account with SDLC " + request.getAccountSdlc());
    }
    // throw gk in front of all the user id's
    request.getUsers().forEach(u -> u.setUserId("gk_" + u.getUserId()));
    Account theAccount = accountInformationService.getAccountByAlias(request.getAccount());
    AWSEnvironment environment = new AWSEnvironment(theAccount.getAlias().toUpperCase(), request.getRegion());
    AccessRequest accessRequest = new AccessRequest().setAccount(request.getAccount().toUpperCase()).setAccountSdlc(request.getAccountSdlc()).setRegion(request.getRegion()).setDays(request.getDays()).setRequestorId(requestor.getUserId()).setRequestorName(requestor.getName()).setRequestorEmail(requestor.getEmail()).setUsers(request.getUsers()).setAwsRdsInstances(request.getInstances()).setRequestReason(request.getRequestReason()).setRoles(request.getRoles());
    logger.info("Checking Users associated with this access request");
    Map<String, List<String>> checkResult;
    try {
        checkResult = databaseConnectionService.checkUsersAndDbs(request.getRoles(), request.getUsers(), request.getInstances());
    } catch (Exception e) {
        throw new GatekeeperException("Unable to verify the Users for the provided databases");
    }
    if (!checkResult.isEmpty()) {
        return new AccessRequestCreationResponse(AccessRequestCreationOutcome.NOT_CREATED_USER_ISSUE, checkResult);
    }
    logger.info("Storing Access Request");
    accessRequestRepository.save(accessRequest);
    logger.info("Access Request stored with ID: " + accessRequest.getId());
    // Kick off the activiti workflow
    Map<String, Object> variables = new HashMap<>();
    variables.put("accessRequest", accessRequest);
    runtimeService.startProcessInstanceByKey("gatekeeperAccessRequest", variables);
    // Verify that we started a new process instance
    logger.info("Number of process instances: " + runtimeService.createProcessInstanceQuery().count());
    return new AccessRequestCreationResponse(AccessRequestCreationOutcome.CREATED, accessRequest);
}
Also used : Account(org.finra.gatekeeper.common.services.account.model.Account) AWSEnvironment(org.finra.gatekeeper.services.aws.model.AWSEnvironment) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException) GatekeeperException(org.finra.gatekeeper.exception.GatekeeperException) GatekeeperUserEntry(org.finra.gatekeeper.common.services.user.model.GatekeeperUserEntry) AccessRequestCreationResponse(org.finra.gatekeeper.services.accessrequest.model.response.AccessRequestCreationResponse)

Aggregations

GatekeeperException (org.finra.gatekeeper.exception.GatekeeperException)5 HashMap (java.util.HashMap)2 Account (org.finra.gatekeeper.common.services.account.model.Account)2 AWSEnvironment (org.finra.gatekeeper.services.aws.model.AWSEnvironment)2 KeyPair (java.security.KeyPair)1 PrivateKey (java.security.PrivateKey)1 PublicKey (java.security.PublicKey)1 Map (java.util.Map)1 GatekeeperUserEntry (org.finra.gatekeeper.common.services.user.model.GatekeeperUserEntry)1 AccessRequestCreationResponse (org.finra.gatekeeper.services.accessrequest.model.response.AccessRequestCreationResponse)1 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)1