Search in sources :

Example 46 with KeyException

use of java.security.KeyException in project scheduling by ow2-proactive.

the class SSHInfrastructureV2 method startNodeImpl.

/**
 * Internal node acquisition method
 * <p>
 * Starts a PA runtime on remote host using SSH, register it manually in the
 * nodesource.
 *
 * @param hostTracker The host on which one the node will be started
 * @param nbNodes number of nodes to deploy
 * @param depNodeURLs list of deploying or lost nodes urls created
 * @throws RMException
 *             acquisition failed
 */
public void startNodeImpl(final HostTracker hostTracker, final int nbNodes, final List<String> depNodeURLs) throws RMException {
    String fs = getTargetOSObj().fs;
    // we set the java security policy file
    ArrayList<String> sb = new ArrayList<>();
    final boolean containsSpace = schedulingPath.contains(" ");
    if (containsSpace) {
        sb.add("-Dproactive.home=\"" + schedulingPath + "\"");
    } else {
        sb.add("-Dproactive.home=" + schedulingPath);
    }
    String securitycmd = CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getCmdLine();
    if (!this.javaOptions.contains(securitycmd)) {
        if (containsSpace) {
            securitycmd += "\"";
        }
        securitycmd += this.schedulingPath + fs + "config" + fs;
        securitycmd += "security.java.policy-client";
        if (containsSpace) {
            securitycmd += "\"";
        }
        sb.add(securitycmd);
    }
    // we set the log4j configuration file
    String log4jcmd = CentralPAPropertyRepository.LOG4J.getCmdLine();
    if (!this.javaOptions.contains(log4jcmd)) {
        // log4j only understands urls
        if (containsSpace) {
            log4jcmd += "\"";
        }
        log4jcmd += "file:";
        if (!this.schedulingPath.startsWith("/")) {
            log4jcmd += "/";
        }
        log4jcmd += this.schedulingPath.replace("\\", "/");
        log4jcmd += "/config/log/node.properties";
        if (containsSpace) {
            log4jcmd += "\"";
        }
        sb.add(log4jcmd);
    }
    // we add extra java/PA configuration
    if (this.javaOptions != null && !this.javaOptions.trim().isEmpty()) {
        sb.add(this.javaOptions.trim());
    }
    CommandLineBuilder clb = super.getDefaultCommandLineBuilder(getTargetOSObj());
    final boolean deployNodesInDetachedMode = PAResourceManagerProperties.RM_NODES_RECOVERY.getValueAsBoolean() || PAResourceManagerProperties.RM_PRESERVE_NODES_ON_SHUTDOWN.getValueAsBoolean();
    if (deployNodesInDetachedMode) {
        // if we do not want to kill the nodes when the RM exits or
        // restarts, then we should launch the nodes in background and
        // ignore the RM termination signal
        clb.setDetached();
    }
    clb.setJavaPath(this.javaPath);
    clb.setRmHome(this.schedulingPath);
    clb.setPaProperties(sb);
    final String nodeName = nodeNameBuilder.generateNodeName(hostTracker);
    clb.setNodeName(nodeName);
    clb.setNumberOfNodes(nbNodes);
    // finally, the credential's value
    String credString;
    try {
        Client currentClient = super.nodeSource.getAdministrator();
        credString = new String(currentClient.getCredentials().getBase64());
    } catch (KeyException e) {
        throw new RMException("Could not get base64 credentials", e);
    }
    clb.setCredentialsValueAndNullOthers(credString);
    // add an expected node. every unexpected node will be discarded
    String cmdLine;
    String obfuscatedCmdLine;
    try {
        cmdLine = clb.buildCommandLine(true);
        obfuscatedCmdLine = clb.buildCommandLine(false);
    } catch (IOException e) {
        throw new RMException("Cannot build the " + RMNodeStarter.class.getSimpleName() + "'s command line.", e);
    }
    // one escape the command to make it runnable through ssh
    if (cmdLine.contains("\"")) {
        cmdLine = cmdLine.replaceAll("\"", "\\\\\"");
    }
    final String finalCmdLine = cmdLine;
    // The final addDeployingNode() method will initiate a timeout that
    // will declare node as lost and set the description of the failure
    // with a simplistic message, since there is no way to override this
    // mechanism we consider only 90% of timeout to set custom description
    // in case of failure and still allow global timeout
    final int shorterTimeout = Math.round((90 * super.nodeTimeOut) / 100);
    JSch jsch = new JSch();
    final String msg = "deploy on " + hostTracker.getResolvedAddress();
    final List<String> createdNodeNames = RMNodeStarter.getWorkersNodeNames(nodeName, nbNodes);
    depNodeURLs.addAll(addMultipleDeployingNodes(createdNodeNames, obfuscatedCmdLine, msg, super.nodeTimeOut));
    addTimeouts(depNodeURLs);
    Session session;
    try {
        // Create ssh session to the hostname
        session = jsch.getSession(this.sshUsername, hostTracker.getResolvedAddress().getHostName(), this.sshPort);
        if (this.sshPassword == null) {
            jsch.addIdentity(this.sshUsername, this.sshPrivateKey, null, null);
        } else {
            session.setPassword(this.sshPassword);
        }
        session.setConfig(this.sshOptions);
        session.connect(shorterTimeout);
    } catch (JSchException e) {
        multipleDeclareDeployingNodeLost(depNodeURLs, "unable to " + msg + "\n" + getStackTraceAsString(e));
        throw new RMException("unable to " + msg, e);
    }
    SSHInfrastructureV2.logger.info("Executing SSH command: '" + finalCmdLine + "'");
    ScheduledExecutorService deployService = Executors.newSingleThreadScheduledExecutor();
    try {
        // Create ssh channel to run the cmd
        ByteArrayOutputStream baos = new ByteArrayOutputStream(DEFAULT_OUTPUT_BUFFER_LENGTH);
        ChannelExec channel;
        try {
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(finalCmdLine);
            channel.setOutputStream(baos);
            channel.setErrStream(baos);
            channel.connect();
        } catch (JSchException e) {
            multipleDeclareDeployingNodeLost(depNodeURLs, "unable to " + msg + "\n" + getStackTraceAsString(e));
            throw new RMException("unable to " + msg, e);
        }
        final ChannelExec chan = channel;
        Future<Void> deployResult = deployService.submit(new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                while (!shutDown.get() && !checkAllNodesAreAcquiredAndDo(createdNodeNames, null, null)) {
                    if (anyTimedOut(depNodeURLs)) {
                        throw new IllegalStateException("The upper infrastructure has issued a timeout");
                    }
                    // processes live completely independently
                    if (!deployNodesInDetachedMode && chan.getExitStatus() != PROCESS_STILL_RUNNING_VALUE) {
                        throw new IllegalStateException("The jvm process of the node has exited prematurely");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // we know the cause of this
                        return null;
                    // interruption just exit
                    }
                }
                // Victory
                return null;
            }
        });
        try {
            deployResult.get(shorterTimeout, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            declareLostAndThrow("Unable to " + msg + " due to " + e.getCause(), depNodeURLs, channel, baos, e);
        } catch (InterruptedException e) {
            deployResult.cancel(true);
            declareLostAndThrow("Unable to " + msg + " due to an interruption", depNodeURLs, channel, baos, e);
        } catch (TimeoutException e) {
            deployResult.cancel(true);
            declareLostAndThrow("Unable to " + msg + " due to timeout", depNodeURLs, channel, baos, e);
        } finally {
            channel.disconnect();
        }
    } finally {
        removeTimeouts(depNodeURLs);
        session.disconnect();
        deployService.shutdownNow();
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) ArrayList(java.util.ArrayList) Throwables.getStackTraceAsString(com.google.common.base.Throwables.getStackTraceAsString) CommandLineBuilder(org.ow2.proactive.resourcemanager.utils.CommandLineBuilder) JSch(com.jcraft.jsch.JSch) RMException(org.ow2.proactive.resourcemanager.exception.RMException) Client(org.ow2.proactive.resourcemanager.authentication.Client) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyException(java.security.KeyException) ChannelExec(com.jcraft.jsch.ChannelExec) KeyException(java.security.KeyException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) RMException(org.ow2.proactive.resourcemanager.exception.RMException) ExecutionException(java.util.concurrent.ExecutionException) JSchException(com.jcraft.jsch.JSchException) Session(com.jcraft.jsch.Session)

