Search in sources :

Example 21 with CredData

use of org.ow2.proactive.authentication.crypto.CredData in project scheduling by ow2-proactive.

the class AuthenticationImpl method authenticate.

/**
 * Performs login.
 *
 * @param cred encrypted username and password
 * @return the name of the user logged
 * @throws LoginException if username or password is incorrect.
 */
public Subject authenticate(Credentials cred) throws LoginException {
    if (activated == false) {
        throw new LoginException("Authentication active object is not activated.");
    }
    CredData credentials = null;
    try {
        credentials = cred.decrypt(privateKeyPath);
    } catch (KeyException e) {
        throw new LoginException("Could not decrypt credentials: " + e);
    }
    String username = credentials.getLogin();
    String password = credentials.getPassword();
    if (username == null || username.equals("")) {
        throw new LoginException("Bad user name (user is null or empty)");
    }
    try {
        // Verify that this user//password can connect to this existing scheduler
        getLogger().info(username + " is trying to connect");
        Map<String, Object> params = new HashMap<>(4);
        // user name to check
        params.put("username", username);
        // password to check
        params.put("pw", password);
        // Load LoginContext according to login method defined in jaas.config
        LoginContext lc = new LoginContext(getLoginMethod(), new NoCallbackHandler(params));
        lc.login();
        getLogger().info("User " + username + " logged successfully");
        return lc.getSubject();
    } catch (LoginException e) {
        getLogger().info(e.getMessage());
        // user about the reason of non authentication
        throw new LoginException("Authentication failed");
    }
}
Also used : LoginContext(javax.security.auth.login.LoginContext) HashMap(java.util.HashMap) CredData(org.ow2.proactive.authentication.crypto.CredData) LoginException(javax.security.auth.login.LoginException) PAActiveObject(org.objectweb.proactive.api.PAActiveObject) KeyException(java.security.KeyException)

Example 22 with CredData

use of org.ow2.proactive.authentication.crypto.CredData in project scheduling by ow2-proactive.

the class CreateCredentials method main.

/**
 * Entry point
 *
 * @see org.ow2.proactive.authentication.crypto.Credentials
 * @param args arguments, try '-h' for help
 * @throws IOException
 * @throws ParseException
 */
