You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2015/06/15 11:44:07 UTC

mina-sshd git commit: [SSHD-491] SSHD fails to correctly verify ECDSA P-521 public keys

Repository: mina-sshd
Updated Branches:
  refs/heads/master f71181ea6 -> 168c5054b


[SSHD-491] SSHD fails to correctly verify ECDSA P-521 public keys


Project: http://git-wip-us.apache.org/repos/asf/mina-sshd/repo
Commit: http://git-wip-us.apache.org/repos/asf/mina-sshd/commit/168c5054
Tree: http://git-wip-us.apache.org/repos/asf/mina-sshd/tree/168c5054
Diff: http://git-wip-us.apache.org/repos/asf/mina-sshd/diff/168c5054

Branch: refs/heads/master
Commit: 168c5054b4469f2518e0f99c99abeda2cf235ac9
Parents: f71181e
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Mon Jun 15 12:43:55 2015 +0300
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Mon Jun 15 12:43:55 2015 +0300

----------------------------------------------------------------------
 .../common/signature/AbstractSignature.java     |  15 ++-
 .../apache/sshd/common/signature/Signature.java |  39 +++---
 .../sshd/common/signature/SignatureECDSA.java   | 119 ++++++++--------
 .../apache/sshd/common/util/ValidateUtils.java  |   6 +
 .../apache/sshd/common/util/buffer/Buffer.java  |  13 +-
 .../sshd/common/util/buffer/BufferUtils.java    |  56 ++++++++
 .../apache/sshd/common/util/io/DERParser.java   | 134 +++++++++++++++++++
 .../apache/sshd/common/util/io/DERWriter.java   | 113 ++++++++++++++++
 .../test/java/org/apache/sshd/EcdsaTest.java    |  63 ++++++---
 9 files changed, 450 insertions(+), 108 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/signature/AbstractSignature.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/signature/AbstractSignature.java b/sshd-core/src/main/java/org/apache/sshd/common/signature/AbstractSignature.java
index 66e93e4..65f434c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/signature/AbstractSignature.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/signature/AbstractSignature.java
@@ -56,14 +56,18 @@ public abstract class AbstractSignature implements Signature {
     }
 
     @Override