Example 47 with KeyException

use of java.security.KeyException in project scheduling by ow2-proactive.

the class FileLoginModule method authenticateUserFromFile.

/**
 * Check user and password from login file.
 * @param username user's login
 * @param password user's password
 * @return true if user is found in login file and its password is correct, falser otherwise
 * @throws LoginException if login file is not found or unreadable.
 */
private boolean authenticateUserFromFile(String username, String password) throws LoginException {
    Properties props = new Properties();
    PrivateKey privateKey = null;
    try {
        privateKey = getPrivateKey();
    } catch (KeyException e) {
        throw new LoginException(e.toString());
    }
    try (FileInputStream stream = new FileInputStream(loginFile)) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        props.load(reader);
    } catch (FileNotFoundException e) {
        throw new LoginException(e.toString());
    } catch (IOException e) {
        throw new LoginException(e.toString());
    }
    // verify the username and password
    if (!props.containsKey(username)) {
        return false;
    } else {
        String encryptedPassword = (String) props.get(username);
        try {
            if (!HybridEncryptionUtil.decryptBase64String(encryptedPassword, privateKey, ENCRYPTED_DATA_SEP).equals(password)) {
                return false;
            }
        } catch (KeyException e) {
            throw new LoginException(e.toString());
        }
        return true;
    }
}
Also used : PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) FileNotFoundException(java.io.FileNotFoundException) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) IOException(java.io.IOException) Properties(java.util.Properties) KeyException(java.security.KeyException) FileInputStream(java.io.FileInputStream)