public static void main(String[] args) throws IOException, ParseException {
    SecurityManagerConfigurator.configureSecurityManager(CreateCredentials.class.getResource("/all-permissions.security.policy").toString());
    Console console = System.console();
    /**
     * default values
     */
    boolean interactive = true;
    String pubKeyPath = null;
    PublicKey pubKey = null;
    String login = null;
    String pass = null;
    String keyfile = null;
    String cipher = "RSA/ECB/PKCS1Padding";
    String path = Credentials.getCredentialsPath();
    String rm = null;
    String scheduler = null;
    String url = null;
    Options options = new Options();
    Option opt = new Option("h", "help", false, "Display this help");
    opt.setRequired(false);
    options.addOption(opt);
    OptionGroup group = new OptionGroup();
    group.setRequired(false);
    opt = new Option("F", "file", true, "Public key path on the local filesystem [default:" + Credentials.getPubKeyPath() + "]");
    opt.setArgName("PATH");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);
    opt = new Option("R", "rm", true, "Request the public key to the Resource Manager at URL");
    opt.setArgName("URL");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);
    opt = new Option("S", "scheduler", true, "Request the public key to the Scheduler at URL");
    opt.setArgName("URL");
    opt.setArgs(1);
    opt.setRequired(false);
    group.addOption(opt);
    options.addOptionGroup(group);
    opt = new Option("l", "login", true, "Generate credentials for this specific user, will be asked interactively if not specified");
    opt.setArgName("LOGIN");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("p", "password", true, "Use this password, will be asked interactively if not specified");
    opt.setArgName("PWD");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("k", "keyfile", true, "Use specified ssh private key, asked interactively if specified without PATH, not specified otherwise.");
    opt.setArgName("PATH");
    opt.setOptionalArg(true);
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("o", "output", true, "Output the resulting credentials to the specified file [default:" + path + "]");
    opt.setArgName("PATH");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("c", "cipher", true, "Use specified cipher parameters, need to be compatible with the specified key [default:" + cipher + "]");
    opt.setArgName("PARAMS");
    opt.setArgs(1);
    opt.setRequired(false);
    options.addOption(opt);
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(newline + "ERROR : " + e.getMessage() + newline);
        System.out.println("type -h or --help to display help screen");
        System.exit(1);
    }
    if (cmd.hasOption("help")) {
        displayHelp(options);
    }
    if (cmd.hasOption("file")) {
        pubKeyPath = cmd.getOptionValue("file");
    }
    if (cmd.hasOption("rm")) {
        rm = cmd.getOptionValue("rm");
    }
    if (cmd.hasOption("scheduler")) {
        scheduler = cmd.getOptionValue("scheduler");
    }
    if (cmd.hasOption("login")) {
        login = cmd.getOptionValue("login");
    }
    if (cmd.hasOption("password")) {
        pass = cmd.getOptionValue("password");
    }
    if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
        keyfile = cmd.getOptionValue("keyfile");
    }
    if (cmd.hasOption("output")) {
        path = cmd.getOptionValue("output");
    }
    if (cmd.hasOption("cipher")) {
        cipher = cmd.getOptionValue("cipher");
    }
    int acc = 0;
    if (pubKeyPath != null) {
        acc++;
    }
    if (scheduler != null) {
        url = URIBuilder.buildURI(Connection.normalize(scheduler), "SCHEDULER").toString();
        acc++;
    }
    if (rm != null) {
        url = URIBuilder.buildURI(Connection.normalize(rm), "RMAUTHENTICATION").toString();
        acc++;
    }
    if (acc > 1) {
        System.out.println("--rm, --scheduler and --file arguments cannot be combined.");
        System.out.println("try -h for help.");
        System.exit(1);
    }
    if (url != null) {
        try {
            Connection<AuthenticationImpl> conn = new Connection<AuthenticationImpl>(AuthenticationImpl.class) {

                public Logger getLogger() {
                    return Logger.getLogger("pa.scheduler.credentials");
                }
            };
            AuthenticationImpl auth = conn.connect(url);
            pubKey = auth.getPublicKey();
        } catch (Exception e) {
            System.err.println("ERROR : Could not retrieve public key from '" + url + "'");
            e.printStackTrace();
            System.exit(3);
        }
        System.out.println("Successfully obtained public key from " + url + newline);
    } else if (pubKeyPath != null) {
        try {
            pubKey = Credentials.getPublicKey(pubKeyPath);
        } catch (KeyException e) {
            System.err.println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
            System.exit(4);
        }
    } else {
        System.out.println("No public key specified, attempting to retrieve it from default location.");
        pubKeyPath = Credentials.getPubKeyPath();
        try {
            pubKey = Credentials.getPublicKey(pubKeyPath);
        } catch (KeyException e) {
            System.err.println("ERROR : Could not retrieve public key from '" + pubKeyPath + "' (no such file)");
            System.exit(5);
        }
    }
    if (login != null && pass != null && (!cmd.hasOption("keyfile") || cmd.getOptionValues("keyfile") != null)) {
        System.out.println("Running in non-interactive mode." + newline);
        interactive = false;
    } else {
        System.out.println("Running in interactive mode.");
    }
    if (interactive) {
        System.out.println("Please enter Scheduler credentials,");
        System.out.println("they will be stored encrypted on disk for future logins." + newline);
        System.out.print("login: ");
        if (login == null) {
            login = console.readLine();
        } else {
            System.out.println(login);
        }
        System.out.print("password: ");
        if (pass == null) {
            pass = new String(console.readPassword());
        } else {
            System.out.println("*******");
        }
        System.out.print("keyfile: ");
        if (!cmd.hasOption("keyfile")) {
            System.out.println("no key file specified");
        } else if (cmd.hasOption("keyfile") && cmd.getOptionValues("keyfile") != null) {
            System.out.println(keyfile);
        } else {
            keyfile = console.readLine();
        }
    }
    try {
        CredData credData;
        if (keyfile != null && keyfile.length() > 0) {
            byte[] keyfileContent = FileToBytesConverter.convertFileToByteArray(new File(keyfile));
            credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass, keyfileContent);
        } else {
            System.out.println("--> Ignoring keyfile, credential does not contain SSH key");
            credData = new CredData(CredData.parseLogin(login), CredData.parseDomain(login), pass);
        }
        Credentials cred = Credentials.createCredentials(credData, pubKey, cipher);
        cred.writeToDisk(path);
    } catch (FileNotFoundException e) {
        System.err.println("ERROR : Could not retrieve ssh private key from '" + keyfile + "' (no such file)");
        System.exit(6);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(7);
    }
    System.out.println("Successfully stored encrypted credentials on disk at :");
    System.out.println("\t" + path);
    System.exit(0);
}
Also used : Options(org.apache.commons.cli.Options) PublicKey(java.security.PublicKey) Connection(org.ow2.proactive.authentication.Connection) FileNotFoundException(java.io.FileNotFoundException) KeyException(java.security.KeyException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.apache.commons.cli.ParseException) KeyException(java.security.KeyException) AuthenticationImpl(org.ow2.proactive.authentication.AuthenticationImpl) CommandLine(org.apache.commons.cli.CommandLine) OptionGroup(org.apache.commons.cli.OptionGroup) Console(java.io.Console) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) File(java.io.File) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 23 with CredData

