Skip to content

Commit b4e4c99

Browse files
committed
Use OpenSSL cipher directly to decrypt SSH private keys
1 parent c0bc2df commit b4e4c99

4 files changed

Lines changed: 36 additions & 2 deletions

File tree

lib/net/ssh/authentication/ed25519.rb

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,31 @@ def self.read(datafull, password)
8080
key = '\x00' * (keylen + ivlen)
8181
end
8282

83-
cipher = CipherFactory.get(ciphername, key: key[0...keylen], iv: key[keylen...keylen + ivlen], decrypt: true)
83+
if ciphername == 'none'
84+
cipher = Transport::IdentityCipher
85+
else
86+
cipher = OpenSSL::Cipher.new(CipherFactory::SSH_TO_OSSL[ciphername])
87+
cipher.decrypt
88+
cipher.key = key[0...keylen]
89+
cipher.iv = key[keylen...keylen + ivlen]
90+
cipher.padding = 0
91+
end
92+
93+
encrypted_data = buffer.remainder_as_buffer.to_s
94+
95+
# TODO: test with chacha poly
96+
decoded = if cipher.authenticated?
97+
# tested with GCM
98+
ciphertext = encrypted_data[0...-16]
99+
auth_tag = encrypted_data[-16..]
100+
cipher.auth_tag = auth_tag
101+
cipher.auth_data = ''
102+
cipher.update(ciphertext)
103+
else
104+
# tested with CBC
105+
cipher.update(encrypted_data)
106+
end
84107

85-
decoded = cipher.update(buffer.remainder_as_buffer.to_s)
86108
decoded << cipher.final
87109

88110
decoded = Net::SSH::Buffer.new(decoded)

lib/net/ssh/transport/chacha20_poly1305_cipher.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,10 @@ def self.block_size
111111
def self.key_length
112112
64
113113
end
114+
115+
def self.iv_len
116+
12
117+
end
114118
end
115119
end
116120
end

lib/net/ssh/transport/cipher_factory.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ class CipherFactory
3030
"aes128-ctr" => ::OpenSSL::Cipher.ciphers.include?("aes-128-ctr") ? "aes-128-ctr" : "aes-128-ecb",
3131
'cast128-ctr' => 'cast5-ecb',
3232

33+
'aes128-gcm@openssh.com' => 'aes-128-gcm',
34+
'aes256-gcm@openssh.com' => 'aes-256-gcm',
35+
'chacha20-poly1305@openssh.com' => 'chacha20-poly1305',
36+
3337
'none' => 'none'
3438
}
3539

lib/net/ssh/transport/identity_cipher.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ def reset
5858
def implicit_mac?
5959
false
6060
end
61+
62+
def authenticated?
63+
false
64+
end
6165
end
6266
end
6367
end

0 commit comments

Comments
 (0)