Example 48 with KeyException

use of java.security.KeyException in project scheduling by ow2-proactive.

the class Credentials method getPrivateKey.

/**
 * Retrieves a private key stored in a local file
 * <p>
 * Tries to guess the algorithm used for keypair generation which
 * is not included in the file. According to <a href="http://download.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html#AppA">Java Cryptography Specification</a>,
 * the algorithm can be only one of "RSA" or "DSA", so we can just try both using the
 * <code>algorithms</code> param. If the algorithm used to generate the key is neither RSA or DSA
 * (highly unlikely), this method cannot recreate the private key, but {@link #decrypt(String)}
 * maybe will.
 *
 * @param privPath
 *            path to the private key on the local filesystem
 * @param algorithms a list of algorithms to try for creating the PK. Recommanded value:
 * 			{"RSA","DSA"}
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException
 *             the key could not be retrieved or is malformed, or the algorithm used for generation
 *             is not one of <code>algorithms</code>
 */
public static PrivateKey getPrivateKey(String privPath, String[] algorithms) throws KeyException {
    PrivateKey privKey = null;
    for (String algo : algorithms) {
        try {
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance(algo);
            // recover private key bytes
            byte[] bytes;
            File pkFile = new File(privPath);
            try (DataInputStream pkStream = new DataInputStream(new FileInputStream(pkFile))) {
                bytes = new byte[(int) pkFile.length()];
                pkStream.readFully(bytes);
            } catch (Exception e) {
                throw new KeyException("Could not recover private key (algo=" + algo + ")", e);
            }
            // reconstruct private key
            PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(bytes);
            try {
                privKey = keyFactory.generatePrivate(privKeySpec);
            } catch (InvalidKeySpecException e) {
                throw new KeyException("Cannot re-generate private key  (algo=" + algo + ")", e);
            }
        } catch (Exception e) {
        }
    }
    if (privKey == null) {
        String str = "Could not generate Private Key (algorithms: ";
        for (String algo : algorithms) {
            str += algo + " ";
        }
        str += ")";
        throw new KeyException(str);
    }
    return privKey;
}
Also used : PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) DataInputStream(java.io.DataInputStream) File(java.io.File) KeyFactory(java.security.KeyFactory) FileInputStream(java.io.FileInputStream) KeyException(java.security.KeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyException(java.security.KeyException)

Example 49 with KeyException

use of java.security.KeyException in project scheduling by ow2-proactive.

the class Credentials method createCredentials.

/**
 * Creates new encrypted credentials
 * <p>
 * Encrypts the message '<code>login</code>:<code>password</code>' using the
 * public key <code>pubKey</code> and <code>cipher</code>
 * and store it in a new Credentials object.
 *
 * @see KeyPairUtil#encrypt(PublicKey, String, byte[])
 * @param login the login to encrypt
 * @param password the corresponding password to encrypt
 * @param pubKey public key used for encryption
 * @param cipher cipher parameters: combination of transformations
 * @return the Credentials object containing the encrypted data
 * @throws KeyException key generation or encryption failed
 */
@Deprecated
public static Credentials createCredentials(String login, String password, byte[] datakey, PublicKey pubKey, String cipher) throws KeyException {
    CredData cc = new CredData();
    cc.setLogin(CredData.parseLogin(login));
    cc.setDomain(CredData.parseDomain(login));
    cc.setPassword(password);
    cc.setKey(datakey);
    // serialize clear credentials to byte array
    byte[] clearCred;
    try {
        clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
    } catch (IOException e1) {
        throw new KeyException(e1.getMessage());
    }
    int size = keySize(pubKey);
    HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey, cipher, clearCred);
    byte[] encAes = encryptedData.getEncryptedSymmetricKey();
    byte[] encData = encryptedData.getEncryptedData();
    return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}
