Search in sources :

Example 26 with Credentials

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

the class EntryPoint method run.

protected int run(String... args) {
    CommandFactory commandFactory = null;
    CommandLine cli = null;
    AbstractDevice console;
    ApplicationContext currentContext = new ApplicationContextImpl().currentContext();
    // Cannot rely on AbstractCommand#isDebugModeEnabled
    // because at this step SetDebugModeCommand#execute has not yet been executed
    // Consequently, SetDebugModeCommand.PROP_DEBUG_MODE is not set even if debug mode is enabled.
    boolean isDebugModeEnabled = isDebugModeEnabled(args);
    try {
        commandFactory = getCommandFactory(currentContext);
        Options options = commandFactory.supportedOptions();
        cli = parseArgs(options, args);
    } catch (IOException ioe) {
        System.err.println("An error occurred.");
        ioe.printStackTrace(System.err);
        return 1;
    } catch (ParseException pe) {
        writeError(currentContext, pe.getMessage(), pe, isDebugModeEnabled);
        // print usage
        Command help = commandFactory.commandForOption(new Option("h", null));
        if (help != null) {
            help.execute(currentContext);
        }
        return 1;
    }
    currentContext.setObjectMapper(new ObjectMapper().configure(FAIL_ON_UNKNOWN_PROPERTIES, false));
    currentContext.setRestServerUrl(DFLT_REST_SCHEDULER_URL);
    currentContext.setResourceType(resourceType());
    // retrieve the (ordered) command list corresponding to command-line
    // arguments
    List<Command> commands;
    try {
        commands = commandFactory.getCommandList(cli, currentContext);
    } catch (CLIException e) {
        writeError(currentContext, "An error occurred.", e, isDebugModeEnabled);
        return 1;
    }
    boolean retryLogin = false;
    try {
        executeCommandList(commands, currentContext);
    } catch (CLIException error) {
        if (REASON_UNAUTHORIZED_ACCESS == error.reason() && hasLoginCommand(commands)) {
            retryLogin = true;
        } else {
            writeError(currentContext, "An error occurred.", error, isDebugModeEnabled);
            return 1;
        }
    } catch (Throwable e) {
        writeError(currentContext, "An error occurred.", e, isDebugModeEnabled);
        return 1;
    }
    /*
         * in case of an existing session-id, the REST CLI reuses it without
         * obtaining a new session-id even if a login with credentials
         * specified. However if the REST server responds with an authorization
         * error (e.g. due to session timeout), it re-executes the commands list
         * with AbstractLoginCommand.PROP_RENEW_SESSION property set to 'true'.
         * This will effectively re-execute the user command with a new
         * session-id from server.
         */
    if (retryLogin && currentContext.getProperty(PROP_PERSISTED_SESSION, Boolean.TYPE, false)) {
        try {
            currentContext.setProperty(PROP_RENEW_SESSION, true);
            executeCommandList(commands, currentContext);
        } catch (Throwable error) {
            writeError(currentContext, "An error occurred while execution.", error, isDebugModeEnabled);
            return 1;
        }
    }
    return 0;
}
Also used : Options(org.apache.commons.cli.Options) IOException(java.io.IOException) CommandLine(org.apache.commons.cli.CommandLine) Command(org.ow2.proactive_grid_cloud_portal.cli.cmd.Command) AbstractLoginCommand(org.ow2.proactive_grid_cloud_portal.cli.cmd.AbstractLoginCommand) AbstractDevice(org.ow2.proactive_grid_cloud_portal.cli.console.AbstractDevice) Option(org.apache.commons.cli.Option) ParseException(org.apache.commons.cli.ParseException) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 27 with Credentials

use of org.ow2.proactive.authentication.crypto.Credentials 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 28 with Credentials

use of org.ow2.proactive.authentication.crypto.Credentials 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 29 with Credentials

use of org.ow2.proactive.authentication.crypto.Credentials 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 30 with Credentials

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

the class RMProxiesManager method createRMProxiesManager.

/**
 * Create a RMProxiesManager using RM's URI (example : "rmi://localhost:1099/" ).
 *
 * @param rmURI The URI of a started Resource Manager
 * @return an instance of RMProxiesManager joined to the Resource Manager at the given URI
 */
public static RMProxiesManager createRMProxiesManager(final URI rmURI) throws RMException, RMProxyCreationException, URISyntaxException {
    Credentials schedulerProxyCredentials;
    try {
        schedulerProxyCredentials = Credentials.getCredentials(PASchedulerProperties.getAbsolutePath(PASchedulerProperties.RESOURCE_MANAGER_CREDS.getValueAsString()));
    } catch (Exception e) {
        throw new RMProxyCreationException(e);
    }
    boolean singleConnection = PASchedulerProperties.RESOURCE_MANAGER_SINGLE_CONNECTION.getValueAsBoolean();
    if (singleConnection) {
        return new SingleConnectionRMProxiesManager(rmURI, schedulerProxyCredentials);
    } else {
        return new PerUserConnectionRMProxiesManager(rmURI, schedulerProxyCredentials);
    }
}
Also used : Credentials(org.ow2.proactive.authentication.crypto.Credentials) URISyntaxException(java.net.URISyntaxException) RMException(org.ow2.proactive.resourcemanager.exception.RMException)

Aggregations

Credentials (org.ow2.proactive.authentication.crypto.Credentials)50 CredData (org.ow2.proactive.authentication.crypto.CredData)42 KeyException (java.security.KeyException)17 ResourceManager (org.ow2.proactive.resourcemanager.frontend.ResourceManager)17 PublicKey (java.security.PublicKey)15 LoginException (javax.security.auth.login.LoginException)15 Test (org.junit.Test)14 SchedulerAuthenticationInterface (org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface)13 RMAuthentication (org.ow2.proactive.resourcemanager.authentication.RMAuthentication)12 IOException (java.io.IOException)11 HashMap (java.util.HashMap)11 File (java.io.File)9 RMFunctionalTest (functionaltests.utils.RMFunctionalTest)6 JMXServiceURL (javax.management.remote.JMXServiceURL)6 JMXConnector (javax.management.remote.JMXConnector)5 Node (org.objectweb.proactive.core.node.Node)5 Scheduler (org.ow2.proactive.scheduler.common.Scheduler)5 MBeanServerConnection (javax.management.MBeanServerConnection)4 ObjectName (javax.management.ObjectName)4 POST (javax.ws.rs.POST)4