use of org.ow2.proactive.authentication.crypto.CredData in project scheduling by ow2-proactive.

the class TimedDoTaskAction method createAndSetCredentials.

private void createAndSetCredentials() throws KeyException, NoSuchAlgorithmException {
    CredData decryptedUserCredentials = job.getCredentials().decrypt(corePrivateKey);
    enrichWithThirdPartyCredentials(decryptedUserCredentials);
    PublicKey nodePublicKey = launcher.generatePublicKey();
    Credentials nodeEncryptedUserCredentials = Credentials.createCredentials(decryptedUserCredentials, nodePublicKey);
    task.getExecutableContainer().setCredentials(nodeEncryptedUserCredentials);
}
Also used : PublicKey(java.security.PublicKey) CredData(org.ow2.proactive.authentication.crypto.CredData) Credentials(org.ow2.proactive.authentication.crypto.Credentials)

Example 24 with CredData

use of org.ow2.proactive.authentication.crypto.CredData in project scheduling by ow2-proactive.

the class RMProxyActiveObject method handleCleaningScript.

/**
 * Execute the given script on the given node.
 * Also register a callback on {@link #cleanCallBack(Future, NodeSet)} method when script has returned.
 * @param nodes           the nodeset on which to start the script
 * @param cleaningScript the script to be executed
 * @param variables
 * @param genericInformation
 * @param taskId
 * @param creds credentials with CredData containing third party credentials
 */