Also used : IOException(java.io.IOException) KeyException(java.security.KeyException)

Example 50 with KeyException

use of java.security.KeyException in project scheduling by ow2-proactive.

the class Credentials method createCredentials.

/**
 * Creates new encrypted credentials
 * <p>
 * Encrypts the message '<code>credData</code>' using the
 * public key <code>pubKey</code> and <code>cipher</code>
 * and store it in a new Credentials object.
 *
 * @see KeyPairUtil#encrypt(PublicKey, String, byte[])
 * @param cc, the class containing the data to be crypted
 * @param pubKey public key used for encryption
 * @param cipher cipher parameters: combination of transformations
 * @return the Credentials object containing the encrypted data
 * @throws KeyException key generation or encryption failed
 */
public static Credentials createCredentials(final CredData cc, final PublicKey pubKey, final String cipher) throws KeyException {
    // serialize clear credentials to byte array
    byte[] clearCred;
    try {
        clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
    } catch (IOException e1) {
        throw new KeyException(e1.getMessage());
    }
    HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey, cipher, clearCred);
    byte[] encAes = encryptedData.getEncryptedSymmetricKey();
    byte[] encData = encryptedData.getEncryptedData();
    int size = keySize(pubKey);
    return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}
Also used : IOException(java.io.IOException) KeyException(java.security.KeyException)

Aggregations

KeyException (java.security.KeyException)59 IOException (java.io.IOException)22 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 File (java.io.File)10 PublicKey (java.security.PublicKey)8 FileInputStream (java.io.FileInputStream)7 Cipher (javax.crypto.Cipher)6 Throwables.getStackTraceAsString (com.google.common.base.Throwables.getStackTraceAsString)5 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)5 LoginException (javax.security.auth.login.LoginException)5 Credentials (org.ow2.proactive.authentication.crypto.Credentials)5 FileNotFoundException (java.io.FileNotFoundException)4 PrivateKey (java.security.PrivateKey)4 CredData (org.ow2.proactive.authentication.crypto.CredData)4 RMException (org.ow2.proactive.resourcemanager.exception.RMException)4 CommandLineBuilder (org.ow2.proactive.resourcemanager.utils.CommandLineBuilder)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DataInputStream (java.io.DataInputStream)3 InputStream (java.io.InputStream)3 Key (java.security.Key)3