CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/net/ssh/pubkey_verifier.rb
Views: 1904
1
require 'net/ssh'
2
3
module Net
4
module SSH
5
6
class PubkeyVerifier
7
include Net::SSH::Transport::Constants
8
include Net::SSH::Authentication::Constants
9
10
attr_accessor :connection, :host, :key, :options, :user
11
12
def initialize(host,user, opts)
13
@host = host
14
# Parse public key data out into a PKey object
15
pubkey_data = opts.fetch(:key_data)
16
@key = Net::SSH::KeyFactory.load_data_public_key(pubkey_data)
17
@user = user
18
19
# Always set auth methods to ONLY publickey regardless
20
# of what the user sends
21
opts[:auth_methods] = ['publickey']
22
@options = Net::SSH.configuration_for(host, opts.fetch(:config, true)).merge(opts)
23
end
24
25
def auth_session(transport)
26
Net::SSH::Authentication::Session.new(transport,options)
27
end
28
29
def ssh_transport
30
Net::SSH::Transport::Session.new(host,options)
31
end
32
33
def verify
34
transport = ssh_transport
35
auth = auth_session(transport)
36
37
transport.send_message(transport.service_request("ssh-userauth"))
38
auth.expect_message(SERVICE_ACCEPT)
39
40
# The initial public key exchange
41
pubkey_method = Net::SSH::Authentication::Methods::Publickey.new(auth)
42
pubkey_method.send(:send_request, key, user, "ssh-connection", key.ssh_type)
43
44
# Check the response to see if the public key is good
45
response_message = auth.next_message
46
case response_message.type
47
when USERAUTH_PK_OK
48
@connection = Net::SSH::Connection::Session.new(transport, options)
49
true
50
when USERAUTH_FAILURE
51
false
52
else
53
raise Net::SSH::Exception, "unexpected reply to USERAUTH_REQUEST: #{response_message.type} (#{response_message.inspect})"
54
end
55
end
56
57
58
end
59
end
60
end
61
62