private void handleCleaningScript(NodeSet nodes, Script<?> cleaningScript, VariablesMap variables, Map<String, String> genericInformation, TaskId taskId, Credentials creds) {
    TaskLogger instance = TaskLogger.getInstance();
    try {
        this.nodesTaskId.put(nodes, taskId);
        // create a decrypter to access scheduler and retrieve Third Party User Credentials
        String privateKeyPath = PASchedulerProperties.getAbsolutePath(PASchedulerProperties.SCHEDULER_AUTH_PRIVKEY_PATH.getValueAsString());
        Decrypter decrypter = new Decrypter(Credentials.getPrivateKey(privateKeyPath));
        decrypter.setCredentials(creds);
        HashMap<String, Serializable> dictionary = new HashMap<>();
        dictionary.putAll(variables.getScriptMap());
        dictionary.putAll(variables.getInheritedMap());
        dictionary.putAll(variables.getPropagatedVariables());
        dictionary.putAll(variables.getScopeMap());
        // start handler for binding
        ScriptHandler handler = ScriptLoader.createHandler(nodes.get(0));
        VariablesMap resolvedMap = new VariablesMap();
        resolvedMap.setInheritedMap(VariableSubstitutor.resolveVariables(variables.getInheritedMap(), dictionary));
        resolvedMap.setScopeMap(VariableSubstitutor.resolveVariables(variables.getScopeMap(), dictionary));
        handler.addBinding(SchedulerConstants.VARIABLES_BINDING_NAME, (Serializable) resolvedMap);
        handler.addBinding(SchedulerConstants.GENERIC_INFO_BINDING_NAME, (Serializable) genericInformation);
        // retrieve scheduler URL to bind with schedulerapi, globalspaceapi, and userspaceapi
        String schedulerUrl = PASchedulerProperties.SCHEDULER_REST_URL.getValueAsString();
        logger.debug("Binding schedulerapi...");
        SchedulerNodeClient client = new SchedulerNodeClient(decrypter, schedulerUrl);
        handler.addBinding(SchedulerConstants.SCHEDULER_CLIENT_BINDING_NAME, (Serializable) client);
        logger.debug("Binding globalspaceapi...");
        RemoteSpace globalSpaceClient = new DataSpaceNodeClient(client, IDataSpaceClient.Dataspace.GLOBAL, schedulerUrl);
        handler.addBinding(SchedulerConstants.DS_GLOBAL_API_BINDING_NAME, (Serializable) globalSpaceClient);
        logger.debug("Binding userspaceapi...");
        RemoteSpace userSpaceClient = new DataSpaceNodeClient(client, IDataSpaceClient.Dataspace.USER, schedulerUrl);
        handler.addBinding(SchedulerConstants.DS_USER_API_BINDING_NAME, (Serializable) userSpaceClient);
        logger.debug("Binding credentials...");
        Map<String, String> resolvedThirdPartyCredentials = VariableSubstitutor.filterAndUpdate(decrypter.decrypt().getThirdPartyCredentials(), dictionary);
        handler.addBinding(SchedulerConstants.CREDENTIALS_VARIABLE, (Serializable) resolvedThirdPartyCredentials);
        ScriptResult<?> future = handler.handle(cleaningScript);
        try {
            PAEventProgramming.addActionOnFuture(future, "cleanCallBack", nodes);
        } catch (IllegalArgumentException e) {
            // TODO - linked to PROACTIVE-936 -> IllegalArgumentException is raised if method name is unknown
            // should be replaced by checked exception
            instance.error(taskId, "ERROR : Callback method won't be executed, node won't be released. This is a critical state, check the callback method name", e);
        }
        instance.info(taskId, "Cleaning Script started on node " + nodes.get(0).getNodeInformation().getURL());
    } catch (Exception e) {
        // if active object cannot be created or script has failed
        instance.error(taskId, "Error while starting cleaning script for task " + taskId + " on " + nodes.get(0), e);
        releaseNodes(nodes).booleanValue();
    }
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SchedulerNodeClient(org.ow2.proactive.scheduler.task.client.SchedulerNodeClient) Decrypter(org.ow2.proactive.scheduler.task.utils.Decrypter) LoginException(javax.security.auth.login.LoginException) TaskLogger(org.ow2.proactive.scheduler.util.TaskLogger) RemoteSpace(org.ow2.proactive.scheduler.common.task.dataspaces.RemoteSpace) VariablesMap(org.ow2.proactive.scheduler.task.utils.VariablesMap) DataSpaceNodeClient(org.ow2.proactive.scheduler.task.client.DataSpaceNodeClient) ScriptHandler(org.ow2.proactive.scripting.ScriptHandler)

Example 25 with CredData

use of org.ow2.proactive.authentication.crypto.CredData in project scheduling by ow2-proactive.

the class AuthenticationTest method loginAsUserIncorrectPassword.

private void loginAsUserIncorrectPassword(SchedulerAuthenticationInterface auth, PublicKey pubKey) {
    log("Test 4");
    log("Trying to authorized as a user with incorrect user name and password");
    try {
        Credentials cred = Credentials.createCredentials(new CredData(TestUsers.USER.username, "b"), pubKey);
        auth.login(cred);
        fail("Error: successful authentication");
    } catch (Exception e) {
        log("Passed: expected error " + e.getMessage());
    }
}
Also used : CredData(org.ow2.proactive.authentication.crypto.CredData) Credentials(org.ow2.proactive.authentication.crypto.Credentials) LoginException(javax.security.auth.login.LoginException) KeyException(java.security.KeyException) PermissionException(org.ow2.proactive.scheduler.common.exception.PermissionException) NotConnectedException(org.ow2.proactive.scheduler.common.exception.NotConnectedException) AlreadyConnectedException(org.ow2.proactive.scheduler.common.exception.AlreadyConnectedException)

Aggregations

CredData (org.ow2.proactive.authentication.crypto.CredData)53 Credentials (org.ow2.proactive.authentication.crypto.Credentials)41 PublicKey (java.security.PublicKey)15 Test (org.junit.Test)15 LoginException (javax.security.auth.login.LoginException)13 KeyException (java.security.KeyException)10 ResourceManager (org.ow2.proactive.resourcemanager.frontend.ResourceManager)10 SchedulerAuthenticationInterface (org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface)10 RMAuthentication (org.ow2.proactive.resourcemanager.authentication.RMAuthentication)9 HashMap (java.util.HashMap)8 RMFunctionalTest (functionaltests.utils.RMFunctionalTest)6 JMXServiceURL (javax.management.remote.JMXServiceURL)6 JMXConnector (javax.management.remote.JMXConnector)5 RMProxyUserInterface (org.ow2.proactive.resourcemanager.common.util.RMProxyUserInterface)5 Scheduler (org.ow2.proactive.scheduler.common.Scheduler)5 SchedulerProxyUserInterface (org.ow2.proactive.scheduler.common.util.SchedulerProxyUserInterface)5 Decrypter (org.ow2.proactive.scheduler.task.utils.Decrypter)5 MBeanServerConnection (javax.management.MBeanServerConnection)4 ObjectName (javax.management.ObjectName)4 POST (javax.ws.rs.POST)4