From 1980072d12a32c58f4c0a51ceab784afa0e48a96 Mon Sep 17 00:00:00 2001 From: Vladimir Lagunov Date: Wed, 16 Mar 2022 14:02:40 +0700 Subject: [PATCH] Throw IOE instead of NPE if OpenSSHKeyV1KeyFile reads an empty file There is a contract that FileKeyProvider.readKey throws an IOException if something goes wrong. Throwing an NPE is not expected by API users. Also, it is much more difficult to find out if the NPE is thrown due to a broken key file, or due to an internal bug. --- .../sshj/userauth/keyprovider/OpenSSHKeyV1KeyFile.java | 3 +++ .../net/schmizz/sshj/keyprovider/OpenSSHKeyFileTest.java | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/main/java/com/hierynomus/sshj/userauth/keyprovider/OpenSSHKeyV1KeyFile.java b/src/main/java/com/hierynomus/sshj/userauth/keyprovider/OpenSSHKeyV1KeyFile.java index 15348bac9..a9d6eb554 100644 --- a/src/main/java/com/hierynomus/sshj/userauth/keyprovider/OpenSSHKeyV1KeyFile.java +++ b/src/main/java/com/hierynomus/sshj/userauth/keyprovider/OpenSSHKeyV1KeyFile.java @@ -218,6 +218,9 @@ private boolean checkHeader(final BufferedReader reader) throws IOException { while (line != null && !line.startsWith(BEGIN)) { line = reader.readLine(); } + if (line == null) { + return false; + } line = line.substring(BEGIN.length()); return line.startsWith(OPENSSH_PRIVATE_KEY); } diff --git a/src/test/java/net/schmizz/sshj/keyprovider/OpenSSHKeyFileTest.java b/src/test/java/net/schmizz/sshj/keyprovider/OpenSSHKeyFileTest.java index d406198cf..3ebfe1644 100644 --- a/src/test/java/net/schmizz/sshj/keyprovider/OpenSSHKeyFileTest.java +++ b/src/test/java/net/schmizz/sshj/keyprovider/OpenSSHKeyFileTest.java @@ -39,6 +39,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; +import java.io.StringReader; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.PrivateKey; @@ -443,6 +444,14 @@ public void notTrimmedKeys() throws IOException { corruptedKeyFile.getPublic()); } + @Test + public void emptyPrivateKey() { + FileKeyProvider keyProvider = new OpenSSHKeyV1KeyFile(); + keyProvider.init(new StringReader("")); + + assertThrows("This key is not in 'openssh-key-v1' format", IOException.class, keyProvider::getPrivate); + } + @Before public void checkBCRegistration() { if (!SecurityUtils.isBouncyCastleRegistered()) {