Permalink
Browse files

Add support for import of SSH key pairs.

Fixes EUCA-2243
  • Loading branch information...
sjones4 committed Jul 31, 2012
1 parent e08d243 commit 415c150fb7b766acd2a25c4da101f0b6c83c078e
@@ -65,25 +65,31 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.io.StringReader;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.util.List;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.NoSuchElementException;
import javax.persistence.PersistenceException;
import org.apache.log4j.Logger;
import org.bouncycastle.openssl.PEMWriter;
import com.eucalyptus.auth.AuthException;
import com.eucalyptus.auth.policy.PolicySpec;
import com.eucalyptus.context.Context;
import com.eucalyptus.context.Contexts;
import com.eucalyptus.context.IllegalContextAccessException;
import com.eucalyptus.crypto.Certs;
import com.eucalyptus.crypto.Digest;
import com.eucalyptus.crypto.util.B64;
import com.eucalyptus.entities.TransactionException;
import com.eucalyptus.entities.Transactions;
import com.eucalyptus.util.EucalyptusCloudException;
import com.eucalyptus.util.RestrictedTypes;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import edu.ucsb.eucalyptus.msgs.CreateKeyPairResponseType;
import edu.ucsb.eucalyptus.msgs.CreateKeyPairType;
import edu.ucsb.eucalyptus.msgs.DeleteKeyPairResponseType;
@@ -163,31 +169,114 @@ public ImportKeyPairResponseType importKeyPair( final ImportKeyPairType request
try {
KeyPairs.lookup( ctx.getUserFullName( ), request.getKeyName( ) );
} catch ( Exception e1 ) {
Supplier<SshKeyPair> allocator = new Supplier<SshKeyPair>() {
@Override
public SshKeyPair get( ) {
SshKeyPair newKey = new SshKeyPair( ctx.getUserFullName( ), request.getKeyName( ) );
newKey.setPublicKey( request.getPublicKeyMaterial( ) );
/**
* TODO:GRZE:OMGFIXME:RELEASE
* Supported formats:
* OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)
* Base64 encoded DER format
* SSH public key file format as specified in RFC4716
*
* DSA keys are not supported. Make sure your key generator is set up to create RSA keys.
* Supported lengths: 1024, 2048, and 4096.
*/
//TODO:GRZE:replace bogus initial impl.
byte[] digest = Digest.MD5.get( ).digest( request.getPublicKeyMaterial( ).getBytes( ) );
String fingerprint = String.format( "%032X", new BigInteger( digest ) );
newKey.setFingerPrint( fingerprint );
reply.setKeyName( request.getKeyName( ) );
return newKey;
}};
RestrictedTypes.allocateUnitlessResource( allocator );
try {
final RSAPublicKey key = decodeKeyMaterial( request.getPublicKeyMaterial( ) );
final String keyFingerprint = KeyPairs.getPublicKeyFingerprint( key );
if ( keyFingerprint == null ) {
throw new GeneralSecurityException( "Error generating fingerprint" );
}
final Supplier<SshKeyPair> allocator = new Supplier<SshKeyPair>() {
@Override
public SshKeyPair get( ) {
final SshKeyPair newKey = new SshKeyPair( ctx.getUserFullName( ), request.getKeyName( ) );
newKey.setFingerPrint( keyFingerprint );
newKey.setPublicKey( KeyPairs.rfc4253Format( ctx.getUserFullName( ), request.getKeyName( ), key ) );
try {
Transactions.save(newKey);
reply.setKeyName( newKey.getDisplayName() );
reply.setKeyFingerprint( newKey.getFingerPrint() );
} catch ( TransactionException e ) {
LOG.warn( "Error saving imported key", e );
}
return newKey;
}};
RestrictedTypes.allocateUnitlessResource( allocator );
} catch (GeneralSecurityException e) {
LOG.warn("Error importing SSH public key", e);
reply.set_return(false);
}
}
return reply;
}
/**
* Decode any supported key material.
*
* Supported formats:
* OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys) http://tools.ietf.org/html/rfc4253#section-6.6
* Base64 encoded DER format
* SSH public key file format as specified in RFC4716
*
* Supported lengths: 1024, 2048, and 4096.
*
* @return The RSA public key
*/
private static RSAPublicKey decodeKeyMaterial( final String b64EncodedKeyMaterial ) throws GeneralSecurityException {
final String decoded;
try {
decoded = B64.standard.decString(b64EncodedKeyMaterial);
} catch ( ArrayIndexOutOfBoundsException e ) {
throw new GeneralSecurityException( "Invalid key material (expected Base64)" );
} catch ( StringIndexOutOfBoundsException e ) {
throw new GeneralSecurityException( "Invalid key material (expected Base64)" );
}
final RSAPublicKey key;
if ( decoded.startsWith( "ssh-rsa " ) ) {
final String[] keyParts = decoded.split("\\s+");
if ( keyParts.length > 1 ) {
key = KeyPairs.decodeSshRsaPublicKey(keyParts[1]);
} else {
throw new GeneralSecurityException( "Invalid SSH key format" );
}
} else if ( decoded.startsWith("---- BEGIN SSH2 PUBLIC KEY ----") ) {
final String keyB64;
try {
keyB64 = Joiner.on("\n").join(Iterables.filter(CharStreams.readLines(new StringReader(decoded)), new Predicate<String>() {
boolean continueLine = false;
boolean sawEnd = false;
@Override
public boolean apply(final String line) {
// skip start / end lines
sawEnd = sawEnd || line.contains("---- END SSH2 PUBLIC KEY ----");
if (line.contains("---- BEGIN SSH2 PUBLIC KEY ----") || sawEnd) {
continueLine = false;
return false;
}
// skip headers and header continuations
if (continueLine || line.contains(":")) {
continueLine = line.endsWith("\\");
return false;
}
return true;
}
}) );
} catch (IOException e) {
throw new GeneralSecurityException( "Error reading key data" );
}
key = KeyPairs.decodeSshRsaPublicKey(keyB64);
} else {
try {
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final X509EncodedKeySpec encodedSpec = new X509EncodedKeySpec( B64.standard.dec( decoded ) );
key = (RSAPublicKey) keyFactory.generatePublic( encodedSpec );
} catch ( ArrayIndexOutOfBoundsException e ) {
throw new GeneralSecurityException( "Invalid key material" );
} catch ( StringIndexOutOfBoundsException e ) {
throw new GeneralSecurityException( "Invalid key material" );
}
}
// verify key properties
final int keySize = key.getModulus().bitLength();
if ( keySize != 1024 &&
keySize != 2048 &&
keySize != 4096 ) {
throw new GeneralSecurityException( "Invalid key size: " + keySize );
}
return key;
}
}
@@ -63,26 +63,33 @@
package com.eucalyptus.keys;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.List;
import javax.persistence.EntityTransaction;
import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;
import org.hibernate.exception.ConstraintViolationException;
import com.eucalyptus.auth.principal.AccountFullName;
import com.eucalyptus.auth.principal.UserFullName;
import com.eucalyptus.cloud.util.DuplicateMetadataException;
import com.eucalyptus.cloud.util.MetadataCreationException;
import com.eucalyptus.cloud.util.MetadataException;
import com.eucalyptus.cloud.util.NoSuchMetadataException;
import com.eucalyptus.crypto.Certs;
import com.eucalyptus.crypto.Digest;
import com.eucalyptus.crypto.util.B64;
import com.eucalyptus.entities.Entities;
import com.eucalyptus.entities.TransactionException;
import com.eucalyptus.entities.Transactions;
import com.eucalyptus.records.Logs;
import com.eucalyptus.util.OwnerFullName;
import com.google.common.primitives.Ints;
public class KeyPairs {
private static Logger LOG = Logger.getLogger( KeyPairs.class );
@@ -149,29 +156,123 @@ public static PrivateKey create( UserFullName userName, String keyName ) throws
}
return newKeys.getPrivate( );
}
/**
* Decode a SSH B64 format RSA public key.
*
* @param publicKeyB64 The base64 formatted key
* @return The RSA public key
* @throws java.security.GeneralSecurityException If an error occurs
*/
public static RSAPublicKey decodeSshRsaPublicKey(final String publicKeyB64) throws GeneralSecurityException {
final byte[] data;
try {
data = B64.standard.dec( publicKeyB64 );
} catch ( ArrayIndexOutOfBoundsException e ) {
throw new GeneralSecurityException( "Invalid key format (expected Base64)" );
} catch ( StringIndexOutOfBoundsException e ) {
throw new GeneralSecurityException( "Invalid key format (expected Base64)" );
}
if ( data.length < 64 ) {
throw new InvalidKeyException("Data too short");
}
int length = Ints.fromBytes(data[0], data[1], data[2], data[3]);
if ( length != 7 ||
data[ 4]!='s' ||
data[ 5]!='s' ||
data[ 6]!='h' ||
data[ 7]!='-' ||
data[ 8]!='r' ||
data[ 9]!='s' ||
data[10]!='a' ) {
throw new InvalidKeyException("Not an RSA key");
}
int exponentLength = Ints.fromBytes( data[11], data[12], data[13], data[14] );
if ( exponentLength <= 0 || exponentLength > 4 ) {
throw new InvalidKeyException("Invalid RSA exponent");
}
int modulusLength = Ints.fromBytes(
data[15+exponentLength],
data[16+exponentLength],
data[17+exponentLength],
data[18+exponentLength]);
if ( modulusLength <= 0 || modulusLength > 513 || data.length < 19+exponentLength+modulusLength ) {
throw new InvalidKeyException("Invalid RSA modulus");
}
final BigInteger modulus = intFromBytes( data, 19+exponentLength, modulusLength );
final BigInteger exponent = intFromBytes( data, 15, exponentLength );
final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
final RSAPublicKeySpec spec = new RSAPublicKeySpec( modulus, exponent );
final PublicKey key = keyFactory.generatePublic( spec );
return (RSAPublicKey) key;
}
public static String rfc4253Format( final UserFullName userName,
final String keyName,
final RSAPublicKey publicKey ) {
return getAuthKeyString( userName.getAccountNumber( ), keyName, publicKey );
}
/**
* An MD5 SSH RSA public key fingerprint as specified in section 4 of RFC 4716
*
* @param publicKey The RSA public key
* @return The fingerprint or null if an error occurred.
*/
public static String getPublicKeyFingerprint( final RSAPublicKey publicKey ) {
try {
final MessageDigest digest = Digest.MD5.get( );
final byte[] fingerprint = digest.digest( encodeSshRsaPublicKey(publicKey) );
final StringBuilder sb = new StringBuilder( );
for ( final byte b : fingerprint )
sb.append( String.format( "%02X:", b ) );
return sb.substring( 0, sb.length( ) - 1 ).toLowerCase( );
} catch ( Exception e ) {
LOG.error( "Error generating fingerprint: " + e.getMessage(), e );
return null;
}
}
private static String getAuthKeyString( UserFullName userName, String keyName, KeyPair newKeys ) {
RSAPublicKey publicKey = ( RSAPublicKey ) newKeys.getPublic( );
final RSAPublicKey publicKey = ( RSAPublicKey ) newKeys.getPublic( );
return getAuthKeyString( userName.getAccountNumber( ), keyName, publicKey );
}
private static byte[] encodeSshRsaPublicKey(final RSAPublicKey publicKey) {
byte[] keyType = "ssh-rsa".getBytes( );
byte[] expBlob = publicKey.getPublicExponent( ).toByteArray( );
byte[] modBlob = publicKey.getModulus( ).toByteArray( );
byte[] authKeyBlob = new byte[3 * 4 + keyType.length + expBlob.length + modBlob.length];
byte[] lenArray = null;
lenArray = BigInteger.valueOf( keyType.length ).toByteArray( );
System.arraycopy( lenArray, 0, authKeyBlob, 4 - lenArray.length, lenArray.length );
System.arraycopy( keyType, 0, authKeyBlob, 4, keyType.length );
lenArray = BigInteger.valueOf( expBlob.length ).toByteArray( );
System.arraycopy( lenArray, 0, authKeyBlob, 4 + keyType.length + 4 - lenArray.length, lenArray.length );
System.arraycopy( expBlob, 0, authKeyBlob, 4 + ( 4 + keyType.length ), expBlob.length );
lenArray = BigInteger.valueOf( modBlob.length ).toByteArray( );
System.arraycopy( lenArray, 0, authKeyBlob, 4 + expBlob.length + 4 + keyType.length + 4 - lenArray.length, lenArray.length );
System.arraycopy( modBlob, 0, authKeyBlob, 4 + ( 4 + expBlob.length + ( 4 + keyType.length ) ), modBlob.length );
String authKeyString = String.format( "%s %s %s@eucalyptus.%s", new String( keyType ), new String( Base64.encode( authKeyBlob ) ), userName.getAccountNumber( ), keyName );
return authKeyString;
return authKeyBlob;
}
private static String getAuthKeyString( String userDesc, String keyName, RSAPublicKey publicKey ) {
final byte[] authKeyBlob = encodeSshRsaPublicKey(publicKey);
return String.format("ssh-rsa %s %s@eucalyptus.%s", B64.standard.encString(authKeyBlob), userDesc, keyName);
}
private static BigInteger intFromBytes( byte[] data, int index, int length ) {
final byte[] intBytes = new byte[length];
System.arraycopy( data, index, intBytes, 0, length );
return new BigInteger( intBytes );
}
}
Oops, something went wrong.

0 comments on commit 415c150

Please sign in to comment.