Skip to content

Commit cfa4872

Browse files
Add FIDO2/U2F security key (sk-*) support (hierynomus#1043)
* Add FIDO2/U2F security key (sk-*) support * Review fixes for PR hierynomus#1043 (FIDO2/U2F sk-* support) - Remove instanceof coupling in KeyedAuthMethod.putSig(): add Signature.isSignaturePreEncoded() default method (false) and override it to true in AbstractSecurityKeySignature, eliminating the cross-package instanceof check and the import of the sk-specific class. - Return defensive copy in SecurityKeySignatureData.getSignature() to prevent callers from mutating internal state. * Added some tests * Drop net.i2p.crypto:eddsa test dependency --------- Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
1 parent 3b629c2 commit cfa4872

20 files changed

Lines changed: 1793 additions & 3 deletions

README.adoc

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ In the `examples` directory, there is a separate Maven project that shows how th
5757

5858
* reading known_hosts files for host key verification
5959
* publickey, password and keyboard-interactive authentication
60+
* FIDO/U2F security keys (`sk-ecdsa-sha2-nistp256@openssh.com`, `sk-ssh-ed25519@openssh.com`) via a pluggable `SecurityKeySigner`
6061
* SSH agent authentication over the `SSH_AUTH_SOCK` unix-domain socket (RSA, ECDSA, Ed25519, and FIDO/U2F security keys)
6162
+
6263
NOTE: The built-in unix-domain socket transport requires a Java 16+ runtime. On older runtimes, supply your own `AgentConnection` implementation.
@@ -82,7 +83,8 @@ key exchange::
8283
`diffie-hellman-group16-sha256`, `diffie-hellman-group16-sha384@ssh.com`, `diffie-hellman-group16-sha512@ssh.com`, `diffie-hellman-group18-sha512@ssh.com`
8384

8485
signatures::
85-
`ssh-rsa`, `ssh-dss`, `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521`, `ssh-ed25519`, `ssh-rsa2-256`, `ssh-rsa2-512`
86+
`ssh-rsa`, `ssh-dss`, `ecdsa-sha2-nistp256`, `ecdsa-sha2-nistp384`, `ecdsa-sha2-nistp521`, `ssh-ed25519`, `ssh-rsa2-256`, `ssh-rsa2-512`,
87+
`sk-ecdsa-sha2-nistp256@openssh.com`, `sk-ssh-ed25519@openssh.com` (FIDO/U2F security keys)
8688

8789
mac::
8890
`hmac-md5`, `hmac-md5-96`, `hmac-sha1`, `hmac-sha1-96`, `hmac-sha2-256`, `hmac-sha2-512`, `hmac-ripemd160`, `hmac-ripemd160@openssh.com`
@@ -92,7 +94,7 @@ compression::
9294
`zlib` and `zlib@openssh.com` (delayed zlib)
9395

9496
private key files::
95-
`pkcs5`, `pkcs8`, `openssh-key-v1`, `ssh-rsa-cert-v01@openssh.com`, `ssh-dsa-cert-v01@openssh.com`
97+
`pkcs5`, `pkcs8`, `openssh-key-v1` (including FIDO/U2F `sk-ecdsa-sha2-nistp256@openssh.com` and `sk-ssh-ed25519@openssh.com` keys), `ssh-rsa-cert-v01@openssh.com`, `ssh-dsa-cert-v01@openssh.com`
9698

9799
If you need something that is not included, it shouldn't be too hard to add (do contribute it!)
98100

src/main/java/com/hierynomus/sshj/key/KeyAlgorithms.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
package com.hierynomus.sshj.key;
1717

1818
import com.hierynomus.sshj.signature.SignatureEdDSA;
19+
import com.hierynomus.sshj.signature.SignatureSkEcdsa;
20+
import com.hierynomus.sshj.signature.SignatureSkEd25519;
1921
import net.schmizz.sshj.common.KeyType;
2022
import net.schmizz.sshj.signature.Signature;
2123
import net.schmizz.sshj.signature.SignatureDSA;
@@ -38,6 +40,8 @@ public class KeyAlgorithms {
3840
public static Factory ECDSASHANistp521CertV01() { return new Factory(KeyType.ECDSA521_CERT.toString(), new SignatureECDSA.Factory521(), KeyType.ECDSA521_CERT); }
3941
public static Factory EdDSA25519() { return new Factory(KeyType.ED25519.toString(), new SignatureEdDSA.Factory(), KeyType.ED25519); }
4042
public static Factory EdDSA25519CertV01() { return new Factory(KeyType.ED25519_CERT.toString(), new SignatureEdDSA.Factory(), KeyType.ED25519_CERT); }
43+
public static Factory SkSSHEd25519() { return new Factory(KeyType.SK_ED25519.toString(), new SignatureSkEd25519.Factory(), KeyType.SK_ED25519); }
44+
public static Factory SkECDSANistp256() { return new Factory(KeyType.SK_ECDSA.toString(), new SignatureSkEcdsa.Factory(), KeyType.SK_ECDSA); }
4145

4246
public static class Factory implements net.schmizz.sshj.common.Factory.Named<KeyAlgorithm> {
4347

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
/*
2+
* Copyright (C)2009 - SSHJ Contributors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.hierynomus.sshj.signature;
17+
18+
import com.hierynomus.sshj.userauth.fido.SecurityKeyPrivateKey;
19+
import com.hierynomus.sshj.userauth.fido.SecurityKeyPublicKey;
20+
import com.hierynomus.sshj.userauth.fido.SecurityKeySignatureData;
21+
import com.hierynomus.sshj.userauth.fido.SecurityKeySigner;
22+
import com.hierynomus.sshj.userauth.fido.SecurityKeySigningRequest;
23+
import net.schmizz.sshj.common.Buffer;
24+
import net.schmizz.sshj.common.SSHRuntimeException;
25+
import net.schmizz.sshj.signature.AbstractSignatureDSA;
26+
27+
import java.io.ByteArrayOutputStream;
28+
import java.io.IOException;
29+
import java.nio.charset.StandardCharsets;
30+
import java.security.MessageDigest;
31+
import java.security.NoSuchAlgorithmException;
32+
import java.security.PrivateKey;
33+
import java.security.PublicKey;
34+
import java.security.SignatureException;
35+
36+
/**
37+
* Base class for the OpenSSH FIDO/U2F security key signatures
38+
* ({@code sk-ecdsa-sha2-nistp256@openssh.com} and {@code sk-ssh-ed25519@openssh.com}).
39+
* <p>
40+
* The difference from an ordinary SSH signature is what actually gets signed. A FIDO authenticator
41+
* never sees the SSH payload directly; instead it signs a small fixed structure (WebAuthn calls it
42+
* the authenticator data plus the client-data hash):
43+
*
44+
* <pre>
45+
* signed = SHA256(application) || flags || counter || SHA256(sshData)
46+
* </pre>
47+
*
48+
* and the wire signature carries the {@code flags} and {@code counter} so the verifier can rebuild
49+
* that structure:
50+
*
51+
* <pre>
52+
* string key type
53+
* string raw signature (ECDSA r||s as two mpints, or 64-byte Ed25519 signature)
54+
* byte flags
55+
* uint32 counter
56+
* </pre>
57+
*
58+
* Verification rebuilds {@code signed} and checks it with the underlying ECDSA/Ed25519 key. Signing
59+
* is delegated to a {@link SecurityKeySigner} (the hardware bridge); this class only hashes the SSH
60+
* payload, hands the challenge to the signer and assembles the wire format from what comes back.
61+
*
62+
* @see <a href="https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.u2f">PROTOCOL.u2f</a>
63+
*/
64+
public abstract class AbstractSecurityKeySignature extends AbstractSignatureDSA {
65+
66+
private final ByteArrayOutputStream sshData = new ByteArrayOutputStream();
67+
private String application;
68+
private SecurityKeyPrivateKey signingKey;
69+
private byte signedFlags;
70+
private long signedCounter;
71+
72+
protected AbstractSecurityKeySignature(String algorithm, String keyTypeName) {
73+
super(algorithm, keyTypeName);
74+
}
75+
76+
@Override
77+
public boolean isSignaturePreEncoded() {
78+
return true;
79+
}
80+
81+
@Override
82+
public void initVerify(PublicKey publicKey) {
83+
if (!(publicKey instanceof SecurityKeyPublicKey)) {
84+
throw new SSHRuntimeException("Expected a SecurityKeyPublicKey but got: " + publicKey);
85+
}
86+
SecurityKeyPublicKey sk = (SecurityKeyPublicKey) publicKey;
87+
this.application = sk.getApplication();
88+
super.initVerify(sk.getDelegate());
89+
}
90+
91+
@Override
92+
public void initSign(PrivateKey privateKey) {
93+
if (!(privateKey instanceof SecurityKeyPrivateKey)) {
94+
throw new SSHRuntimeException("Expected a SecurityKeyPrivateKey but got: " + privateKey);
95+
}
96+
this.signingKey = (SecurityKeyPrivateKey) privateKey;
97+
this.application = signingKey.getApplication();
98+
}
99+
100+
@Override
101+
public void update(byte[] foo, int off, int len) {
102+
sshData.write(foo, off, len);
103+
}
104+
105+
@Override
106+
public byte[] sign() {
107+
if (signingKey == null) {
108+
throw new SSHRuntimeException("initSign was not called with a SecurityKeyPrivateKey");
109+
}
110+
SecurityKeySigner signer = signingKey.getSigner();
111+
if (signer == null) {
112+
throw new SSHRuntimeException("No SecurityKeySigner attached to security key " + signingKey.getKeyTypeName()
113+
+ "; cannot reach the authenticator. Authenticate via ssh-agent or attach a SecurityKeySigner.");
114+
}
115+
byte[] challenge = sha256(sshData.toByteArray());
116+
SecurityKeySignatureData data;
117+
try {
118+
data = signer.sign(new SecurityKeySigningRequest(signingKey.getKeyTypeName(), application,
119+
signingKey.getKeyHandle(), challenge, signingKey.getFlags()));
120+
} catch (IOException e) {
121+
throw new SSHRuntimeException("Security key signing failed", e);
122+
}
123+
this.signedFlags = data.getFlags();
124+
this.signedCounter = data.getCounter();
125+
return deviceSignatureToSsh(data.getSignature());
126+
}
127+
128+
/**
129+
* Assemble the full SSH signature value: {@code string keyType || string rawSig || byte flags || uint32 counter}.
130+
* Relies on {@link #sign()} having been called first to capture the flags and counter.
131+
*/
132+
@Override
133+
public byte[] encode(byte[] sshRawSignature) {
134+
return new Buffer.PlainBuffer()
135+
.putString(getSignatureName())
136+
.putBytes(sshRawSignature)
137+
.putByte(signedFlags)
138+
.putUInt32(signedCounter)
139+
.getCompactData();
140+
}
141+
142+
@Override
143+
public boolean verify(byte[] sig) {
144+
Buffer.PlainBuffer buf = new Buffer.PlainBuffer(sig);
145+
try {
146+
String type = buf.readString();
147+
if (!getSignatureName().equals(type)) {
148+
throw new SSHRuntimeException("Expected '" + getSignatureName() + "' signature but got: " + type);
149+
}
150+
byte[] sshRawSignature = buf.readBytes();
151+
byte flags = buf.readByte();
152+
long counter = buf.readUInt32();
153+
154+
byte[] signedData = buildSignedData(flags, counter, sha256(sshData.toByteArray()));
155+
signature.update(signedData);
156+
return signature.verify(sshSignatureToDevice(sshRawSignature));
157+
} catch (Buffer.BufferException | SignatureException e) {
158+
throw new SSHRuntimeException(e);
159+
}
160+
}
161+
162+
/**
163+
* The exact bytes the authenticator signs: {@code SHA256(application) || flags || counter || clientDataHash}.
164+
*/
165+
private byte[] buildSignedData(byte flags, long counter, byte[] clientDataHash) {
166+
byte[] rpIdHash = sha256(application.getBytes(StandardCharsets.UTF_8));
167+
return new Buffer.PlainBuffer()
168+
.putRawBytes(rpIdHash)
169+
.putByte(flags)
170+
.putUInt32(counter)
171+
.putRawBytes(clientDataHash)
172+
.getCompactData();
173+
}
174+
175+
protected static byte[] sha256(byte[] data) {
176+
try {
177+
return MessageDigest.getInstance("SHA-256").digest(data);
178+
} catch (NoSuchAlgorithmException e) {
179+
throw new SSHRuntimeException(e);
180+
}
181+
}
182+
183+
/**
184+
* Convert the SSH raw-signature encoding read off the wire into the byte format the JCA
185+
* verification engine expects (DER for ECDSA, unchanged for Ed25519).
186+
*/
187+
protected abstract byte[] sshSignatureToDevice(byte[] sshRawSignature) throws Buffer.BufferException;
188+
189+
/**
190+
* Convert the authenticator's native signature into the SSH raw-signature encoding (r||s as two
191+
* mpints for ECDSA, unchanged for Ed25519).
192+
*/
193+
protected abstract byte[] deviceSignatureToSsh(byte[] deviceSignature);
194+
}
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* Copyright (C)2009 - SSHJ Contributors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.hierynomus.sshj.signature;
17+
18+
import com.hierynomus.asn1.ASN1InputStream;
19+
import com.hierynomus.asn1.encodingrules.der.DERDecoder;
20+
import com.hierynomus.asn1.types.constructed.ASN1Sequence;
21+
import com.hierynomus.asn1.types.primitive.ASN1Integer;
22+
import net.schmizz.sshj.common.Buffer;
23+
import net.schmizz.sshj.common.IOUtils;
24+
import net.schmizz.sshj.common.KeyType;
25+
import net.schmizz.sshj.common.SSHRuntimeException;
26+
import net.schmizz.sshj.signature.Signature;
27+
28+
import java.io.ByteArrayInputStream;
29+
import java.io.IOException;
30+
import java.math.BigInteger;
31+
32+
/**
33+
* Signature for the {@code sk-ecdsa-sha2-nistp256@openssh.com} FIDO/U2F key type.
34+
* <p>
35+
* The authenticator produces an ASN.1 DER ECDSA signature; on the SSH wire it is encoded as the two
36+
* integers {@code r} and {@code s} as mpints, exactly like a plain {@code ecdsa-sha2-nistp256}
37+
* signature. This class converts between the two encodings. The verification engine is always
38+
* SHA-256 (the "sha2-nistp256" of the key type).
39+
*/
40+
public class SignatureSkEcdsa extends AbstractSecurityKeySignature {
41+
42+
public static class Factory implements net.schmizz.sshj.common.Factory.Named<Signature> {
43+
@Override
44+
public String getName() {
45+
return KeyType.SK_ECDSA.toString();
46+
}
47+
48+
@Override
49+
public Signature create() {
50+
return new SignatureSkEcdsa();
51+
}
52+
}
53+
54+
public SignatureSkEcdsa() {
55+
super("SHA256withECDSA", KeyType.SK_ECDSA.toString());
56+
}
57+
58+
@Override
59+
protected byte[] sshSignatureToDevice(byte[] sshRawSignature) throws Buffer.BufferException {
60+
Buffer.PlainBuffer buf = new Buffer.PlainBuffer(sshRawSignature);
61+
BigInteger r = buf.readMPInt();
62+
BigInteger s = buf.readMPInt();
63+
try {
64+
return encodeAsnSignature(r, s);
65+
} catch (IOException e) {
66+
throw new SSHRuntimeException(e);
67+
}
68+
}
69+
70+
@Override
71+
protected byte[] deviceSignatureToSsh(byte[] derSignature) {
72+
ByteArrayInputStream bais = new ByteArrayInputStream(derSignature);
73+
ASN1InputStream asn1InputStream = new ASN1InputStream(new DERDecoder(), bais);
74+
try {
75+
ASN1Sequence sequence = asn1InputStream.readObject();
76+
BigInteger r = ((ASN1Integer) sequence.get(0)).getValue();
77+
BigInteger s = ((ASN1Integer) sequence.get(1)).getValue();
78+
return new Buffer.PlainBuffer().putMPInt(r).putMPInt(s).getCompactData();
79+
} finally {
80+
IOUtils.closeQuietly(asn1InputStream, bais);
81+
}
82+
}
83+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
* Copyright (C)2009 - SSHJ Contributors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.hierynomus.sshj.signature;
17+
18+
import net.schmizz.sshj.common.KeyType;
19+
import net.schmizz.sshj.signature.Signature;
20+
21+
/**
22+
* Signature for the {@code sk-ssh-ed25519@openssh.com} FIDO/U2F key type. The raw Ed25519
23+
* signature is used as-is in both directions.
24+
*/
25+
public class SignatureSkEd25519 extends AbstractSecurityKeySignature {
26+
27+
public static class Factory implements net.schmizz.sshj.common.Factory.Named<Signature> {
28+
@Override
29+
public String getName() {
30+
return KeyType.SK_ED25519.toString();
31+
}
32+
33+
@Override
34+
public Signature create() {
35+
return new SignatureSkEd25519();
36+
}
37+
}
38+
39+
public SignatureSkEd25519() {
40+
super("Ed25519", KeyType.SK_ED25519.toString());
41+
}
42+
43+
@Override
44+
protected byte[] sshSignatureToDevice(byte[] sshRawSignature) {
45+
return sshRawSignature;
46+
}
47+
48+
@Override
49+
protected byte[] deviceSignatureToSsh(byte[] deviceSignature) {
50+
return deviceSignature;
51+
}
52+
}

0 commit comments

Comments
 (0)