You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@brooklyn.apache.org by ahgittin <gi...@git.apache.org> on 2015/01/22 22:20:21 UTC

[GitHub] incubator-brooklyn pull request: Jclouds tidy

GitHub user ahgittin opened a pull request:

    https://github.com/apache/incubator-brooklyn/pull/465

    Jclouds tidy

    refactor to share code for credentials inferencing; then expand this to:
    * validate keys, including passphrase (fail fast if bad passphrase)
    * support add'l public keys to be authorized
    * support add'l first-boot commands as part of the template options script


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/ahgittin/incubator-brooklyn jclouds-tidy

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/incubator-brooklyn/pull/465.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #465
    
----
commit fa79e20dbf895520b411965779034f0baee01f30
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T10:33:16Z

    tidy up how os credentials are inferred
    
    share lookup routines in preparation for adding validation

commit c3828fbffb6bad0006456e4f828f56f4cfc44bb2
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T14:55:47Z

    validate public, private key and passphrase *before* provisioning
    
    and give good feedback through logging and errors

commit 50395595f9a808af254a715516adce6b1ae5d93c
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T20:42:08Z

    add extraSshPublicKeys options to jclouds
    
    allows extra public keys to be supplied to authorized_keys on provisioned vm's

commit aafddb59c576df3842ed70a15e759426cfe0ee4d
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T21:18:17Z

    add a custom template-options script in case sudoers or something else needs changing on first boot

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23466397
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    +        private final ConfigBag config;
    +        private boolean preferPassword = false;
    +        private boolean tryDefaultKeys = true;
    +        private boolean requirePublicKey = true;
    +        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
    +        private boolean warnOnErrors = true;
    +        private boolean throwOnErrors = false;
    +        
    +        private boolean dirty = true;;
    +        
    +        private String privateKeyData;
    +        private String publicKeyData;
    +        private String password;
    +        
    +        private OsCredential(ConfigBag config) {
    +            this.config = config;
    +        }
    +
    +        /** throws if there are any problems */
    +        public OsCredential checkNotEmpty() {
    +            checkNoErrors();
    +            
    +            if (!hasKey() && !hasPassword()) {
    +                if (warningMessages.size()>0)
    +                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
    +                else 
    +                    throw new IllegalStateException("Could not find credentials");
    +            }
    +            return this;
    +        }
    +
    +        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
    +         * @return */
    +        public OsCredential checkNoErrors() {
    +            throwOnErrors(true);
    +            dirty();
    +            infer();
    +            return this;
    +        }
    +        
    +        public OsCredential logAnyWarnings() {
    +            if (!warningMessages.isEmpty())
    +                log.warn("When reading credentials: "+warningMessages);
    +            return this;
    +        }
    +
    +        public Set<String> getWarningMessages() {
    +            return warningMessages;
    +        }
    +        
    +        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
    +         * via {@link #preferPassword()} */
    +        public synchronized String get() {
    +            infer();
    +            
    +            if (isUsingPassword()) return password;
    +            if (hasKey()) return privateKeyData;
    +            return null;
    +        }
    +
    +        /** if there is no credential (ignores public key) */
    +        public boolean isEmpty() {
    +            return !hasKey() && !hasPassword();
    +        }
    +        public boolean hasKey() {
    +            infer();
    +            // key has stricter non-blank check than password
    +            return Strings.isNonBlank(privateKeyData);
    +        }
    +        public boolean hasPassword() {
    +            infer();
    +            // blank, even empty passwords are allowed
    +            return password!=null;
    +        }
    +        /** if a password is available, and either this is preferred over a key or there is no key */
    +        public boolean isUsingPassword() {
    +            return hasPassword() && (!hasKey() || preferPassword);
    +        }
    +        
    +        public String getPrivateKeyData() {
    +            infer();
    +            return privateKeyData;
    +        }
    +        public String getPublicKeyData() {
    +            infer();
    +            return publicKeyData;
    +        }
    +        public String getPassword() {
    +            infer();
    +            return password;
    +        }
    +        
    +        /** if both key and password supplied, prefer the key; the default */
    +        public OsCredential preferKey() { preferPassword = false; return dirty(); }
    +        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
    +        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
    +        
    +        /** if false, do not mind if there is no public key corresponding to any private key;
    +         * defaults to true; only applies if a private key is set */
    +        public OsCredential requirePublicKey(boolean requirePublicKey) {
    +            this.requirePublicKey = requirePublicKey;
    +            return dirty(); 
    +        }
    +        /** whether to check the private/public keys and passphrase are coherent; default true */
    +        public OsCredential doKeyValidation(boolean doKeyValidation) {
    +            this.doKeyValidation = doKeyValidation;
    +            return dirty();
    +        }
    +        /** if true (the default) this will look at default locations set on keys */
    +        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
    +            this.tryDefaultKeys = tryDefaultKeys;
    +            return dirty(); 
    +        }
    +        /** whether to log warnings on problems */
    +        public OsCredential warnOnErrors(boolean warnOnErrors) {
    +            this.warnOnErrors = warnOnErrors;
    +            return dirty(); 
    +        }
    +        /** whether to throw on problems */
    +        public OsCredential throwOnErrors(boolean throwOnErrors) {
    +            this.throwOnErrors = throwOnErrors;
    +            return dirty(); 
    +        }
    +        
    +        private OsCredential dirty() { dirty = true; return this; }
    +            
    +        public static OsCredential newInstance(ConfigBag config) {
    +            return new OsCredential(config);
    +        }
    +        
    +        private synchronized void infer() {
    +            if (!dirty) return;
    +            warningMessages.clear(); 
    +            
    +            log.debug("Inferring OS credentials");
    +            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
    +            password = config.get(LocationConfigKeys.PASSWORD);
    +            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
    +
    +            KeyPair privateKey = null;
    +            
    +            if (Strings.isBlank(privateKeyData)) {
    +                // look up private key files
    +                String privateKeyFiles = null;
    +                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
    +                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (Strings.isNonBlank(privateKeyFiles)) {
    +                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
    +                    while (fi.hasNext()) {
    +                        String file = fi.next();
    +                        if (Strings.isNonBlank(file)) {
    +                            try {
    +                                // real URL's won't actual work, due to use of path separator above 
    +                                // not real important, but we get it for free if "files" is a list instead.
    +                                // using ResourceUtils is useful for classpath resources
    +                                if (file!=null)
    +                                    privateKeyData = ResourceUtils.create().getResourceAsString(file);
    +                                // else use data already set
    +                                
    +                                privateKey = getValidatedPrivateKey(file);
    +                                
    +                                if (privateKeyData==null) {
    +                                    // was cleared due to validation error
    +                                } else if (Strings.isNonBlank(publicKeyData)) {
    +                                    log.debug("Loaded private key data from "+file+" (public key data explicitly set)");
    +                                    break;
    +                                } else {
    +                                    String publicKeyFile = (file!=null ? file+".pub" : "(data)");
    +                                    try {
    +                                        publicKeyData = ResourceUtils.create().getResourceAsString(publicKeyFile);
    +                                        
    +                                        log.debug("Loaded private key data from "+file+
    +                                            " and public key data from "+publicKeyFile);
    +                                        break;
    +                                    } catch (Exception e) {
    +                                        Exceptions.propagateIfFatal(e);
    +                                        log.debug("No public key file "+publicKeyFile+"; will try extracting from private key");
    +                                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
    +                                        
    +                                        if (publicKeyData==null) {
    +                                            if (requirePublicKey) {
    +                                                addWarning("Unable to find or extract public key for "+file, "skipping");
    +                                            } else {
    +                                                log.debug("Loaded private key data from "+file+" (public key data not found but not required)");
    +                                                break;
    +                                            }
    +                                        } else {
    +                                            log.debug("Loaded private key data from "+file+" (public key data extracted)");
    +                                            break;
    +                                        }
    +                                        privateKeyData = null;
    +                                    }
    +                                }
    +
    +                            } catch (Exception e) {
    +                                Exceptions.propagateIfFatal(e);
    +                                String message = "Missing/invalid private key file "+file;
    +                                if (privateKeyFilesExplicitlySet) addWarning(message, (!fi.hasNext() ? "no more files to try" : "trying next file")+": "+e);
    +                            }
    +                        }
    +                    }
    +                    if (privateKeyFilesExplicitlySet && Strings.isBlank(privateKeyData))
    +                        error("No valid private keys found", ""+warningMessages);
    +                }
    +            } else {
    +                privateKey = getValidatedPrivateKey("(data)");
    +            }
    +            
    +            if (privateKeyData!=null) {
    +                if (requirePublicKey && Strings.isBlank(publicKeyData)) {
    +                    if (privateKey!=null) {
    +                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
    +                    }
    +                    if (Strings.isBlank(publicKeyData)) {
    +                        error("If explicit "+LocationConfigKeys.PRIVATE_KEY_DATA.getName()+" is supplied, then "
    +                            + "the corresponding "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" must also be supplied.", null);
    +                    } else {
    +                        log.debug("Public key data extracted");
    +                    }
    +                }
    +                if (doKeyValidation && privateKey!=null && privateKey.getPublic()!=null && Strings.isNonBlank(publicKeyData)) {
    +                    PublicKey decoded = null;
    +                    try {
    +                        decoded = AuthorizedKeysParser.decodePublicKey(publicKeyData);
    +                    } catch (Exception e) {
    +                        Exceptions.propagateIfFatal(e);
    +                        addWarning("Invalid public key: "+decoded);
    +                    }
    +                    if (decoded!=null && !privateKey.getPublic().equals( decoded )) {
    +                        error("Public key inferred from does not match public key extracted from private key", null);
    +                    }
    +                }
    +            }
    +
    +            log.debug("OS credential inference: "+this);
    +            dirty = false;
    +        }
    +
    +        private KeyPair getValidatedPrivateKey(String label) {
    +            KeyPair privateKey = null;
    +            String passphrase = config.get(CloudLocationConfig.PRIVATE_KEY_PASSPHRASE);
    +            try {
    +                privateKey = SecureKeys.readPem(new ByteArrayInputStream(privateKeyData.getBytes()), passphrase);
    +                if (passphrase!=null) {
    +                    // get the unencrypted key data for our internal use (jclouds requires this)
    +                    privateKeyData = SecureKeys.toPem(privateKey);
    +                }
    +            } catch (PassphraseProblem e) {
    +                if (doKeyValidation) {
    +                    if (Strings.isBlank(passphrase))
    +                        addWarning("Passphrase required for key '"+label+"'");
    +                    else
    +                        addWarning("Invalid passphrase for key '"+label+"'");
    +                    privateKeyData = null;
    +                }
    +            } catch (Exception e) {
    +                Exceptions.propagateIfFatal(e);
    +                if (doKeyValidation) {
    +                    addWarning("Unable to parse private key from '"+label+"': unknown format");
    +                    privateKeyData = null;
    +                }
    +            }
    +            return privateKey;
    +        }
    +        
    +        Set<String> warningMessages = MutableSet.of();
    +        
    +        private void error(String msg, String logExtension) {
    +            addWarning(msg);
    +            if (warnOnErrors) log.warn(msg+(logExtension==null ? "" : ": "+logExtension));
    +            if (throwOnErrors) throw new IllegalStateException(msg+(logExtension==null ? "" : "; "+logExtension));
    +        }
    +
    +        private void addWarning(String msg) {
    +            addWarning(msg, null);
    +        }
    +        private void addWarning(String msg, String debugExtension) {
    +            log.debug(msg+(debugExtension==null ? "" : "; "+debugExtension));
    +            warningMessages.add(msg);
    +        }
    +
    +        @Override
    +        public String toString() {
    +            return getClass().getSimpleName()+"["+
    +                (Strings.isNonBlank(publicKeyData) ? publicKeyData : "public-key")+";"+
    +                (Strings.isNonBlank(privateKeyData) ? "private-key" : "private-key")+","+
    --- End diff --
    
    `toString` looks wrong: will say "private-key" whether or not there is privateKeyData, and will say "public-key" if there is no publicKeyData.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23525418
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    --- End diff --
    
    True that most/all exceptions that come from java 1.0 have a no-arg constructor. It was a great relief when they stopped using those in situations like `ClassCastException`, to actually tell you something about the exception.
    
    For new exception classes that folk are writing, the (vast?) majority of cases it deserves forcing the caller to pass a message, rather than allowing the absence of useful info to the end-user.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#issuecomment-71692661
  
    merging -- @richardcloudsoft as this should address the worry you had, not compound it!  but please do test and let me know


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522243
  
    --- Diff: core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java ---
    @@ -93,6 +95,40 @@ public void testReadRsaKey() throws Exception {
             checkNonTrivial(key);
         }
     
    +    @Test(expectedExceptions=IllegalStateException.class)
    +    public void testReadRsaPublicKeyAsPemFails() throws Exception {
    +        // should fail; see next test
    +        SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"), null);
    +    }
    +    
    +    @Test
    +    public void testReadRsaPublicKeyAsAuthKeysWorks() throws Exception {
    +        PublicKey key = AuthorizedKeysParser.decodePublicKey(
    +            ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"));
    +        KeyPair fromPem = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem"), null);        
    --- End diff --
    
    i've added `*.pem` for good measure.  `*_rsa` was already there.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522215
  
    --- Diff: core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java ---
    @@ -93,6 +95,40 @@ public void testReadRsaKey() throws Exception {
             checkNonTrivial(key);
         }
     
    +    @Test(expectedExceptions=IllegalStateException.class)
    +    public void testReadRsaPublicKeyAsPemFails() throws Exception {
    +        // should fail; see next test
    +        SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"), null);
    +    }
    +    
    +    @Test
    +    public void testReadRsaPublicKeyAsAuthKeysWorks() throws Exception {
    +        PublicKey key = AuthorizedKeysParser.decodePublicKey(
    +            ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"));
    +        KeyPair fromPem = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem"), null);        
    --- End diff --
    
    maybe it is big enough rat can tell it isn't human readable?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522043
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    --- End diff --
    
    done, and we log it (debug) when catching


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520443
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
    --- End diff --
    
    `extends` used here in the "builds-on" sense, not the "has all properties of the parent" sense


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#issuecomment-71450330
  
    @ahgittin finished reviewing. Lots of good stuff here.
    
    My biggest comment (because it relates to the user experience) is about an explicit configuration option to tell it to auto-generate a key-pair.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521961
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
    --- End diff --
    
    If Brooklyn makes up a new password, then should we log that? Looks like it's not logged anywhere currently. Most important to log it if the auto-generated password is the only subsequent login approach.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520649
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    --- End diff --
    
    Unfortunately these methods (e.g. `newKeyStore`, `getTrustManager`, `getCanonicalImpl` etc) weren't marked as `@Beta` and neither was the class. Are we definitely ok with just deleting them rather than deprecating them?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521840
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    +                pubKey = SecureKeys.toPub(newKeyPair);
    +                privKey = SecureKeys.toPem(newKeyPair);
    +                LOG.debug("Brooklyn key being created for "+user+" at new machine "+this+" is:\n"+privKey);
                 }
    +            // ensure credential is not used any more, as we have extracted al useful info
    --- End diff --
    
    Typo: "al" instead of "all".


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#issuecomment-71164054
  
    closing and re-opening to kick off another build.  it's passing for me locally.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#issuecomment-71453437
  
    Thanks @aledsage .  You happy with the last 3 commits?  I think they address all the main issues.
    
    @richardcloudsoft let me know when you've tried this!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23519856
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java ---
    @@ -42,7 +44,9 @@
      * X509v3CertificateBuilder drags in an add'l dependency (bcmail) and is harder to use. */
     @SuppressWarnings("deprecation")
    --- End diff --
    
    I know it's not your code but couldn't help commenting...
    
    I'd prefer us not to use a blanket `@SuppressWarnings("deprecation")` on the class. It means we don't get told what we're using that is actually deprecated, which we should fix (unless we're deliberately doing it for backwards compatibility reasons with multiple versions of a library?!).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522559
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    +                pubKey = SecureKeys.toPub(newKeyPair);
    +                privKey = SecureKeys.toPem(newKeyPair);
    +                LOG.debug("Brooklyn key being created for "+user+" at new machine "+this+" is:\n"+privKey);
                 }
    +            // ensure credential is not used any more, as we have extracted al useful info
    +            credential = null;
                 
    -        } else {
                 // Create the user
                 // note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
                 AdminAccess.Builder adminBuilder = AdminAccess.builder()
                         .adminUsername(user)
    -                    .adminPassword(password)
    -                    .grantSudoToAdminUser(groovyTruth(grantUserSudo))
    -                    .resetLoginPassword(true)
    -                    .loginPassword(password);
    -
    -            if (publicKeyData!=null) {
    -                adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(publicKeyData);
    +                    .grantSudoToAdminUser(groovyTruth(grantUserSudo));
    +                    // login user's password now set to something random
    +                    // (could explicitly set with loginPassword)
    +            
    +            Boolean useKey = null;
    +            if (passwordToSet!=null) {
    +                adminBuilder.adminPassword(passwordToSet);
    +                useKey = false;
    --- End diff --
    
    yes, good spot.  and similar `isNonBlank` check in codepath above where `user` equals `loginUser` -- fixing


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23466128
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    +        private final ConfigBag config;
    +        private boolean preferPassword = false;
    +        private boolean tryDefaultKeys = true;
    +        private boolean requirePublicKey = true;
    +        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
    +        private boolean warnOnErrors = true;
    +        private boolean throwOnErrors = false;
    +        
    +        private boolean dirty = true;;
    +        
    +        private String privateKeyData;
    +        private String publicKeyData;
    +        private String password;
    +        
    +        private OsCredential(ConfigBag config) {
    +            this.config = config;
    +        }
    +
    +        /** throws if there are any problems */
    +        public OsCredential checkNotEmpty() {
    +            checkNoErrors();
    +            
    +            if (!hasKey() && !hasPassword()) {
    +                if (warningMessages.size()>0)
    +                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
    +                else 
    +                    throw new IllegalStateException("Could not find credentials");
    +            }
    +            return this;
    +        }
    +
    +        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
    +         * @return */
    +        public OsCredential checkNoErrors() {
    +            throwOnErrors(true);
    +            dirty();
    +            infer();
    +            return this;
    +        }
    +        
    +        public OsCredential logAnyWarnings() {
    +            if (!warningMessages.isEmpty())
    +                log.warn("When reading credentials: "+warningMessages);
    +            return this;
    +        }
    +
    +        public Set<String> getWarningMessages() {
    +            return warningMessages;
    +        }
    +        
    +        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
    +         * via {@link #preferPassword()} */
    +        public synchronized String get() {
    +            infer();
    +            
    +            if (isUsingPassword()) return password;
    +            if (hasKey()) return privateKeyData;
    +            return null;
    +        }
    +
    +        /** if there is no credential (ignores public key) */
    +        public boolean isEmpty() {
    +            return !hasKey() && !hasPassword();
    +        }
    +        public boolean hasKey() {
    +            infer();
    +            // key has stricter non-blank check than password
    +            return Strings.isNonBlank(privateKeyData);
    +        }
    +        public boolean hasPassword() {
    +            infer();
    +            // blank, even empty passwords are allowed
    +            return password!=null;
    +        }
    +        /** if a password is available, and either this is preferred over a key or there is no key */
    +        public boolean isUsingPassword() {
    +            return hasPassword() && (!hasKey() || preferPassword);
    +        }
    +        
    +        public String getPrivateKeyData() {
    +            infer();
    +            return privateKeyData;
    +        }
    +        public String getPublicKeyData() {
    +            infer();
    +            return publicKeyData;
    +        }
    +        public String getPassword() {
    +            infer();
    +            return password;
    +        }
    +        
    +        /** if both key and password supplied, prefer the key; the default */
    +        public OsCredential preferKey() { preferPassword = false; return dirty(); }
    +        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
    +        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
    +        
    +        /** if false, do not mind if there is no public key corresponding to any private key;
    +         * defaults to true; only applies if a private key is set */
    +        public OsCredential requirePublicKey(boolean requirePublicKey) {
    +            this.requirePublicKey = requirePublicKey;
    +            return dirty(); 
    +        }
    +        /** whether to check the private/public keys and passphrase are coherent; default true */
    +        public OsCredential doKeyValidation(boolean doKeyValidation) {
    +            this.doKeyValidation = doKeyValidation;
    +            return dirty();
    +        }
    +        /** if true (the default) this will look at default locations set on keys */
    +        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
    +            this.tryDefaultKeys = tryDefaultKeys;
    +            return dirty(); 
    +        }
    +        /** whether to log warnings on problems */
    +        public OsCredential warnOnErrors(boolean warnOnErrors) {
    +            this.warnOnErrors = warnOnErrors;
    +            return dirty(); 
    +        }
    +        /** whether to throw on problems */
    +        public OsCredential throwOnErrors(boolean throwOnErrors) {
    +            this.throwOnErrors = throwOnErrors;
    +            return dirty(); 
    +        }
    +        
    +        private OsCredential dirty() { dirty = true; return this; }
    +            
    +        public static OsCredential newInstance(ConfigBag config) {
    +            return new OsCredential(config);
    +        }
    +        
    +        private synchronized void infer() {
    +            if (!dirty) return;
    +            warningMessages.clear(); 
    +            
    +            log.debug("Inferring OS credentials");
    +            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
    +            password = config.get(LocationConfigKeys.PASSWORD);
    +            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
    +
    +            KeyPair privateKey = null;
    +            
    +            if (Strings.isBlank(privateKeyData)) {
    +                // look up private key files
    +                String privateKeyFiles = null;
    +                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
    +                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (Strings.isNonBlank(privateKeyFiles)) {
    +                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
    --- End diff --
    
    Ah, I see you write that in a comment directly below this!


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23526368
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    +            | ((stream.read() & 0xFF) << 8) | (stream.read() & 0xFF);
    +    }
    +    
    +    private static byte[] readBytesWithLength(InputStream stream) throws IOException {
    +        int len = readInt(stream);
    +        byte[] result = new byte[len];
    +        stream.read(result);
    +        return result;
    +    }
    +    
    +    private static void writeInt(OutputStream stream, int v) throws IOException {
    +        for (int shift = 24; shift >= 0; shift -= 8)
    +            stream.write((v >>> shift) & 0xFF);
    +    }
    +    private static void writeBytesWithLength(OutputStream stream, byte[] buf) throws IOException {
    +        writeInt(stream, buf.length);
    +        stream.write(buf);
    +    }
    +    
    +    private static String readType(InputStream stream) throws IOException { return new String(readBytesWithLength(stream)); }
    +    private static BigInteger readBigInt(InputStream stream) throws IOException { return new BigInteger(readBytesWithLength(stream)); }
    +
    +    public static String encodePublicKey(PublicKey key) {
    --- End diff --
    
    i spent a while looking and didn't find one


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:

    https://github.com/apache/incubator-brooklyn/pull/465


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23524429
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java ---
    @@ -71,13 +72,25 @@
         public static final ConfigKey<String> LOGIN_USER_PRIVATE_KEY_FILE = ConfigKeys.newStringConfigKey("loginUser.privateKeyFile",
                 "Custom private key for the user who logs in initially", null); 
         public static final ConfigKey<String> EXTRA_PUBLIC_KEY_DATA_TO_AUTH = ConfigKeys.newStringConfigKey("extraSshPublicKeyData",
    -            "Additional public key data to add to authorized_keys", null);
    +        "Additional public key data to add to authorized_keys", null);
    +    @SuppressWarnings("serial")
    +    public static final ConfigKey<List<String>> EXTRA_PUBLIC_KEYS_TO_AUTH = ConfigKeys.newConfigKey(new TypeToken<List<String>>() {}, 
    --- End diff --
    
    For consistency with other names, should this be `EXTRA_PUBLIC_KEY_FILES_TO_AUTH`?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23466967
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    +        private final ConfigBag config;
    +        private boolean preferPassword = false;
    +        private boolean tryDefaultKeys = true;
    +        private boolean requirePublicKey = true;
    +        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
    +        private boolean warnOnErrors = true;
    +        private boolean throwOnErrors = false;
    +        
    +        private boolean dirty = true;;
    +        
    +        private String privateKeyData;
    +        private String publicKeyData;
    +        private String password;
    +        
    +        private OsCredential(ConfigBag config) {
    +            this.config = config;
    +        }
    +
    +        /** throws if there are any problems */
    +        public OsCredential checkNotEmpty() {
    +            checkNoErrors();
    +            
    +            if (!hasKey() && !hasPassword()) {
    +                if (warningMessages.size()>0)
    +                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
    +                else 
    +                    throw new IllegalStateException("Could not find credentials");
    +            }
    +            return this;
    +        }
    +
    +        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
    +         * @return */
    +        public OsCredential checkNoErrors() {
    +            throwOnErrors(true);
    +            dirty();
    +            infer();
    +            return this;
    +        }
    +        
    +        public OsCredential logAnyWarnings() {
    +            if (!warningMessages.isEmpty())
    +                log.warn("When reading credentials: "+warningMessages);
    +            return this;
    +        }
    +
    +        public Set<String> getWarningMessages() {
    +            return warningMessages;
    +        }
    +        
    +        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
    +         * via {@link #preferPassword()} */
    +        public synchronized String get() {
    +            infer();
    +            
    +            if (isUsingPassword()) return password;
    +            if (hasKey()) return privateKeyData;
    +            return null;
    +        }
    +
    +        /** if there is no credential (ignores public key) */
    +        public boolean isEmpty() {
    +            return !hasKey() && !hasPassword();
    +        }
    +        public boolean hasKey() {
    +            infer();
    +            // key has stricter non-blank check than password
    +            return Strings.isNonBlank(privateKeyData);
    +        }
    +        public boolean hasPassword() {
    +            infer();
    +            // blank, even empty passwords are allowed
    +            return password!=null;
    +        }
    +        /** if a password is available, and either this is preferred over a key or there is no key */
    +        public boolean isUsingPassword() {
    +            return hasPassword() && (!hasKey() || preferPassword);
    +        }
    +        
    +        public String getPrivateKeyData() {
    +            infer();
    +            return privateKeyData;
    +        }
    +        public String getPublicKeyData() {
    +            infer();
    +            return publicKeyData;
    +        }
    +        public String getPassword() {
    +            infer();
    +            return password;
    +        }
    +        
    +        /** if both key and password supplied, prefer the key; the default */
    +        public OsCredential preferKey() { preferPassword = false; return dirty(); }
    +        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
    +        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
    +        
    +        /** if false, do not mind if there is no public key corresponding to any private key;
    +         * defaults to true; only applies if a private key is set */
    +        public OsCredential requirePublicKey(boolean requirePublicKey) {
    +            this.requirePublicKey = requirePublicKey;
    +            return dirty(); 
    +        }
    +        /** whether to check the private/public keys and passphrase are coherent; default true */
    +        public OsCredential doKeyValidation(boolean doKeyValidation) {
    +            this.doKeyValidation = doKeyValidation;
    +            return dirty();
    +        }
    +        /** if true (the default) this will look at default locations set on keys */
    +        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
    +            this.tryDefaultKeys = tryDefaultKeys;
    +            return dirty(); 
    +        }
    +        /** whether to log warnings on problems */
    +        public OsCredential warnOnErrors(boolean warnOnErrors) {
    +            this.warnOnErrors = warnOnErrors;
    +            return dirty(); 
    +        }
    +        /** whether to throw on problems */
    +        public OsCredential throwOnErrors(boolean throwOnErrors) {
    +            this.throwOnErrors = throwOnErrors;
    +            return dirty(); 
    +        }
    +        
    +        private OsCredential dirty() { dirty = true; return this; }
    +            
    +        public static OsCredential newInstance(ConfigBag config) {
    +            return new OsCredential(config);
    +        }
    +        
    +        private synchronized void infer() {
    +            if (!dirty) return;
    +            warningMessages.clear(); 
    +            
    +            log.debug("Inferring OS credentials");
    +            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
    +            password = config.get(LocationConfigKeys.PASSWORD);
    +            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
    +
    +            KeyPair privateKey = null;
    +            
    +            if (Strings.isBlank(privateKeyData)) {
    +                // look up private key files
    +                String privateKeyFiles = null;
    +                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
    +                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (Strings.isNonBlank(privateKeyFiles)) {
    +                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
    --- End diff --
    
    yeah - the format is legacy, and bad


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23523860
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    --- End diff --
    
    I think that I'd prefer an explicit configuration option to enable creating new keys. The question is what use-case this is covering.
    
    If it is for advanced users, and requires an explicit act to set the config value to blank, then the user could equally well have set a more explicit config key to tell brooklyn to crate the keypair.
    
    If it is for newbies that don't have ssh keys set up yet (and don't intend to), then I think the automatic key-gen is a false economy for them. At some point they'll want to log in, so would have to manually find the private key in the debug log and create an appropriately permissioned file with it. That sounds more onerous than running a standard key-gen command up front.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522338
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    --- End diff --
    
    makes sense.  have changed `get()` to `getPreferredCredential()`, and not used if we've already done an explicit check


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521372
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -752,6 +762,17 @@ protected JcloudsSshMachineLocation obtainOnce(ConfigBag setup) throws NoMachine
                         List<String> cmds = ImmutableList.of(IptablesCommands.iptablesServiceStop(), IptablesCommands.iptablesServiceStatus());
                         sshMachineLocation.execCommands("Stopping iptables", cmds);
                     }
    +                
    +                List<String> extraKeyUrlsToAuth = setup.get(EXTRA_PUBLIC_KEYS_TO_AUTH);
    +                if (extraKeyUrlsToAuth!=null && !extraKeyUrlsToAuth.isEmpty()) {
    +                    List<String> extraKeyDataToAuth = MutableList.of();
    +                    for (String keyUrl: extraKeyUrlsToAuth) {
    +                        extraKeyDataToAuth.add(ResourceUtils.create().getResourceAsString(keyUrl));
    +                    }
    +                    sshMachineLocation.execCommands("Authorizing ssh keys", 
    +                        MutableList.of(new AuthorizeRSAPublicKeys(extraKeyDataToAuth).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX)));
    --- End diff --
    
    Personal preference: I prefer us using `ImmutableList` everywhere that we expect no nulls and expect not to modify it. In this case, a null is going to be a programming error / bug somewhere so `ImmutableList` feels better.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521770
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    --- End diff --
    
    I'd prefer `credential.getPassword()` rather than `credential.get()` - it's much more explicit, rather than relying on `.get()` returning password because `isUsingPassword()`. Same for line below.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin closed the pull request at:

    https://github.com/apache/incubator-brooklyn/pull/465


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520397
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    --- End diff --
    
    I'd pass in the cause as well. Is there any more specific exception we can catch here? Feels risky that we could get other exceptions and swallow them, incorrectly reporting it as a "wrong passphrase".


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522095
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    -        try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(source, passphrase!=null ? passphrase.toCharArray() : new char[0]);
    -            return store;
             } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            Exceptions.propagateIfFatal(e);
    +
    +            // older code relied on PEMReader, now deprecated
    +            // replaced with above based on http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser
    +            // passes the same tests (Jan 2015) but leaving the old code as a fallback for the time being 
    +
    +            input = new ByteArrayInputStream(cache);
    +            try {
    +                Security.addProvider(new BouncyCastleProvider());
    +                PEMReader pr = new PEMReader(new InputStreamReader(input), new PasswordFinder() {
    +                    public char[] getPassword() {
    +                        return passphrase!=null ? passphrase.toCharArray() : new char[0];
    +                    }
    +                });
    +                KeyPair result = (KeyPair) pr.readObject();
    +                pr.close();
    +                if (result==null)
    +                    throw Exceptions.propagate(e);
    +                
    +                log.warn("PEMParser failed when PEMReader succeeded, with "+result+"; had: "+e);
    --- End diff --
    
    +1 adding the word `deprecated`.  But I really want this one brought to our attention so leaving it log warning.  We can exclude the logger or (better) patch.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23523268
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    +                pubKey = SecureKeys.toPub(newKeyPair);
    +                privKey = SecureKeys.toPem(newKeyPair);
    +                LOG.debug("Brooklyn key being created for "+user+" at new machine "+this+" is:\n"+privKey);
                 }
    +            // ensure credential is not used any more, as we have extracted al useful info
    +            credential = null;
                 
    -        } else {
                 // Create the user
                 // note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
                 AdminAccess.Builder adminBuilder = AdminAccess.builder()
                         .adminUsername(user)
    -                    .adminPassword(password)
    -                    .grantSudoToAdminUser(groovyTruth(grantUserSudo))
    -                    .resetLoginPassword(true)
    -                    .loginPassword(password);
    -
    -            if (publicKeyData!=null) {
    -                adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(publicKeyData);
    +                    .grantSudoToAdminUser(groovyTruth(grantUserSudo));
    +                    // login user's password now set to something random
    +                    // (could explicitly set with loginPassword)
    +            
    +            Boolean useKey = null;
    +            if (passwordToSet!=null) {
    +                adminBuilder.adminPassword(passwordToSet);
    +                useKey = false;
    --- End diff --
    
    have removed and added quite a bit more logging for this, as it is something we want to be able to drill down on


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520737
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    -        try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(source, passphrase!=null ? passphrase.toCharArray() : new char[0]);
    -            return store;
             } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            Exceptions.propagateIfFatal(e);
    +
    +            // older code relied on PEMReader, now deprecated
    +            // replaced with above based on http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser
    +            // passes the same tests (Jan 2015) but leaving the old code as a fallback for the time being 
    +
    +            input = new ByteArrayInputStream(cache);
    +            try {
    +                Security.addProvider(new BouncyCastleProvider());
    +                PEMReader pr = new PEMReader(new InputStreamReader(input), new PasswordFinder() {
    +                    public char[] getPassword() {
    +                        return passphrase!=null ? passphrase.toCharArray() : new char[0];
    +                    }
    +                });
    +                KeyPair result = (KeyPair) pr.readObject();
    +                pr.close();
    +                if (result==null)
    +                    throw Exceptions.propagate(e);
    +                
    +                log.warn("PEMParser failed when PEMReader succeeded, with "+result+"; had: "+e);
     
    -    /** see {@link #getTrustManager(KeyStore, Class)}, matching any type */
    -    public static TrustManager getTrustManager(KeyStore trustStore) {
    -        return getTrustManager(trustStore, null);
    -    }
    -    /** returns the trust manager inferred from trustStore, matching the type (if not null);
    -     * throws exception if there are none, or if there are multiple */
    -    @SuppressWarnings("unchecked")
    -    public static <T extends TrustManager> T getTrustManager(KeyStore trustStore, Class<T> type) {
    -        try {
    -            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
    -                    TrustManagerFactory.getDefaultAlgorithm());
    -            tmf.init(trustStore);
    -            T result = null;
    -            for (TrustManager tm: tmf.getTrustManagers()) {
    -                if (type==null || type.isInstance(tm)) {
    -                    if (result!=null)
    -                        throw new IllegalStateException("Multiple trust managers matching "+type+" inferred from "+trustStore);
    -                    result = (T)tm;
    -                }
    -            }
    -            if (result!=null)
                     return result;
    -            throw new NoSuchElementException("No trust manager matching "+type+" can be inferred from "+trustStore);
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    -    
    -    public static X509TrustManager getTrustManager(X509Certificate certificate) {
    -        try {
    -            KeyStore ks = newKeyStore();
    -            ks.setCertificateEntry("", certificate);
    -            return getTrustManager(ks, X509TrustManager.class);
    -        } catch (KeyStoreException e) {
    -            throw Exceptions.propagate(e);
    +
    +            } catch (Exception e2) {
    +                Exceptions.propagateIfFatal(e2);
    +                throw Exceptions.propagate(e);
    +            }
             }
         }
     
    -    /** converts a certificate to the canonical implementation, commonly sun.security.x509.X509CertImpl,
    -     * which is required in some places -- the Bouncy Castle X509 impl is not accepted 
    -     * (e.g. where certs are chained, passed to trust manager) */
    -    public static X509Certificate getCanonicalImpl(X509Certificate inCert) {
    -        try {
    -            KeyStore store = SecureKeys.newKeyStore();
    -            store.setCertificateEntry("to-canonical", inCert);
    -            ByteArrayOutputStream out = new ByteArrayOutputStream();
    -            store.store(out, "".toCharArray());
    -
    -            KeyStore store2 = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store2.load(new ByteArrayInputStream(out.toByteArray()), "".toCharArray());
    -            return (X509Certificate) store2.getCertificate("to-canonical");
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    +    /** because KeyPair.equals is not implemented :( */
    +    public static boolean equal(KeyPair k1, KeyPair k2) {
    +        return Objects.equal(k2.getPrivate(), k1.getPrivate()) && Objects.equal(k2.getPrivate(), k1.getPrivate());
    --- End diff --
    
    Looks wrong. Did you mean for one of the `Objects.equal` to compare the `getPublic()`?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23526358
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    +            | ((stream.read() & 0xFF) << 8) | (stream.read() & 0xFF);
    +    }
    +    
    +    private static byte[] readBytesWithLength(InputStream stream) throws IOException {
    +        int len = readInt(stream);
    +        byte[] result = new byte[len];
    --- End diff --
    
    agree, now:
    
            if (len<10 || len>100000)
                throw new IllegalStateException("Invalid stream header: length "+len);



---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#issuecomment-71623771
  
    fixed a typo.  also added some simple CLI stuff; not related, but very small and it would otherwise conflict with this PR.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522012
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    +                pubKey = SecureKeys.toPub(newKeyPair);
    +                privKey = SecureKeys.toPem(newKeyPair);
    +                LOG.debug("Brooklyn key being created for "+user+" at new machine "+this+" is:\n"+privKey);
                 }
    +            // ensure credential is not used any more, as we have extracted al useful info
    +            credential = null;
                 
    -        } else {
                 // Create the user
                 // note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
                 AdminAccess.Builder adminBuilder = AdminAccess.builder()
                         .adminUsername(user)
    -                    .adminPassword(password)
    -                    .grantSudoToAdminUser(groovyTruth(grantUserSudo))
    -                    .resetLoginPassword(true)
    -                    .loginPassword(password);
    -
    -            if (publicKeyData!=null) {
    -                adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(publicKeyData);
    +                    .grantSudoToAdminUser(groovyTruth(grantUserSudo));
    +                    // login user's password now set to something random
    +                    // (could explicitly set with loginPassword)
    +            
    +            Boolean useKey = null;
    +            if (passwordToSet!=null) {
    --- End diff --
    
    `passwordToSet` can presumably never be null at this point - we'll have auto-generated a random password if one was not supplied.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520154
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
    --- End diff --
    
    Given the class extends `SecureKeysWithoutBouncyCastle`, it's surprising to see this static code in it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23526262
  
    --- Diff: core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java ---
    @@ -21,77 +21,134 @@
     import static org.testng.Assert.assertEquals;
     import static org.testng.Assert.assertTrue;
     
    +import org.testng.Assert;
     import org.testng.annotations.Test;
     
    +import brooklyn.location.basic.LocationConfigUtils.OsCredential;
     import brooklyn.util.config.ConfigBag;
     
    +@Test
     public class LocationConfigUtilsTest {
     
    -    public static final String SSH_PRIVATE_KEY_FILE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa");
    -    public static final String SSH_PUBLIC_KEY_FILE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa.pub");
    +    // set these system properties differently if needed to fix your tests
    +    public static final String SSH_PRIVATE_KEY_FILE_WITH_TILDE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa");
    +    public static final String SSH_PUBLIC_KEY_FILE_WITH_TILDE = System.getProperty("sshPublicKey", "~/.ssh/id_rsa.pub");
    +    // these should work as they are on classpath
    +    public static final String SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE = System.getProperty("sshPrivateKeyWithPassphrase", "/brooklyn/util/crypto/sample_rsa_passphrase.pem");
    +    public static final String SSH_PRIVATE_KEY_FILE = System.getProperty("sshPrivateKeySample", "/brooklyn/location/basic/sample_id_rsa");
    +    public static final String SSH_PUBLIC_KEY_FILE = System.getProperty("sshPublicKeySample", "/brooklyn/location/basic/sample_id_rsa.pub");
         
    -    @Test(groups="Integration")
         public void testPreferPrivateKeyDataOverFile() throws Exception {
             ConfigBag config = ConfigBag.newInstance();
             config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
             config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
             
    -        String data = LocationConfigUtils.getPrivateKeyData(config);
    +        OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
    +        Assert.assertTrue(creds.hasKey());
    +        // warnings, as it is malformed
    +        Assert.assertFalse(creds.getWarningMessages().isEmpty());
    +
    +        String data = creds.getPrivateKeyData();
             assertEquals(data, "mydata");
         }
    -    
    -    @Test(groups="Integration")
    -    public void testPreferPubilcKeyDataOverFile() throws Exception {
    +
    +    @Test(expectedExceptions=IllegalStateException.class)
    +    public void testInvalidKeyData() throws Exception {
    +        ConfigBag config = ConfigBag.newInstance();
    +        config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
    +        
    +        OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
    +        Assert.assertTrue(creds.hasKey());
    +        Assert.assertFalse(creds.getWarningMessages().isEmpty());
    +        
    +        creds.checkNoErrors();
    +    }
    +
    +    public void testPreferPublicKeyDataOverFileAndNoPrivateKeyRequired() throws Exception {
             ConfigBag config = ConfigBag.newInstance();
             config.put(LocationConfigKeys.PUBLIC_KEY_DATA, "mydata");
             config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE);
    +        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "");
             
    -        String data = LocationConfigUtils.getPublicKeyData(config);
    +        OsCredential creds = LocationConfigUtils.getOsCredential(config);
    +        String data = creds.getPublicKeyData();
             assertEquals(data, "mydata");
    +        Assert.assertNull(creds.get());
    +        Assert.assertFalse(creds.hasPassword());
    +        Assert.assertFalse(creds.hasKey());
    +        // and not even any warnings here
    +        Assert.assertTrue(creds.getWarningMessages().isEmpty());
         }
         
    -    @Test(groups="Integration")
    -    public void testReadsPrivateKeyFileWithTildaPath() throws Exception {
    +    @Test(groups="Integration")  // requires ~/.ssh/id_rsa
    +    public void testReadsPrivateKeyFileWithTildePath() throws Exception {
             ConfigBag config = ConfigBag.newInstance();
    -        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
    -        
    -        String data = LocationConfigUtils.getPrivateKeyData(config);
    +        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);
    +
    +        // don't mind if it has a passphrase
    +        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).get();
             assertTrue(data != null && data.length() > 0);
         }
         
    -    @Test(groups="Integration")
    +    @Test(groups="Integration")  // requires ~/.ssh/passphrase-id_rsa
    --- End diff --
    
    comment was wrong, it uses a key that is added to classpath


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23524964
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    +            | ((stream.read() & 0xFF) << 8) | (stream.read() & 0xFF);
    +    }
    +    
    +    private static byte[] readBytesWithLength(InputStream stream) throws IOException {
    +        int len = readInt(stream);
    +        byte[] result = new byte[len];
    +        stream.read(result);
    +        return result;
    +    }
    +    
    +    private static void writeInt(OutputStream stream, int v) throws IOException {
    +        for (int shift = 24; shift >= 0; shift -= 8)
    +            stream.write((v >>> shift) & 0xFF);
    +    }
    +    private static void writeBytesWithLength(OutputStream stream, byte[] buf) throws IOException {
    +        writeInt(stream, buf.length);
    +        stream.write(buf);
    +    }
    +    
    +    private static String readType(InputStream stream) throws IOException { return new String(readBytesWithLength(stream)); }
    +    private static BigInteger readBigInt(InputStream stream) throws IOException { return new BigInteger(readBytesWithLength(stream)); }
    +
    +    public static String encodePublicKey(PublicKey key) {
    --- End diff --
    
    Surprised there's not some utility method in one of our dependencies that already does this, but I haven't looked at all.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522150
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    +                pubKey = SecureKeys.toPub(newKeyPair);
    +                privKey = SecureKeys.toPem(newKeyPair);
    +                LOG.debug("Brooklyn key being created for "+user+" at new machine "+this+" is:\n"+privKey);
                 }
    +            // ensure credential is not used any more, as we have extracted al useful info
    +            credential = null;
                 
    -        } else {
                 // Create the user
                 // note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
                 AdminAccess.Builder adminBuilder = AdminAccess.builder()
                         .adminUsername(user)
    -                    .adminPassword(password)
    -                    .grantSudoToAdminUser(groovyTruth(grantUserSudo))
    -                    .resetLoginPassword(true)
    -                    .loginPassword(password);
    -
    -            if (publicKeyData!=null) {
    -                adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(publicKeyData);
    +                    .grantSudoToAdminUser(groovyTruth(grantUserSudo));
    +                    // login user's password now set to something random
    +                    // (could explicitly set with loginPassword)
    +            
    +            Boolean useKey = null;
    +            if (passwordToSet!=null) {
    +                adminBuilder.adminPassword(passwordToSet);
    +                useKey = false;
    --- End diff --
    
    This looks wrong, so not sure how it works. Presumably we'll always go into this if branch because `passwordToSet` is never null. Therefore we'll always set `userKey = false`.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23523565
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java ---
    @@ -42,7 +44,9 @@
      * X509v3CertificateBuilder drags in an add'l dependency (bcmail) and is harder to use. */
     @SuppressWarnings("deprecation")
     public class FluentKeySigner {
    -    
    +
    +    static { Security.addProvider(new BouncyCastleProvider()); }
    --- End diff --
    
    Sounds sensible, I think. Is there anything beyond bouncy castle currently that we'd want to include in a `BrooklynInitialization`? If it's just bouncy castle, then maybe we live with code as-is for now, with an appropriate comment somewhere (e.g. `LocalManagementContext` or the `Main` class?) about this initialization.
    
    I presume that would be at the level of the `ManagementContext` so wouldn't know about initializing web-apps etc? 


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23524743
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    +            | ((stream.read() & 0xFF) << 8) | (stream.read() & 0xFF);
    +    }
    +    
    +    private static byte[] readBytesWithLength(InputStream stream) throws IOException {
    +        int len = readInt(stream);
    +        byte[] result = new byte[len];
    --- End diff --
    
    Perhaps guard this - if `len` is big then there's something wrong (given the context of this method). Better to throw a graceful exception rather than cause an OutOfMemoryError.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23524691
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    --- End diff --
    
    Worth a unit test for this kind of thing, I think (package-private, annotated as `@VisibleForTesting`, and an easy unit test to write). same for the other methods here.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522109
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    -        try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(source, passphrase!=null ? passphrase.toCharArray() : new char[0]);
    -            return store;
             } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            Exceptions.propagateIfFatal(e);
    +
    +            // older code relied on PEMReader, now deprecated
    +            // replaced with above based on http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser
    +            // passes the same tests (Jan 2015) but leaving the old code as a fallback for the time being 
    +
    +            input = new ByteArrayInputStream(cache);
    +            try {
    +                Security.addProvider(new BouncyCastleProvider());
    +                PEMReader pr = new PEMReader(new InputStreamReader(input), new PasswordFinder() {
    +                    public char[] getPassword() {
    +                        return passphrase!=null ? passphrase.toCharArray() : new char[0];
    +                    }
    +                });
    +                KeyPair result = (KeyPair) pr.readObject();
    +                pr.close();
    +                if (result==null)
    +                    throw Exceptions.propagate(e);
    +                
    +                log.warn("PEMParser failed when PEMReader succeeded, with "+result+"; had: "+e);
     
    -    /** see {@link #getTrustManager(KeyStore, Class)}, matching any type */
    -    public static TrustManager getTrustManager(KeyStore trustStore) {
    -        return getTrustManager(trustStore, null);
    -    }
    -    /** returns the trust manager inferred from trustStore, matching the type (if not null);
    -     * throws exception if there are none, or if there are multiple */
    -    @SuppressWarnings("unchecked")
    -    public static <T extends TrustManager> T getTrustManager(KeyStore trustStore, Class<T> type) {
    -        try {
    -            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
    -                    TrustManagerFactory.getDefaultAlgorithm());
    -            tmf.init(trustStore);
    -            T result = null;
    -            for (TrustManager tm: tmf.getTrustManagers()) {
    -                if (type==null || type.isInstance(tm)) {
    -                    if (result!=null)
    -                        throw new IllegalStateException("Multiple trust managers matching "+type+" inferred from "+trustStore);
    -                    result = (T)tm;
    -                }
    -            }
    -            if (result!=null)
                     return result;
    -            throw new NoSuchElementException("No trust manager matching "+type+" can be inferred from "+trustStore);
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    -    
    -    public static X509TrustManager getTrustManager(X509Certificate certificate) {
    -        try {
    -            KeyStore ks = newKeyStore();
    -            ks.setCertificateEntry("", certificate);
    -            return getTrustManager(ks, X509TrustManager.class);
    -        } catch (KeyStoreException e) {
    -            throw Exceptions.propagate(e);
    +
    +            } catch (Exception e2) {
    +                Exceptions.propagateIfFatal(e2);
    +                throw Exceptions.propagate(e);
    +            }
             }
         }
     
    -    /** converts a certificate to the canonical implementation, commonly sun.security.x509.X509CertImpl,
    -     * which is required in some places -- the Bouncy Castle X509 impl is not accepted 
    -     * (e.g. where certs are chained, passed to trust manager) */
    -    public static X509Certificate getCanonicalImpl(X509Certificate inCert) {
    -        try {
    -            KeyStore store = SecureKeys.newKeyStore();
    -            store.setCertificateEntry("to-canonical", inCert);
    -            ByteArrayOutputStream out = new ByteArrayOutputStream();
    -            store.store(out, "".toCharArray());
    -
    -            KeyStore store2 = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store2.load(new ByteArrayInputStream(out.toByteArray()), "".toCharArray());
    -            return (X509Certificate) store2.getCertificate("to-canonical");
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    +    /** because KeyPair.equals is not implemented :( */
    +    public static boolean equal(KeyPair k1, KeyPair k2) {
    +        return Objects.equal(k2.getPrivate(), k1.getPrivate()) && Objects.equal(k2.getPrivate(), k1.getPrivate());
    --- End diff --
    
    yes - good spot


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23467013
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    --- End diff --
    
    yeah - probably worth refactoring.  are you okay with me marking it `@Beta` for now, and we can do that later?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522416
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    --- End diff --
    
    now using `isEmpty()`


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23465125
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    --- End diff --
    
    This code would be cleaner if there was a separate builder, and then OsCredential was immutable. With that pattern, we wouldn't need calls to `infer()` in each method, or the `dirty()`. We'd also have a clearer separation of which fields are for configuring it, and which are about the actual state (and thus behaviour of the constructed `OsCredential`).
    
    It would also hide the many builder methods from users of the `OsCredential`, simplifying things for such programmers.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23525180
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    --- End diff --
    
    Ah, I see they are on the super-class (`SecureKeysWithoutBouncyCastle`). Therefore I presume this comment can be ignored (though I haven't gone through to check all methods are there with the same signature).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
GitHub user ahgittin reopened a pull request:

    https://github.com/apache/incubator-brooklyn/pull/465

    Jclouds tidy

    refactor to share code for credentials inferencing; then expand this to:
    * validate keys, including passphrase (fail fast if bad passphrase)
    * support add'l public keys to be authorized
    * support add'l first-boot commands as part of the template options script


You can merge this pull request into a Git repository by running:

    $ git pull https://github.com/ahgittin/incubator-brooklyn jclouds-tidy

Alternatively you can review and apply these changes as the patch at:

    https://github.com/apache/incubator-brooklyn/pull/465.patch

To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:

    This closes #465
    
----
commit fa79e20dbf895520b411965779034f0baee01f30
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T10:33:16Z

    tidy up how os credentials are inferred
    
    share lookup routines in preparation for adding validation

commit c3828fbffb6bad0006456e4f828f56f4cfc44bb2
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T14:55:47Z

    validate public, private key and passphrase *before* provisioning
    
    and give good feedback through logging and errors

commit 50395595f9a808af254a715516adce6b1ae5d93c
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T20:42:08Z

    add extraSshPublicKeys options to jclouds
    
    allows extra public keys to be supplied to authorized_keys on provisioned vm's

commit aafddb59c576df3842ed70a15e759426cfe0ee4d
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T21:18:17Z

    add a custom template-options script in case sudoers or something else needs changing on first boot

commit f4346ef8009a13f03c6a6ee4f03777bfeb0bbb21
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Date:   2015-01-22T21:38:52Z

    add + fix location ssh tests
    
    including a sample yaml for quickly trying lots of weird combos

----


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520547
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    -        try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(source, passphrase!=null ? passphrase.toCharArray() : new char[0]);
    -            return store;
             } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            Exceptions.propagateIfFatal(e);
    +
    +            // older code relied on PEMReader, now deprecated
    +            // replaced with above based on http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser
    +            // passes the same tests (Jan 2015) but leaving the old code as a fallback for the time being 
    +
    +            input = new ByteArrayInputStream(cache);
    +            try {
    +                Security.addProvider(new BouncyCastleProvider());
    +                PEMReader pr = new PEMReader(new InputStreamReader(input), new PasswordFinder() {
    +                    public char[] getPassword() {
    +                        return passphrase!=null ? passphrase.toCharArray() : new char[0];
    +                    }
    +                });
    +                KeyPair result = (KeyPair) pr.readObject();
    +                pr.close();
    +                if (result==null)
    +                    throw Exceptions.propagate(e);
    +                
    +                log.warn("PEMParser failed when PEMReader succeeded, with "+result+"; had: "+e);
    --- End diff --
    
    Can we include the word "deprecated" in the message? e.g. `"PEMParser failed when deprecated PEMReader succeeded, with "+result+"; had: "+e`.
    Perhaps we should log the exception at debug as well - with just the first line and no stacktrace, we mind find it impossible to fix some kinds of exceptions.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520516
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    --- End diff --
    
    ? -- most exceptions have a no-arg constructor


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23526193
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocationConfig.java ---
    @@ -71,13 +72,25 @@
         public static final ConfigKey<String> LOGIN_USER_PRIVATE_KEY_FILE = ConfigKeys.newStringConfigKey("loginUser.privateKeyFile",
                 "Custom private key for the user who logs in initially", null); 
         public static final ConfigKey<String> EXTRA_PUBLIC_KEY_DATA_TO_AUTH = ConfigKeys.newStringConfigKey("extraSshPublicKeyData",
    -            "Additional public key data to add to authorized_keys", null);
    +        "Additional public key data to add to authorized_keys", null);
    +    @SuppressWarnings("serial")
    +    public static final ConfigKey<List<String>> EXTRA_PUBLIC_KEYS_TO_AUTH = ConfigKeys.newConfigKey(new TypeToken<List<String>>() {}, 
    --- End diff --
    
    agree, `EXTRA_PUBLIC_KEY_URLS_TO_AUTH` (here we can accept urls, falling back to file format)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23525919
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    +                if (!loggedSshKeysHint && !config.containsKey(PRIVATE_KEY_FILE)) {
    +                    loggedSshKeysHint = true;
    +                    LOG.info("Default SSH keys not found or not usable; will create new keys for each machine. "
    +                        + "Create ~/.ssh/id_rsa or "
    +                        + "set "+PRIVATE_KEY_FILE.getName()+" / "+PRIVATE_KEY_PASSPHRASE.getName()+" / "+PASSWORD.getName()+" "
    +                        + "as appropriate for this location if you wish to be able to log in without Brooklyn.");
                     }
    +                KeyPair newKeyPair = SecureKeys.newKeyPair();
    --- End diff --
    
    This is for both use cases.  I pretty much agree with your suggestion but that could be a new feature (ie not in this PR).  All I've done here is swap the random per-machine password with a random per-machine key, because (a) it's more secure and (b) an increasing number of VM's don't support password-ssh login.
    
    for the advanced use case, i like an explicit `create_new_key_per_machine`.  in this case i would not write it to the file system, but we make the key available through REST API or GUI.  (by the way, currently the lookup procedure is probably even worse than you expect:  we don't know what machine is being provisioned here, so if there are several machines it's going to trial-and-error to correlate.)
    
    if this config key were not set, then in the new user case we could then create a `brooklyn_id_rsa` and `.pub` in `MGMT_BASE_DIR` (which is used subsequently as the default).  but i would only want to do this if it's just the one ssh key, and i don't want to lose the capability of new keys per machine.
    
    have added comment to this effect.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520213
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    --- End diff --
    
    Exceptions should pretty much always just have two constructors: one that takes a message, and one that takes a message+cause. The no-arg constructor is not used, and let's keep it that way by deleting it.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521347
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java ---
    @@ -42,7 +44,9 @@
      * X509v3CertificateBuilder drags in an add'l dependency (bcmail) and is harder to use. */
     @SuppressWarnings("deprecation")
    --- End diff --
    
    i'll refactor to use the fully qualified class name everywhere, that way we can suppress deprecations on a per-line basis not class-wide


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521788
  
    --- Diff: locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java ---
    @@ -1305,118 +1326,148 @@ public UserCreation(LoginCredentials creds, List<Statement> statements) {
          *   
          * @param image  The image being used to create the VM
          * @param config Configuration for creating the VM
    -     * @return       The commands required to create the user, along with the expected login credentials.
    +     * @return       The commands required to create the user, along with the expected login credentials for that user,
    +     * or null if we are just going to use those from jclouds.
          */
         protected UserCreation createUserStatements(@Nullable Image image, ConfigBag config) {
    -        //NB: we ignore private key here because, by default we probably should not be installing it remotely;
    -        //also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
    -        //but not elsewhere, e.g. on rackspace).
    +        //NB: private key is not installed remotely, just used to get/validate the public key
             
    -        LoginCredentials loginCreds = null;
    +        LoginCredentials createdUserCreds = null;
             String user = getUser(config);
             String explicitLoginUser = config.get(LOGIN_USER);
             String loginUser = groovyTruth(explicitLoginUser) ? explicitLoginUser : (image != null && image.getDefaultCredentials() != null) ? image.getDefaultCredentials().identity : null;
             Boolean dontCreateUser = config.get(DONT_CREATE_USER);
             Boolean grantUserSudo = config.get(GRANT_USER_SUDO);
    -        String publicKeyData = LocationConfigUtils.getPublicKeyData(config);
    -        String privateKeyData = LocationConfigUtils.getPrivateKeyData(config);
    -        String explicitPassword = config.get(PASSWORD);
    -        String password = groovyTruth(explicitPassword) ? explicitPassword : Identifiers.makeRandomId(12);
    +        OsCredential credential = LocationConfigUtils.getOsCredential(config);
    +        credential.checkNoErrors().logAnyWarnings();
    +        String passwordToSet = Strings.isNonBlank(credential.getPassword()) ? credential.getPassword() : Identifiers.makeRandomId(12);
             List<Statement> statements = Lists.newArrayList();
             
             if (groovyTruth(dontCreateUser)) {
    -            // TODO For dontCreateUser, we probably only want to treat it special if user was explicitly supplied
    -            // (rather than it just being the default config key value). If user was explicit, then should
    -            // set the password + authorize the key for that user. Presumably the caller knows that this
    -            // user pre-exists on the given VM image.
    +            // dontCreateUser:
    +            // if caller has not specified a user, we'll just continue to use the loginUser;
    +            // if caller *has*, we set up our credentials assuming that user and credentials already exist
    +            
                 if (!groovyTruth(user)) {
    -                // loginCreds result will be null; use creds returned by jclouds on the node
    +                // createdUserCreds returned from this method will be null; 
    +                // we will use the creds returned by jclouds on the node
                     LOG.info("Not setting up any user (subsequently using loginUser {})", user, loginUser);
                     config.put(USER, loginUser);
                     
                 } else {
    -                LOG.info("Not creating user {}, and not setting its password or authorizing keys", user);
    -                
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    -                } else if (explicitPassword != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).password(password).build();
    +                LOG.info("Not creating user {}, and not installing its password or authorizing keys (assuming it exists)", user);
    +
    +                if (credential.isUsingPassword()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).password(credential.get()).build();
    +                } else if (credential.hasKey()) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.get()).build();
                     }
                 }
                 
    -        } else if (!groovyTruth(user) || user.equals(loginUser)) {
    +        } else if (Strings.isBlank(user) || user.equals(loginUser) || user.equals(ROOT_USERNAME)) {
                 // For subsequent ssh'ing, we'll be using the loginUser
    -            if (!groovyTruth(user)) {
    -                config.put(USER, loginUser);
    +            if (Strings.isBlank(user)) {
    +                user = loginUser;
    +                config.put(USER, user);
                 }
     
                 // Using the pre-existing loginUser; setup the publicKey/password so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), loginUser, password));
    -                loginCreds = LoginCredentials.builder().user(loginUser).password(password).build();
    +            if (Strings.isNonBlank(passwordToSet)) {
    +                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), user, passwordToSet));
    +                createdUserCreds = LoginCredentials.builder().user(user).password(passwordToSet).build();
                 }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+loginUser+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(loginUser).privateKey(privateKeyData).build();
    +            if (Strings.isNonBlank(credential.getPublicKeyData())) {
    +                statements.add(new AuthorizeRSAPublicKeys("~"+user+"/.ssh", ImmutableList.of(credential.getPublicKeyData())));
    +                if (!credential.isUsingPassword() && Strings.isNonBlank(credential.getPrivateKeyData())) {
    +                    createdUserCreds = LoginCredentials.builder().user(user).privateKey(credential.getPrivateKeyData()).build();
                     }
                 }
                 
    -        } else if (user.equals(ROOT_USERNAME)) {
    -            // Authorizes the public-key and sets password for the root user, so can login as expected
    -            if (password != null) {
    -                statements.add(new ReplaceShadowPasswordEntry(Sha512Crypt.function(), ROOT_USERNAME, password));
    -                loginCreds = LoginCredentials.builder().user(user).password(password).build();
    -            }
    -            if (publicKeyData!=null) {
    -                statements.add(new AuthorizeRSAPublicKeys("~"+ROOT_USERNAME+"/.ssh", ImmutableList.of(publicKeyData)));
    -                if (privateKeyData != null) {
    -                    loginCreds = LoginCredentials.builder().user(user).privateKey(privateKeyData).build();
    +        } else {
    +            String pubKey = credential.getPublicKeyData();
    +            String privKey = credential.getPrivateKeyData();
    +            
    +            if (credential.get()==null) {
    --- End diff --
    
    This is confusing code initially - hard to guess what `credential.get()` does, compared to `credential.getXyz()` for getting public key data, private key data, etc.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23466090
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    +        private final ConfigBag config;
    +        private boolean preferPassword = false;
    +        private boolean tryDefaultKeys = true;
    +        private boolean requirePublicKey = true;
    +        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
    +        private boolean warnOnErrors = true;
    +        private boolean throwOnErrors = false;
    +        
    +        private boolean dirty = true;;
    +        
    +        private String privateKeyData;
    +        private String publicKeyData;
    +        private String password;
    +        
    +        private OsCredential(ConfigBag config) {
    +            this.config = config;
    +        }
    +
    +        /** throws if there are any problems */
    +        public OsCredential checkNotEmpty() {
    +            checkNoErrors();
    +            
    +            if (!hasKey() && !hasPassword()) {
    +                if (warningMessages.size()>0)
    +                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
    +                else 
    +                    throw new IllegalStateException("Could not find credentials");
    +            }
    +            return this;
    +        }
    +
    +        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
    +         * @return */
    +        public OsCredential checkNoErrors() {
    +            throwOnErrors(true);
    +            dirty();
    +            infer();
    +            return this;
    +        }
    +        
    +        public OsCredential logAnyWarnings() {
    +            if (!warningMessages.isEmpty())
    +                log.warn("When reading credentials: "+warningMessages);
    +            return this;
    +        }
    +
    +        public Set<String> getWarningMessages() {
    +            return warningMessages;
    +        }
    +        
    +        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
    +         * via {@link #preferPassword()} */
    +        public synchronized String get() {
    +            infer();
    +            
    +            if (isUsingPassword()) return password;
    +            if (hasKey()) return privateKeyData;
    +            return null;
    +        }
    +
    +        /** if there is no credential (ignores public key) */
    +        public boolean isEmpty() {
    +            return !hasKey() && !hasPassword();
    +        }
    +        public boolean hasKey() {
    +            infer();
    +            // key has stricter non-blank check than password
    +            return Strings.isNonBlank(privateKeyData);
    +        }
    +        public boolean hasPassword() {
    +            infer();
    +            // blank, even empty passwords are allowed
    +            return password!=null;
    +        }
    +        /** if a password is available, and either this is preferred over a key or there is no key */
    +        public boolean isUsingPassword() {
    +            return hasPassword() && (!hasKey() || preferPassword);
    +        }
    +        
    +        public String getPrivateKeyData() {
    +            infer();
    +            return privateKeyData;
    +        }
    +        public String getPublicKeyData() {
    +            infer();
    +            return publicKeyData;
    +        }
    +        public String getPassword() {
    +            infer();
    +            return password;
    +        }
    +        
    +        /** if both key and password supplied, prefer the key; the default */
    +        public OsCredential preferKey() { preferPassword = false; return dirty(); }
    +        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
    +        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
    +        
    +        /** if false, do not mind if there is no public key corresponding to any private key;
    +         * defaults to true; only applies if a private key is set */
    +        public OsCredential requirePublicKey(boolean requirePublicKey) {
    +            this.requirePublicKey = requirePublicKey;
    +            return dirty(); 
    +        }
    +        /** whether to check the private/public keys and passphrase are coherent; default true */
    +        public OsCredential doKeyValidation(boolean doKeyValidation) {
    +            this.doKeyValidation = doKeyValidation;
    +            return dirty();
    +        }
    +        /** if true (the default) this will look at default locations set on keys */
    +        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
    +            this.tryDefaultKeys = tryDefaultKeys;
    +            return dirty(); 
    +        }
    +        /** whether to log warnings on problems */
    +        public OsCredential warnOnErrors(boolean warnOnErrors) {
    +            this.warnOnErrors = warnOnErrors;
    +            return dirty(); 
    +        }
    +        /** whether to throw on problems */
    +        public OsCredential throwOnErrors(boolean throwOnErrors) {
    +            this.throwOnErrors = throwOnErrors;
    +            return dirty(); 
    +        }
    +        
    +        private OsCredential dirty() { dirty = true; return this; }
    +            
    +        public static OsCredential newInstance(ConfigBag config) {
    +            return new OsCredential(config);
    +        }
    +        
    +        private synchronized void infer() {
    +            if (!dirty) return;
    +            warningMessages.clear(); 
    +            
    +            log.debug("Inferring OS credentials");
    +            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
    +            password = config.get(LocationConfigKeys.PASSWORD);
    +            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
    +
    +            KeyPair privateKey = null;
    +            
    +            if (Strings.isBlank(privateKeyData)) {
    +                // look up private key files
    +                String privateKeyFiles = null;
    +                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
    +                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (Strings.isNonBlank(privateKeyFiles)) {
    +                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
    --- End diff --
    
    Maybe agree, but am hesitant for us to have different formats for the contents of brooklyn.properties on Windows and Unix.
    
    But the value of this field will look very different on linux and windows, given that it normally contains file paths.
    
    I see we use `getResourceAsString(file)` which means it would actually work with a URL (except for `:` having been used as a separator). I don't think we need to support URLs; the config key's description is clear that they are files.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23523396
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
    --- End diff --
    
    sub-classing should be an "is-a" relationship. If not that, then other mechanisms of code-reuse are perhaps more appropriate. This at least deserves a comment in the javadoc of the class.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520116
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java ---
    @@ -42,7 +44,9 @@
      * X509v3CertificateBuilder drags in an add'l dependency (bcmail) and is harder to use. */
     @SuppressWarnings("deprecation")
     public class FluentKeySigner {
    -    
    +
    +    static { Security.addProvider(new BouncyCastleProvider()); }
    --- End diff --
    
    I'm uncomfortable with doing this here. Feels like we should set up these JVM-wide provides at the start, as part of setup. My main concern with doing it here is that it could impact other stuff running in the JVM a while after Brooklyn has started, causing weird behaviour.
    
    It feels like the same argument for why it's a bad idea to call `System.setProperty("security....")` in the middle of some class - thus impacting what other seemingly unrelated code in the JVM will subsequently do.
    
    My other concern is that it doesn't give a way to see easily see all the dependencies we're using (i.e. what we're injecting into the JVM).


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23467032
  
    --- Diff: core/src/main/java/brooklyn/location/basic/LocationConfigUtils.java ---
    @@ -20,39 +20,355 @@
     
     import static brooklyn.util.JavaGroovyEquivalents.groovyTruth;
     
    +import java.io.ByteArrayInputStream;
     import java.io.File;
    -import java.io.IOException;
    +import java.security.KeyPair;
    +import java.security.PublicKey;
     import java.util.Arrays;
    +import java.util.Iterator;
     import java.util.List;
     import java.util.Map;
    +import java.util.Set;
     
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
     
     import brooklyn.config.ConfigKey;
     import brooklyn.entity.basic.ConfigKeys;
    +import brooklyn.internal.BrooklynFeatureEnablement;
    +import brooklyn.location.cloud.CloudLocationConfig;
     import brooklyn.management.ManagementContext;
    +import brooklyn.util.ResourceUtils;
     import brooklyn.util.collections.MutableMap;
    +import brooklyn.util.collections.MutableSet;
     import brooklyn.util.config.ConfigBag;
    +import brooklyn.util.crypto.AuthorizedKeysParser;
    +import brooklyn.util.crypto.SecureKeys;
    +import brooklyn.util.crypto.SecureKeys.PassphraseProblem;
    +import brooklyn.util.exceptions.Exceptions;
     import brooklyn.util.os.Os;
     import brooklyn.util.text.StringFunctions;
     import brooklyn.util.text.Strings;
     
    -import com.google.common.base.Charsets;
     import com.google.common.base.Objects;
     import com.google.common.collect.ImmutableList;
     import com.google.common.collect.Iterables;
     import com.google.common.collect.Lists;
    -import com.google.common.io.Files;
     
     public class LocationConfigUtils {
     
         private static final Logger log = LoggerFactory.getLogger(LocationConfigUtils.class);
    +
    +    /** Creates an instance of {@link OsCredential} by inspecting {@link LocationConfigKeys#PASSWORD}; 
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE};
    +     * {@link LocationConfigKeys#PRIVATE_KEY_PASSPHRASE} if needed, and
    +     * {@link LocationConfigKeys#PRIVATE_KEY_DATA} and {@link LocationConfigKeys#PRIVATE_KEY_FILE}
    +     * (defaulting to the private key file + ".pub"). 
    +     **/
    +    public static OsCredential getOsCredential(ConfigBag config) {
    +        return OsCredential.newInstance(config);
    +    }
         
    +    /** Convenience class for holding private/public keys and passwords, inferring from config keys.
    +     * See {@link LocationConfigUtils#getOsCredential(ConfigBag)}. */
    +    public static class OsCredential {
    +        private final ConfigBag config;
    +        private boolean preferPassword = false;
    +        private boolean tryDefaultKeys = true;
    +        private boolean requirePublicKey = true;
    +        private boolean doKeyValidation = BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_VALIDATE_LOCATION_SSH_KEYS);
    +        private boolean warnOnErrors = true;
    +        private boolean throwOnErrors = false;
    +        
    +        private boolean dirty = true;;
    +        
    +        private String privateKeyData;
    +        private String publicKeyData;
    +        private String password;
    +        
    +        private OsCredential(ConfigBag config) {
    +            this.config = config;
    +        }
    +
    +        /** throws if there are any problems */
    +        public OsCredential checkNotEmpty() {
    +            checkNoErrors();
    +            
    +            if (!hasKey() && !hasPassword()) {
    +                if (warningMessages.size()>0)
    +                    throw new IllegalStateException("Could not find credentials: "+warningMessages);
    +                else 
    +                    throw new IllegalStateException("Could not find credentials");
    +            }
    +            return this;
    +        }
    +
    +        /** throws if there were errors resolving (e.g. explicit keys, none of which were found/valid, or public key required and not found) 
    +         * @return */
    +        public OsCredential checkNoErrors() {
    +            throwOnErrors(true);
    +            dirty();
    +            infer();
    +            return this;
    +        }
    +        
    +        public OsCredential logAnyWarnings() {
    +            if (!warningMessages.isEmpty())
    +                log.warn("When reading credentials: "+warningMessages);
    +            return this;
    +        }
    +
    +        public Set<String> getWarningMessages() {
    +            return warningMessages;
    +        }
    +        
    +        /** returns either the key or password or null; if both a key and a password this prefers the key unless otherwise set
    +         * via {@link #preferPassword()} */
    +        public synchronized String get() {
    +            infer();
    +            
    +            if (isUsingPassword()) return password;
    +            if (hasKey()) return privateKeyData;
    +            return null;
    +        }
    +
    +        /** if there is no credential (ignores public key) */
    +        public boolean isEmpty() {
    +            return !hasKey() && !hasPassword();
    +        }
    +        public boolean hasKey() {
    +            infer();
    +            // key has stricter non-blank check than password
    +            return Strings.isNonBlank(privateKeyData);
    +        }
    +        public boolean hasPassword() {
    +            infer();
    +            // blank, even empty passwords are allowed
    +            return password!=null;
    +        }
    +        /** if a password is available, and either this is preferred over a key or there is no key */
    +        public boolean isUsingPassword() {
    +            return hasPassword() && (!hasKey() || preferPassword);
    +        }
    +        
    +        public String getPrivateKeyData() {
    +            infer();
    +            return privateKeyData;
    +        }
    +        public String getPublicKeyData() {
    +            infer();
    +            return publicKeyData;
    +        }
    +        public String getPassword() {
    +            infer();
    +            return password;
    +        }
    +        
    +        /** if both key and password supplied, prefer the key; the default */
    +        public OsCredential preferKey() { preferPassword = false; return dirty(); }
    +        /** if both key and password supplied, prefer the password; see {@link #preferKey()} */
    +        public OsCredential preferPassword() { preferPassword = true; return dirty(); }
    +        
    +        /** if false, do not mind if there is no public key corresponding to any private key;
    +         * defaults to true; only applies if a private key is set */
    +        public OsCredential requirePublicKey(boolean requirePublicKey) {
    +            this.requirePublicKey = requirePublicKey;
    +            return dirty(); 
    +        }
    +        /** whether to check the private/public keys and passphrase are coherent; default true */
    +        public OsCredential doKeyValidation(boolean doKeyValidation) {
    +            this.doKeyValidation = doKeyValidation;
    +            return dirty();
    +        }
    +        /** if true (the default) this will look at default locations set on keys */
    +        public OsCredential useDefaultKeys(boolean tryDefaultKeys) {
    +            this.tryDefaultKeys = tryDefaultKeys;
    +            return dirty(); 
    +        }
    +        /** whether to log warnings on problems */
    +        public OsCredential warnOnErrors(boolean warnOnErrors) {
    +            this.warnOnErrors = warnOnErrors;
    +            return dirty(); 
    +        }
    +        /** whether to throw on problems */
    +        public OsCredential throwOnErrors(boolean throwOnErrors) {
    +            this.throwOnErrors = throwOnErrors;
    +            return dirty(); 
    +        }
    +        
    +        private OsCredential dirty() { dirty = true; return this; }
    +            
    +        public static OsCredential newInstance(ConfigBag config) {
    +            return new OsCredential(config);
    +        }
    +        
    +        private synchronized void infer() {
    +            if (!dirty) return;
    +            warningMessages.clear(); 
    +            
    +            log.debug("Inferring OS credentials");
    +            privateKeyData = config.get(LocationConfigKeys.PRIVATE_KEY_DATA);
    +            password = config.get(LocationConfigKeys.PASSWORD);
    +            publicKeyData = getKeyDataFromDataKeyOrFileKey(config, LocationConfigKeys.PUBLIC_KEY_DATA, LocationConfigKeys.PUBLIC_KEY_FILE);
    +
    +            KeyPair privateKey = null;
    +            
    +            if (Strings.isBlank(privateKeyData)) {
    +                // look up private key files
    +                String privateKeyFiles = null;
    +                boolean privateKeyFilesExplicitlySet = config.containsKey(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (privateKeyFilesExplicitlySet || (tryDefaultKeys && password==null)) 
    +                    privateKeyFiles = config.get(LocationConfigKeys.PRIVATE_KEY_FILE);
    +                if (Strings.isNonBlank(privateKeyFiles)) {
    +                    Iterator<String> fi = Arrays.asList(privateKeyFiles.split(File.pathSeparator)).iterator();
    +                    while (fi.hasNext()) {
    +                        String file = fi.next();
    +                        if (Strings.isNonBlank(file)) {
    +                            try {
    +                                // real URL's won't actual work, due to use of path separator above 
    +                                // not real important, but we get it for free if "files" is a list instead.
    +                                // using ResourceUtils is useful for classpath resources
    +                                if (file!=null)
    +                                    privateKeyData = ResourceUtils.create().getResourceAsString(file);
    +                                // else use data already set
    +                                
    +                                privateKey = getValidatedPrivateKey(file);
    +                                
    +                                if (privateKeyData==null) {
    +                                    // was cleared due to validation error
    +                                } else if (Strings.isNonBlank(publicKeyData)) {
    +                                    log.debug("Loaded private key data from "+file+" (public key data explicitly set)");
    +                                    break;
    +                                } else {
    +                                    String publicKeyFile = (file!=null ? file+".pub" : "(data)");
    +                                    try {
    +                                        publicKeyData = ResourceUtils.create().getResourceAsString(publicKeyFile);
    +                                        
    +                                        log.debug("Loaded private key data from "+file+
    +                                            " and public key data from "+publicKeyFile);
    +                                        break;
    +                                    } catch (Exception e) {
    +                                        Exceptions.propagateIfFatal(e);
    +                                        log.debug("No public key file "+publicKeyFile+"; will try extracting from private key");
    +                                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
    +                                        
    +                                        if (publicKeyData==null) {
    +                                            if (requirePublicKey) {
    +                                                addWarning("Unable to find or extract public key for "+file, "skipping");
    +                                            } else {
    +                                                log.debug("Loaded private key data from "+file+" (public key data not found but not required)");
    +                                                break;
    +                                            }
    +                                        } else {
    +                                            log.debug("Loaded private key data from "+file+" (public key data extracted)");
    +                                            break;
    +                                        }
    +                                        privateKeyData = null;
    +                                    }
    +                                }
    +
    +                            } catch (Exception e) {
    +                                Exceptions.propagateIfFatal(e);
    +                                String message = "Missing/invalid private key file "+file;
    +                                if (privateKeyFilesExplicitlySet) addWarning(message, (!fi.hasNext() ? "no more files to try" : "trying next file")+": "+e);
    +                            }
    +                        }
    +                    }
    +                    if (privateKeyFilesExplicitlySet && Strings.isBlank(privateKeyData))
    +                        error("No valid private keys found", ""+warningMessages);
    +                }
    +            } else {
    +                privateKey = getValidatedPrivateKey("(data)");
    +            }
    +            
    +            if (privateKeyData!=null) {
    +                if (requirePublicKey && Strings.isBlank(publicKeyData)) {
    +                    if (privateKey!=null) {
    +                        publicKeyData = AuthorizedKeysParser.encodePublicKey(privateKey.getPublic());
    +                    }
    +                    if (Strings.isBlank(publicKeyData)) {
    +                        error("If explicit "+LocationConfigKeys.PRIVATE_KEY_DATA.getName()+" is supplied, then "
    +                            + "the corresponding "+LocationConfigKeys.PUBLIC_KEY_DATA.getName()+" must also be supplied.", null);
    +                    } else {
    +                        log.debug("Public key data extracted");
    +                    }
    +                }
    +                if (doKeyValidation && privateKey!=null && privateKey.getPublic()!=null && Strings.isNonBlank(publicKeyData)) {
    +                    PublicKey decoded = null;
    +                    try {
    +                        decoded = AuthorizedKeysParser.decodePublicKey(publicKeyData);
    +                    } catch (Exception e) {
    +                        Exceptions.propagateIfFatal(e);
    +                        addWarning("Invalid public key: "+decoded);
    +                    }
    +                    if (decoded!=null && !privateKey.getPublic().equals( decoded )) {
    +                        error("Public key inferred from does not match public key extracted from private key", null);
    +                    }
    +                }
    +            }
    +
    +            log.debug("OS credential inference: "+this);
    +            dirty = false;
    +        }
    +
    +        private KeyPair getValidatedPrivateKey(String label) {
    +            KeyPair privateKey = null;
    +            String passphrase = config.get(CloudLocationConfig.PRIVATE_KEY_PASSPHRASE);
    +            try {
    +                privateKey = SecureKeys.readPem(new ByteArrayInputStream(privateKeyData.getBytes()), passphrase);
    +                if (passphrase!=null) {
    +                    // get the unencrypted key data for our internal use (jclouds requires this)
    +                    privateKeyData = SecureKeys.toPem(privateKey);
    +                }
    +            } catch (PassphraseProblem e) {
    +                if (doKeyValidation) {
    +                    if (Strings.isBlank(passphrase))
    +                        addWarning("Passphrase required for key '"+label+"'");
    +                    else
    +                        addWarning("Invalid passphrase for key '"+label+"'");
    +                    privateKeyData = null;
    +                }
    +            } catch (Exception e) {
    +                Exceptions.propagateIfFatal(e);
    +                if (doKeyValidation) {
    +                    addWarning("Unable to parse private key from '"+label+"': unknown format");
    +                    privateKeyData = null;
    +                }
    +            }
    +            return privateKey;
    +        }
    +        
    +        Set<String> warningMessages = MutableSet.of();
    +        
    +        private void error(String msg, String logExtension) {
    +            addWarning(msg);
    +            if (warnOnErrors) log.warn(msg+(logExtension==null ? "" : ": "+logExtension));
    +            if (throwOnErrors) throw new IllegalStateException(msg+(logExtension==null ? "" : "; "+logExtension));
    +        }
    +
    +        private void addWarning(String msg) {
    +            addWarning(msg, null);
    +        }
    +        private void addWarning(String msg, String debugExtension) {
    +            log.debug(msg+(debugExtension==null ? "" : "; "+debugExtension));
    +            warningMessages.add(msg);
    +        }
    +
    +        @Override
    +        public String toString() {
    +            return getClass().getSimpleName()+"["+
    +                (Strings.isNonBlank(publicKeyData) ? publicKeyData : "public-key")+";"+
    +                (Strings.isNonBlank(privateKeyData) ? "private-key" : "private-key")+","+
    --- End diff --
    
    oops - yes


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522035
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    --- End diff --
    
    but agree it's no use here, so removing it


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23522104
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/SecureKeys.java ---
    @@ -19,182 +19,149 @@
     package brooklyn.util.crypto;
     
     import java.io.ByteArrayInputStream;
    -import java.io.ByteArrayOutputStream;
    -import java.io.FileWriter;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.StringWriter;
     import java.security.KeyPair;
    -import java.security.KeyPairGenerator;
    -import java.security.KeyStore;
    -import java.security.KeyStoreException;
    -import java.security.NoSuchAlgorithmException;
    +import java.security.PrivateKey;
    +import java.security.PublicKey;
     import java.security.Security;
    -import java.security.cert.CertificateException;
    -import java.security.cert.X509Certificate;
    -import java.util.NoSuchElementException;
    -
    -import javax.net.ssl.TrustManager;
    -import javax.net.ssl.TrustManagerFactory;
    -import javax.net.ssl.X509TrustManager;
    -import javax.security.auth.x500.X500Principal;
     
    +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
     import org.bouncycastle.jce.X509Principal;
     import org.bouncycastle.jce.provider.BouncyCastleProvider;
    +import org.bouncycastle.openssl.PEMDecryptorProvider;
    +import org.bouncycastle.openssl.PEMEncryptedKeyPair;
    +import org.bouncycastle.openssl.PEMKeyPair;
    +import org.bouncycastle.openssl.PEMParser;
     import org.bouncycastle.openssl.PEMReader;
     import org.bouncycastle.openssl.PEMWriter;
     import org.bouncycastle.openssl.PasswordFinder;
    +import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
    +import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
    +import org.slf4j.Logger;
    +import org.slf4j.LoggerFactory;
     
     import brooklyn.util.exceptions.Exceptions;
    +import brooklyn.util.stream.Streams;
     
    +import com.google.common.base.Objects;
     import com.google.common.base.Throwables;
     
     /**
      * Utility methods for generating and working with keys
      */
    -public class SecureKeys {
    +public class SecureKeys extends SecureKeysWithoutBouncyCastle {
     
    +    private static final Logger log = LoggerFactory.getLogger(SecureKeys.class);
    +    
         static { Security.addProvider(new BouncyCastleProvider()); }
         
    -    private static KeyPairGenerator defaultKeyPairGenerator = newKeyPairGenerator("RSA", 1024);  
    -
    -    private SecureKeys() {}
    -
    -    public static KeyPairGenerator newKeyPairGenerator(String algorithm, int bits) {
    -        KeyPairGenerator keyPairGenerator;
    -        try {
    -            keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    -        } catch (NoSuchAlgorithmException e) {
    -            throw Exceptions.propagate(e);
    -        }
    -        keyPairGenerator.initialize(bits);
    -        return keyPairGenerator;
    +    public static class PassphraseProblem extends IllegalStateException {
    +        private static final long serialVersionUID = -3382824813899223447L;
    +        public PassphraseProblem() { super("Passphrase problem with this key"); }
    +        public PassphraseProblem(String message) { super("Passphrase problem with this key: "+message); }
         }
         
    -    public static KeyPair newKeyPair() {
    -        return defaultKeyPairGenerator.generateKeyPair();
    +    private SecureKeys() {}
    +    
    +    /** RFC1773 order, with None for other values. Normally prefer X500Principal. */
    +    public static X509Principal getX509PrincipalWithCommonName(String commonName) {
    +        return new X509Principal("" + "C=None," + "L=None," + "O=None," + "OU=None," + "CN=" + commonName);
         }
     
    -    public static KeyPair newKeyPair(String algorithm, int bits) {
    -        return newKeyPairGenerator(algorithm, bits).generateKeyPair();
    -    }
    +    /** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
    +     * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
    +    public static KeyPair readPem(InputStream input, final String passphrase) {
    +        // TODO cache is only for fallback "reader" strategy 
    +        byte[] cache = Streams.readFully(input);
    +        input = new ByteArrayInputStream(cache);
     
    -    /** returns a new keystore, of the default type, and initialized to be empty.
    -     * (everyone always forgets to load(null,null).) */
    -    public static KeyStore newKeyStore() {
             try {
    -            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    -            store.load(null, null);
    -            return store;
    -        } catch (Exception e) {
    -            throw Exceptions.propagate(e);
    -        }
    -    }
    +            PEMParser pemParser = new PEMParser(new InputStreamReader(input));
    +
    +            Object object = pemParser.readObject();
    +            pemParser.close();
    +
    +            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    +            KeyPair kp = null;
    +            if (object==null) {
    +                throw new IllegalStateException("PEM parsing failed: missing or invalid data");
    +            } else if (object instanceof PEMEncryptedKeyPair) {
    +                if (passphrase==null) throw new PassphraseProblem("passphrase required");
    +                try {
    +                    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray());
    +                    kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    +                } catch (Exception e) {
    +                    Exceptions.propagateIfFatal(e);
    +                    throw new PassphraseProblem("wrong passphrase");
    +                }
    +            } else  if (object instanceof PEMKeyPair) {
    +                kp = converter.getKeyPair((PEMKeyPair) object);
    +            } else if (object instanceof PrivateKeyInfo) {
    +                PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
    +                kp = new KeyPair(null, privKey);
    +            } else {
    +                throw new IllegalStateException("PEM parser support missing for: "+object);
    +            }
    +
    +            return kp;
     
    -    /** returns keystore of default type read from given source */
    -    public static KeyStore newKeyStore(InputStream source, String passphrase) {
    --- End diff --
    
    they are in superclass


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23520391
  
    --- Diff: core/src/main/java/brooklyn/util/crypto/FluentKeySigner.java ---
    @@ -42,7 +44,9 @@
      * X509v3CertificateBuilder drags in an add'l dependency (bcmail) and is harder to use. */
     @SuppressWarnings("deprecation")
     public class FluentKeySigner {
    -    
    +
    +    static { Security.addProvider(new BouncyCastleProvider()); }
    --- End diff --
    
    I share the concern but I don't like the idea of mandating a specific entry point as it would mean we can't easily run test classes on their own.
    
    Maybe the thing to do is have a `BrooklynInitialization` class with statics `initBouncyCastle()` and `initAll()` which we can invoke as and where needed?  Start-sequence-wise it wouldn't be any difference but at least the startup logic would be in one place for reference.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by ahgittin <gi...@git.apache.org>.
Github user ahgittin commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23526283
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    --- End diff --
    
    `SecureKeysAndSignerTest` provides enough test coverage i think


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23521034
  
    --- Diff: core/src/test/java/brooklyn/util/crypto/SecureKeysAndSignerTest.java ---
    @@ -93,6 +95,40 @@ public void testReadRsaKey() throws Exception {
             checkNonTrivial(key);
         }
     
    +    @Test(expectedExceptions=IllegalStateException.class)
    +    public void testReadRsaPublicKeyAsPemFails() throws Exception {
    +        // should fail; see next test
    +        SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"), null);
    +    }
    +    
    +    @Test
    +    public void testReadRsaPublicKeyAsAuthKeysWorks() throws Exception {
    +        PublicKey key = AuthorizedKeysParser.decodePublicKey(
    +            ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/crypto/sample_rsa.pem.pub"));
    +        KeyPair fromPem = SecureKeys.readPem(ResourceUtils.create(this).getResourceFromUrl("classpath://brooklyn/util/crypto/sample_rsa.pem"), null);        
    --- End diff --
    
    Not particularly related to this PR, but on first impressions I'm confused why `brooklyn/util/crypto/sample_rsa.pem` is excluded from RAT check. In the root `pom.xml`, it has `<exclude>**/*.pem.pub</exclude>` but nothing for `*.pem`.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23524551
  
    --- Diff: core/src/test/java/brooklyn/location/basic/LocationConfigUtilsTest.java ---
    @@ -21,77 +21,134 @@
     import static org.testng.Assert.assertEquals;
     import static org.testng.Assert.assertTrue;
     
    +import org.testng.Assert;
     import org.testng.annotations.Test;
     
    +import brooklyn.location.basic.LocationConfigUtils.OsCredential;
     import brooklyn.util.config.ConfigBag;
     
    +@Test
     public class LocationConfigUtilsTest {
     
    -    public static final String SSH_PRIVATE_KEY_FILE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa");
    -    public static final String SSH_PUBLIC_KEY_FILE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa.pub");
    +    // set these system properties differently if needed to fix your tests
    +    public static final String SSH_PRIVATE_KEY_FILE_WITH_TILDE = System.getProperty("sshPrivateKey", "~/.ssh/id_rsa");
    +    public static final String SSH_PUBLIC_KEY_FILE_WITH_TILDE = System.getProperty("sshPublicKey", "~/.ssh/id_rsa.pub");
    +    // these should work as they are on classpath
    +    public static final String SSH_PRIVATE_KEY_FILE_WITH_PASSPHRASE = System.getProperty("sshPrivateKeyWithPassphrase", "/brooklyn/util/crypto/sample_rsa_passphrase.pem");
    +    public static final String SSH_PRIVATE_KEY_FILE = System.getProperty("sshPrivateKeySample", "/brooklyn/location/basic/sample_id_rsa");
    +    public static final String SSH_PUBLIC_KEY_FILE = System.getProperty("sshPublicKeySample", "/brooklyn/location/basic/sample_id_rsa.pub");
         
    -    @Test(groups="Integration")
         public void testPreferPrivateKeyDataOverFile() throws Exception {
             ConfigBag config = ConfigBag.newInstance();
             config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
             config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
             
    -        String data = LocationConfigUtils.getPrivateKeyData(config);
    +        OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
    +        Assert.assertTrue(creds.hasKey());
    +        // warnings, as it is malformed
    +        Assert.assertFalse(creds.getWarningMessages().isEmpty());
    +
    +        String data = creds.getPrivateKeyData();
             assertEquals(data, "mydata");
         }
    -    
    -    @Test(groups="Integration")
    -    public void testPreferPubilcKeyDataOverFile() throws Exception {
    +
    +    @Test(expectedExceptions=IllegalStateException.class)
    +    public void testInvalidKeyData() throws Exception {
    +        ConfigBag config = ConfigBag.newInstance();
    +        config.put(LocationConfigKeys.PRIVATE_KEY_DATA, "mydata");
    +        
    +        OsCredential creds = LocationConfigUtils.getOsCredential(config).doKeyValidation(false);
    +        Assert.assertTrue(creds.hasKey());
    +        Assert.assertFalse(creds.getWarningMessages().isEmpty());
    +        
    +        creds.checkNoErrors();
    +    }
    +
    +    public void testPreferPublicKeyDataOverFileAndNoPrivateKeyRequired() throws Exception {
             ConfigBag config = ConfigBag.newInstance();
             config.put(LocationConfigKeys.PUBLIC_KEY_DATA, "mydata");
             config.put(LocationConfigKeys.PUBLIC_KEY_FILE, SSH_PUBLIC_KEY_FILE);
    +        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, "");
             
    -        String data = LocationConfigUtils.getPublicKeyData(config);
    +        OsCredential creds = LocationConfigUtils.getOsCredential(config);
    +        String data = creds.getPublicKeyData();
             assertEquals(data, "mydata");
    +        Assert.assertNull(creds.get());
    +        Assert.assertFalse(creds.hasPassword());
    +        Assert.assertFalse(creds.hasKey());
    +        // and not even any warnings here
    +        Assert.assertTrue(creds.getWarningMessages().isEmpty());
         }
         
    -    @Test(groups="Integration")
    -    public void testReadsPrivateKeyFileWithTildaPath() throws Exception {
    +    @Test(groups="Integration")  // requires ~/.ssh/id_rsa
    +    public void testReadsPrivateKeyFileWithTildePath() throws Exception {
             ConfigBag config = ConfigBag.newInstance();
    -        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE);
    -        
    -        String data = LocationConfigUtils.getPrivateKeyData(config);
    +        config.put(LocationConfigKeys.PRIVATE_KEY_FILE, SSH_PRIVATE_KEY_FILE_WITH_TILDE);
    +
    +        // don't mind if it has a passphrase
    +        String data = LocationConfigUtils.getOsCredential(config).doKeyValidation(false).get();
             assertTrue(data != null && data.length() > 0);
         }
         
    -    @Test(groups="Integration")
    +    @Test(groups="Integration")  // requires ~/.ssh/passphrase-id_rsa
    --- End diff --
    
    Instead of adding another external file dependency, can use re-use the `SshToolAbstractIntegrationTest.SSH_KEY_WITH_PASSPHRASE` (i.e. use `~/.ssh/id_rsa_with_passphrase` as the default)?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

[GitHub] incubator-brooklyn pull request: Jclouds tidy

Posted by aledsage <gi...@git.apache.org>.
Github user aledsage commented on a diff in the pull request:

    https://github.com/apache/incubator-brooklyn/pull/465#discussion_r23525043
  
    --- Diff: utils/common/src/main/java/brooklyn/util/crypto/AuthorizedKeysParser.java ---
    @@ -0,0 +1,132 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package brooklyn.util.crypto;
    +
    +import java.io.ByteArrayInputStream;
    +import java.io.ByteArrayOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.OutputStream;
    +import java.math.BigInteger;
    +import java.security.KeyFactory;
    +import java.security.PublicKey;
    +import java.security.interfaces.DSAPublicKey;
    +import java.security.interfaces.RSAPublicKey;
    +import java.security.spec.DSAPublicKeySpec;
    +import java.security.spec.RSAPublicKeySpec;
    +
    +import brooklyn.util.exceptions.Exceptions;
    +
    +import com.google.common.io.BaseEncoding;
    +
    +public class AuthorizedKeysParser {
    +
    +    public static PublicKey decodePublicKey(String keyLine) {
    +        try {
    +            ByteArrayInputStream stream = null;
    +
    +            // look for the Base64 encoded part of the line to decode
    +            // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    +            for (String part : keyLine.split(" ")) {
    +                if (part.startsWith("AAAA")) {
    +                    stream = new ByteArrayInputStream(BaseEncoding.base64().decode(part));
    +                    break;
    +                }
    +            }
    +            if (stream == null)
    +                throw new IllegalArgumentException("Encoded public key should include phrase beginning AAAA.");
    +
    +            String type = readType(stream);
    +            if (type.equals("ssh-rsa")) {
    +                BigInteger e = readBigInt(stream);
    +                BigInteger m = readBigInt(stream);
    +                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
    +                return KeyFactory.getInstance("RSA").generatePublic(spec);
    +            } else if (type.equals("ssh-dss")) {
    +                BigInteger p = readBigInt(stream);
    +                BigInteger q = readBigInt(stream);
    +                BigInteger g = readBigInt(stream);
    +                BigInteger y = readBigInt(stream);
    +                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
    +                return KeyFactory.getInstance("DSA").generatePublic(spec);
    +            } else {
    +                throw new IllegalArgumentException("Unknown public key type " + type);
    +            }
    +            
    +        } catch (Exception e) {
    +            Exceptions.propagateIfFatal(e);
    +            throw new IllegalArgumentException("Error parsing authorized_keys/SSH2 format public key: "+e);
    +        }
    +    }
    +
    +    private static int readInt(InputStream stream) throws IOException {
    +        return ((stream.read() & 0xFF) << 24) | ((stream.read() & 0xFF) << 16)
    --- End diff --
    
    If we create a new `AuthorizedKeysParserTest.java`, then it should include a reference to `SecureKeysAndSignerTest` where there are tests that use this utility class.


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---