-    public void update(byte[] foo, int off, int len) throws Exception {
-        signature.update(foo, off, len);
+    public void update(byte[] hash) throws Exception {
+        update(hash, 0, GenericUtils.length(hash));
+    }
+
+    @Override
+    public void update(byte[] hash, int off, int len) throws Exception {
+        signature.update(hash, off, len);
     }
 
     protected byte[] extractSig(byte[] sig) {
-        if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0) {
-            int i = 0;
-            int j;
+        if ((sig[0] == 0) && (sig[1] == 0) && (sig[2] == 0)) {
+            int i = 0, j;
             j = ((sig[i++] << 24) & 0xff000000) |
                 ((sig[i++] << 16) & 0x00ff0000) |
                 ((sig[i++] <<  8) & 0x0000ff00) |
@@ -77,6 +81,7 @@ public abstract class AbstractSignature implements Signature {
             System.arraycopy(sig, i, tmp, 0, j);
             sig = tmp;
         }
+
         return sig;
     }
 

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/signature/Signature.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/signature/Signature.java b/sshd-core/src/main/java/org/apache/sshd/common/signature/Signature.java
index 3a37a5a..dad946c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/signature/Signature.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/signature/Signature.java
@@ -34,39 +34,42 @@ public interface Signature {
     String getAlgorithm();
 
     /**
-     * Initialize this signature with the given public key and private key.
-     * If the private key is null, only signature verification can be performed.
-     *
-     * @param pubkey
-     * @param prvkey
-     * @throws Exception
+     * @param pubkey The {@link PublicKey} to be used for verifying signatures
+     * @param prvkey The {@link PrivateKey} to be used for signing - if {@code null}
+     * then only verification can be performed
+     * @throws Exception If failed to initialize
      */
     void init(PublicKey pubkey, PrivateKey prvkey) throws Exception;
 
     /**
      * Update the computed signature with the given data
-     *
-     * @param H
-     * @param off
-     * @param len
-     * @throws Exception
+     * @param hash The hash data buffer
+     * @throws Exception If failed to update
      */
-    void update(byte[] H, int off, int len) throws Exception;
+    void update(byte[] hash) throws Exception;
+
+    /**
+     * Update the computed signature with the given data
+     * @param hash The hash data buffer
+     * @param off Offset of hash data in buffer
+     * @param len Length of hash data
+     * @throws Exception If failed to update
+     */
+    void update(byte[] hash, int off, int len) throws Exception;
 
     /**
      * Verify against the given signature
      *
-     * @param sig
-     * @return
-     * @throws Exception
+     * @param sig The signed data
+     * @return {@code true} if signature is valid
+     * @throws Exception If failed to extract signed data for validation
      */
     boolean verify(byte[] sig) throws Exception;
 
     /**
      * Compute the signature
-     *
-     * @return
-     * @throws Exception
+     * @return The signature value
+     * @throws Exception If failed to calculate the signature
      */
     byte[] sign() throws Exception;
 

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureECDSA.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureECDSA.java b/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureECDSA.java
index 2fdef4e..4aa3ec9 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureECDSA.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/signature/SignatureECDSA.java
@@ -23,10 +23,11 @@ import java.math.BigInteger;
 
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+import org.apache.sshd.common.util.io.DERParser;
+import org.apache.sshd.common.util.io.DERWriter;
 
 /**
- * Signature algorithm for EC keys using ECDSA. There 
- *
+ * Signature algorithm for EC keys using ECDSA. 
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public class SignatureECDSA extends AbstractSignature {
@@ -38,71 +39,71 @@ public class SignatureECDSA extends AbstractSignature {
     @Override
     public byte[] sign() throws Exception {
         byte[] sig = signature.sign();
-
-        if ((sig[0] != 0x30) || (sig[1] != sig.length - 2) || (sig[2] != 0x02)) {
-            throw new IOException("Invalid signature format");
+        
+        // see http://tools.ietf.org/html/rfc3278#section-8.2
+        try(DERParser parser = new DERParser(sig)) {
+            int type = parser.read();
+            if (type != 0x30) {
+                throw new IOException("Invalid signature format - not a DER SEQUENCE: 0x" + Integer.toHexString(type));
+            }
+    
+            // length of remaining encoding of the 2 integers
+            int remainLen = parser.readLength();
+            /*
+             * There are supposed to be 2 INTEGERs, each encoded with:
+             * 
+             *  - one byte representing the fact that it is an INTEGER
+             *  - one byte of the integer encoding length
+             *  - at least one byte of integer data (zero length is not an option)
+             */
+            if (remainLen < (2 * 3)) {
+                throw new IOException("Invalid signature format - not enough encoded data length: " + remainLen);
+            }
+
+            BigInteger r = parser.readBigInteger();
+            BigInteger s = parser.readBigInteger();
+
+            // see https://tools.ietf.org/html/rfc5656#page-5
+            Buffer rsBuf = new ByteArrayBuffer();
+            rsBuf.putMPInt(r);
+            rsBuf.putMPInt(s);
+    
+            return rsBuf.getCompactData();
         }
-
-        int rLength = sig[3];
-        if ((rLength + 6 > sig.length) || (sig[4 + rLength] != 0x02)) {
-            throw new IOException("Invalid signature format");
-        }
-
-        int sLength = sig[5 + rLength];
-        if (6 + rLength + sLength > sig.length) {
-            throw new IOException("Invalid signature format");
-        }
-
-        byte[] rArray = new byte[rLength];
-        byte[] sArray = new byte[sLength];
-
-        System.arraycopy(sig, 4, rArray, 0, rLength);
-        System.arraycopy(sig, 6 + rLength, sArray, 0, sLength);
-
-        BigInteger r = new BigInteger(rArray);
-        BigInteger s = new BigInteger(sArray);
-
-        // Write the <r,s> to its own types writer.
-        Buffer rsBuf = new ByteArrayBuffer();
-        rsBuf.putMPInt(r);
-        rsBuf.putMPInt(s);
-
-        return rsBuf.getCompactData();
     }
 
     @Override
     public boolean verify(byte[] sig) throws Exception {
-        sig = extractSig(sig);
+        byte[] data = extractSig(sig);
+        Buffer rsBuf = new ByteArrayBuffer(data);
 
-        Buffer rsBuf = new ByteArrayBuffer(sig);
-        byte[] rArray = rsBuf.getMPIntAsBytes();
-        byte[] sArray = rsBuf.getMPIntAsBytes();
-
-        if (rsBuf.available() != 0) {
-            throw new IOException("Signature had padding");
+        byte[] rArray = rsBuf.getMPIntAsBytes(), rEncoding;
+        try(DERWriter w = new DERWriter(rArray.length + 4)) {     // in case length > 0x7F
+            w.writeBigInteger(rArray);
+            rEncoding = w.toByteArray();
+        }
+        
+        byte[] sArray = rsBuf.getMPIntAsBytes(), sEncoding;
+        try(DERWriter w = new DERWriter(sArray.length + 4)) {     // in case length > 0x7F
+            w.writeBigInteger(sArray);
+            sEncoding = w.toByteArray();
+        }
+        
+        int remaining = rsBuf.available();
+        if (remaining != 0) {
+            throw new IOException("Signature had padding - remaining=" + remaining);
         }
 
-        // ASN.1
-        int frst = ((rArray[0] & 0x80) != 0 ? 1 : 0);
-        int scnd = ((sArray[0] & 0x80) != 0 ? 1 : 0);
-
-        int length = rArray.length + sArray.length + 6 + frst + scnd;
-        byte[] tmp = new byte[length];
-        tmp[0] = (byte) 0x30;
-        tmp[1] = (byte) (rArray.length + sArray.length + 4);
-        tmp[1] += frst;
-        tmp[1] += scnd;
-        tmp[2] = (byte) 0x02;
-        tmp[3] = (byte) rArray.length;
-        tmp[3] += frst;
-        System.arraycopy(rArray, 0, tmp, 4 + frst, rArray.length);
-        tmp[4 + tmp[3]] = (byte) 0x02;
-        tmp[5 + tmp[3]] = (byte) sArray.length;
-        tmp[5 + tmp[3]] += scnd;
-        System.arraycopy(sArray, 0, tmp, 6 + tmp[3] + scnd, sArray.length);
-        sig = tmp;
+        int length = rEncoding.length + sEncoding.length;
+        byte[] encoded;
+        try(DERWriter w = new DERWriter(1 + length + 4)) {  // in case length > 0x7F
+            w.write(0x30); // SEQUENCE
+            w.writeLength(length);
+            w.write(rEncoding);
+            w.write(sEncoding);
+            encoded = w.toByteArray();
+        }
 
-        return signature.verify(sig);
+        return signature.verify(encoded);
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java
index 64c3c7e..1051a69 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/ValidateUtils.java
@@ -67,6 +67,12 @@ public final class ValidateUtils {
         return t;
     }
 
+    public static final void checkTrue(boolean flag, String message, long arg) {
+        if (!flag) {
+            throwIllegalArgumentException(message, Long.valueOf(arg));
+        }
+    }
+
     public static final void checkTrue(boolean flag, String message, Object arg) {
         if (!flag) {
             throwIllegalArgumentException(message, arg);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java b/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java
index 784daa7..233766a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/Buffer.java
@@ -116,11 +116,7 @@ public abstract class Buffer implements Readable {
         // TODO use Integer.BYTES for JDK-8
         ensureAvailable(Integer.SIZE / Byte.SIZE);
         getRawBytes(workBuf, 0, Integer.SIZE / Byte.SIZE);
-        long l = ((workBuf[0] << 24) & 0xff000000L)|
-                 ((workBuf[1] << 16) & 0x00ff0000L)|
-                 ((workBuf[2] <<  8) & 0x0000ff00L)|
-                 ((workBuf[3]      ) & 0x000000ffL);
-        return l;        
+        return BufferUtils.getUInt(workBuf, 0, Integer.SIZE / Byte.SIZE);
     }
 
     public long getLong() {
@@ -330,15 +326,12 @@ public abstract class Buffer implements Readable {
 
     /**
      * Writes 32 bits
-     * @param i
+     * @param i The 32-bit value
      */
     public void putInt(long i) {
         // TODO use Integer.BYTES for JDK-8
         ensureCapacity(Integer.SIZE / Byte.SIZE);
-        workBuf[0] = (byte) (i >> 24);
-        workBuf[1] = (byte) (i >> 16);
-        workBuf[2] = (byte) (i >>  8);
-        workBuf[3] = (byte) (i      );
+        BufferUtils.putUInt(i, workBuf, 0, Integer.SIZE / Byte.SIZE);
         putRawBytes(workBuf, 0, Integer.SIZE / Byte.SIZE);
     }
 

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/BufferUtils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/BufferUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/BufferUtils.java
index 07b8617..775f24e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/BufferUtils.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/buffer/BufferUtils.java
@@ -59,6 +59,62 @@ public class BufferUtils {
         return sb.toString();
     }
 
+    /**
+     * @param buf A buffer holding a 32-bit unsigned integer in <B>big endian</B>
+     * format. <B>Note:</B> if more than 4 bytes are available, then only the
+     * <U>first</U> 4 bytes in the buffer will be used
+     * @return The result as a {@code long} whose 32 high-order bits are zero
+     * @see #getUInt(byte[], int, int)
+     */
+    public static long getUInt(byte ... buf) {
+        return getUInt(buf, 0, GenericUtils.length(buf));
+    }
+    
+    /**
+     * @param buf A buffer holding a 32-bit unsigned integer in <B>big endian</B>
+     * format.
+     * @param off The offset of the data in the buffer
+     * @param len The available data length. <B>Note:</B> if more than 4 bytes
+     * are available, then only the <U>first</U> 4 bytes in the buffer will be
+     * used (starting at the specified <tt>offset</tt>)
+     * @return The result as a {@code long} whose 32 high-order bits are zero
+     */
+    public static long getUInt(byte[] buf, int off, int len) {
+        // TODO use Integer.BYTES for JDK-8
+        if (len < (Integer.SIZE / Byte.SIZE)) {
+            throw new IllegalArgumentException("Not enough data for a UINT: required=" + (Integer.SIZE / Byte.SIZE) + ", available=" + len);
+        }
+
+        return ((buf[off] << 24) & 0xff000000L)
+             | ((buf[off + 1] << 16) & 0x00ff0000L)
+             | ((buf[off + 2] <<  8) & 0x0000ff00L)
+             | ((buf[off + 3]      ) & 0x000000ffL)
+             ;
+    }
+
+    /**
+     * @param value The 32-bit value 
+     * @param buf
+     * @return
+     */
+    public static int putUInt(long value, byte[] buf) {
+        return putUInt(value, buf, 0, GenericUtils.length(buf));
+    }
+
+    public static int putUInt(long value, byte[] buf, int off, int len) {
+        // TODO use Integer.BYTES for JDK-8
+        if (len < (Integer.SIZE / Byte.SIZE)) {
+            throw new IllegalArgumentException("Not enough data for a UINT: required=" + (Integer.SIZE / Byte.SIZE) + ", available=" + len);
+        }
+
+        buf[off]     = (byte) (value >> 24);
+        buf[off + 1] = (byte) (value >> 16);
+        buf[off + 2] = (byte) (value >>  8);
+        buf[off + 3] = (byte) (value & 0xFF);
+
+        return (Integer.SIZE / Byte.SIZE);
+    }
+
     public static boolean equals(byte[] a1, byte[] a2) {
         int len1 = GenericUtils.length(a1);
         int len2 = GenericUtils.length(a2);

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERParser.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERParser.java b/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERParser.java
new file mode 100644
index 0000000..1177133
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERParser.java
@@ -0,0 +1,134 @@
+/*
+ * 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 org.apache.sshd.common.util.io;
+
+import java.io.ByteArrayInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StreamCorruptedException;
+import java.math.BigInteger;
+import java.util.Arrays;
+
+import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.buffer.BufferUtils;
+
+/**
+ * A bare minimum DER parser - just enough to be able to decode
+ * signatures and private keys
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class DERParser extends FilterInputStream {
+    // TODO in JDK-8 use Integer.BYTES
+    private final byte[] lenBytes = new byte[Integer.SIZE / Byte.SIZE];
+
+    public DERParser(byte ... bytes) {
+        this(bytes, 0, GenericUtils.length(bytes));
+    }
+
+    public DERParser(byte[] bytes, int offset, int len) {
+        this(new ByteArrayInputStream(bytes, offset, len));
+    }
+
+    public DERParser(InputStream s) {
+        super(s);
+    }
+
+    /**
+     * Maximum size of data allowed by {@link #readLength()} - it is a bit
+     * arbitrary since one can encode 32-bit length data, but it is good
+     * enough for the keys
+     */
+    public static final int MAX_DER_VALUE_LENGTH=2 * Short.MAX_VALUE;
+
+    /**
+     * Decode the length of the field. Can only support length
+     * encoding up to 4 octets. In BER/DER encoding, length can
+     * be encoded in 2 forms:
+     * <ul>
+     *      <li>
+     *      Short form - One octet. Bit 8 has value "0" and bits 7-1
+     *      give the length.
+     *      </li>
+     *
+     *      <li>
+     *      Long form - Two to 127 octets (only 4 is supported here).
+     *      Bit 8 of first octet has value "1" and bits 7-1 give the
+     *      number of additional length octets. Second and following
+     *      octets give the length, base 256, most significant digit
+     *      first.
+     *      </li>
+     * </ul>
+     * @return The length as integer
+     * @throws IOException
+     */
+    public int readLength() throws IOException {
+        int i = read();
+        if (i == -1) {
+            throw new StreamCorruptedException("Invalid DER: length missing");
+        }
+
+        // A single byte short length
+        if ((i & ~0x7F) == 0) {
+            return i;
+        }
+
+        int num = i & 0x7F;
+        // TODO We can't handle length longer than 4 bytes
+        if ((i >= 0xFF) || (num > lenBytes.length)) {
+            throw new StreamCorruptedException("Invalid DER: length field too big: " + i);
+        }
+
+        // place the read bytes last so that the 1st ones are zeroes as big endian
+        Arrays.fill(lenBytes, (byte) 0);
+        int n = read(lenBytes, 4 - num, num);
+        if (n < num) {
+            throw new StreamCorruptedException("Invalid DER: length data too short: expected=" + num + ", actual=" + n);
+        }
+
+        long len=BufferUtils.getUInt(lenBytes);
+        if (len < 0x7FL) {   // according to standard: "the shortest possible length encoding must be used"
+            throw new StreamCorruptedException("Invalid DER: length not in shortest form: " + len);
+        }
+
+        if (len > MAX_DER_VALUE_LENGTH) {
+            throw new StreamCorruptedException("Invalid DER: data length too big: " + len + " (max=" + MAX_DER_VALUE_LENGTH + ")");
+        }
+
+        // we know the cast is safe since it is less than MAX_DER_VALUE_LENGTH which is ~64K
+        return (int) len;
+    }
+    
+    public BigInteger readBigInteger() throws IOException {
+        int type = read();
+        if (type != 0x02) {
+            throw new StreamCorruptedException("Invalid DER: data type is not an INTEGER: 0x" + Integer.toHexString(type));
+        }
+        
+        int len = readLength();
+        byte[] value = new byte[len];
+        int n = read(value);
+        if (n < len) {
+            throw new StreamCorruptedException("Invalid DER: stream too short, missing value: read " + n + " out of required " + len);
+        }
+        
+        return new BigInteger(value);
+    }
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERWriter.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERWriter.java b/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERWriter.java
new file mode 100644
index 0000000..1e0098e
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/io/DERWriter.java
@@ -0,0 +1,113 @@
+/*
+ * 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 org.apache.sshd.common.util.io;
+
+import java.io.ByteArrayOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.StreamCorruptedException;
+import java.math.BigInteger;
+
+import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.common.util.ValidateUtils;
+import org.apache.sshd.common.util.buffer.BufferUtils;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+
+/**
+ * A bare-minimum DER encoder - just enough so we can encoder signatures
+ * and keys data
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class DERWriter extends FilterOutputStream {
+    // TODO in JDK-8 use Integer.BYTES
+    private final byte[] lenBytes = new byte[Integer.SIZE / Byte.SIZE];
+
+    public DERWriter() {
+        this(ByteArrayBuffer.DEFAULT_SIZE);
+    }
+
+    public DERWriter(int initialSize) {
+        this(new ByteArrayOutputStream(initialSize));
+    }
+
+    public DERWriter(OutputStream stream) {
+        super(ValidateUtils.checkNotNull(stream, "No output stream", GenericUtils.EMPTY_OBJECT_ARRAY));
+    }
+    
+    public void writeBigInteger(BigInteger value) throws IOException {
+        writeBigInteger(ValidateUtils.checkNotNull(value, "No value", GenericUtils.EMPTY_OBJECT_ARRAY).toByteArray());
+    }
+
+    public void writeBigInteger(byte ... bytes) throws IOException {
+        // ASN.1 - zero padding if 1st byte is > 0x7F
+        int padLen = ((bytes[0] & 0x80) != 0) ? 1 : 0;
+
+        write(0x02);    // indicate it is an INTEGER
+        writeLength(bytes.length + padLen);
+
+        for (int index = 0; index < padLen; index++) {
+            write(0);
+        }
+
+        write(bytes);
+    }
+
+    public void writeObject(byte tag, int len, byte ... data) throws IOException {
+        write(tag & 0xFF);
+        writeLength(len);
+        write(data, 0, len);
+    }
+
+    public void writeLength(int len) throws IOException {
+        ValidateUtils.checkTrue(len >= 0, "Invalid length: %d", len);
+
+        // short form - MSBit is zero
+        if (len <= 127) {
+            write(len);
+            return;
+        }
+
+        BufferUtils.putUInt(len, lenBytes);
+
+        int nonZeroPos = 0;
+        for ( ; nonZeroPos < lenBytes.length; nonZeroPos++) {
+            if (lenBytes[nonZeroPos] != 0) {
+                break;
+            }
+        }
+
+        if (nonZeroPos >= lenBytes.length) {
+            throw new StreamCorruptedException("All zeroes length representation for len=" + len);
+        }
+
+        int bytesLen=lenBytes.length - nonZeroPos;
+        write(0x80 | bytesLen); // indicate number of octets
+        write(lenBytes, nonZeroPos, bytesLen);
+    }
+    
+    public byte[] toByteArray() throws IOException {
+        if (this.out instanceof ByteArrayOutputStream) {
+            return ((ByteArrayOutputStream) this.out).toByteArray();
+        } else {
+            throw new IOException("The underlying stream is not a byte[] stream");
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/168c5054/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java b/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
index c62c83c..629c238 100644
--- a/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
@@ -25,17 +25,20 @@ import java.security.spec.ECGenParameterSpec;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.sshd.client.SshClient;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.RuntimeSshException;
+import org.apache.sshd.common.cipher.ECCurves;
+import org.apache.sshd.common.config.keys.ECDSAPublicKeyEntryDecoder;
 import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider;
 import org.apache.sshd.common.signature.BuiltinSignatures;
 import org.apache.sshd.common.signature.Signature;
 import org.apache.sshd.common.util.SecurityUtils;
-import org.apache.sshd.server.SshServer;
 import org.apache.sshd.server.PublickeyAuthenticator.AcceptAllPublickeyAuthenticator;
+import org.apache.sshd.server.SshServer;
 import org.apache.sshd.util.BaseTestSupport;
 import org.apache.sshd.util.BogusPasswordAuthenticator;
 import org.apache.sshd.util.Utils;
@@ -58,10 +61,13 @@ public class EcdsaTest extends BaseTestSupport {
     private SshClient client;
     private int port;
 
+    public EcdsaTest() {
+        super();
+    }
+
     @Before
     public void setUp() throws Exception {
         sshd = SshServer.setUpDefaultServer();
-//        sshd.setShellFactory(new TestEchoShellFactory());
         sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE);
         sshd.setSessionFactory(new org.apache.sshd.server.session.SessionFactory());
     }
@@ -78,21 +84,46 @@ public class EcdsaTest extends BaseTestSupport {
 
     @Test
     public void testECDSA_SHA2_NISTP256() throws Exception {
-        Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered());
+        testECDSA_SHA2_NISTP_Curve(ECCurves.NISTP256);
+    }
+
+    @Test
+    public void testECDSA_SHA2_NISTP384() throws Exception {
+        testECDSA_SHA2_NISTP_Curve(ECCurves.NISTP384);
+    }
+
+    @Test
+    public void testECDSA_SHA2_NISTP521() throws Exception {
+        testECDSA_SHA2_NISTP_Curve(ECCurves.NISTP521);
+    }
+
+    private void testECDSA_SHA2_NISTP_Curve(final String curvName) throws Exception {
+        Assume.assumeTrue("ECC not supported", SecurityUtils.hasEcc() || SecurityUtils.isBouncyCastleRegistered());
         sshd.setKeyPairProvider(new AbstractKeyPairProvider() {
-            @Override
-            public Iterable<KeyPair> loadKeys() {
-                try {
-                    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
-                    KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator("ECDSA");
-                    generator.initialize(ecGenSpec, new SecureRandom());
-                    KeyPair kp = generator.generateKeyPair();
-                    return Collections.singleton(kp);
-                } catch (Exception e) {
-                    throw new RuntimeSshException(e);
+                private final AtomicReference<Iterable<KeyPair>> keys=new AtomicReference<Iterable<KeyPair>>(null);
+    
+                @Override
+                public Iterable<KeyPair> loadKeys() {
+                    Iterable<KeyPair>   iter;
+                    synchronized(keys) {
+                        if ((iter=keys.get()) != null) {
+                            return iter;
+                        }
+    
+                        try {
+                            Integer keySize = ECCurves.getCurveSize(curvName);
+                            assertNotNull("No key size for curve=" + curvName, keySize);
+                            KeyPair kp = ECDSAPublicKeyEntryDecoder.INSTANCE.generateKeyPair(keySize.intValue());
+                            iter = Collections.singleton(kp);
+                            keys.set(iter);
+                        } catch (Exception e) {
+                            throw new RuntimeSshException(e);
+                        }
+                    }
+                    
+                    return iter;
                 }
-            }
-        });
+            });
         sshd.start();
         port = sshd.getPort();
 
@@ -104,7 +135,7 @@ public class EcdsaTest extends BaseTestSupport {
         client.start();
         try(ClientSession s = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
             s.addPasswordIdentity(getCurrentTestName());
-            s.auth().verify(5L, TimeUnit.SECONDS);
+            s.auth().verify(15L, TimeUnit.SECONDS);
         } finally {
             client.stop();
         }