-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathsocket.cr
286 lines (245 loc) · 7.92 KB
/
socket.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
abstract class OpenSSL::SSL::Socket < IO
class Client < Socket
def initialize(io, context : Context::Client = Context::Client.new, sync_close : Bool = false, hostname : String? = nil)
super(io, context, sync_close)
begin
if hostname
# Macro from OpenSSL: SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name,(char *)name)
LibSSL.ssl_ctrl(
@ssl,
LibSSL::SSLCtrl::SET_TLSEXT_HOSTNAME,
LibSSL::TLSExt::NAMETYPE_host_name,
hostname.to_unsafe.as(Pointer(Void))
)
{% if LibSSL.has_method?(:ssl_get0_param) %}
param = LibSSL.ssl_get0_param(@ssl)
if ::Socket::IPAddress.valid?(hostname)
unless LibCrypto.x509_verify_param_set1_ip_asc(param, hostname) == 1
raise OpenSSL::Error.new("X509_VERIFY_PARAM_set1_ip_asc")
end
else
unless LibCrypto.x509_verify_param_set1_host(param, hostname, 0) == 1
raise OpenSSL::Error.new("X509_VERIFY_PARAM_set1_host")
end
end
{% else %}
context.set_cert_verify_callback(hostname)
{% end %}
end
ret = LibSSL.ssl_connect(@ssl)
unless ret == 1
raise OpenSSL::SSL::Error.new(@ssl, ret, "SSL_connect")
end
rescue ex
LibSSL.ssl_free(@ssl) # GC never calls finalize, avoid mem leak
raise ex
end
end
def self.open(io, context : Context::Client = Context::Client.new, sync_close : Bool = false, hostname : String? = nil, &)
socket = new(io, context, sync_close, hostname)
begin
yield socket
ensure
socket.close
end
end
# Returns the `OpenSSL::X509::Certificate` the peer presented.
def peer_certificate : OpenSSL::X509::Certificate
super.not_nil!
end
end
class Server < Socket
def initialize(io, context : Context::Server = Context::Server.new,
sync_close : Bool = false, accept : Bool = true)
super(io, context, sync_close)
if accept
begin
self.accept
rescue ex
LibSSL.ssl_free(@ssl) # GC never calls finalize, avoid mem leak
raise ex
end
end
end
def accept : Nil
ret = LibSSL.ssl_accept(@ssl)
unless ret == 1
@bio.io.close if @sync_close
raise OpenSSL::SSL::Error.new(@ssl, ret, "SSL_accept")
end
end
def self.open(io, context : Context::Server = Context::Server.new, sync_close : Bool = false, &)
socket = new(io, context, sync_close)
begin
yield socket
ensure
socket.close
end
end
end
include IO::Buffered
# If `#sync_close?` is `true`, closing this socket will
# close the underlying IO.
property? sync_close : Bool
getter? closed : Bool
protected def initialize(io, context : Context, @sync_close : Bool = false)
@closed = false
@ssl = LibSSL.ssl_new(context)
unless @ssl
raise OpenSSL::Error.new("SSL_new")
end
# Since OpenSSL::SSL::Socket is buffered it makes no
# sense to wrap a IO::Buffered with buffering activated.
if io.is_a?(IO::Buffered)
io.sync = true
io.read_buffering = false
end
@bio = BIO.new(io)
LibSSL.ssl_set_bio(@ssl, @bio, @bio)
end
def finalize
LibSSL.ssl_free(@ssl)
end
def unbuffered_read(slice : Bytes) : Int32
check_open
count = slice.size
return 0 if count == 0
LibSSL.ssl_read(@ssl, slice.to_unsafe, count).tap do |bytes|
if bytes <= 0 && !LibSSL.ssl_get_error(@ssl, bytes).zero_return?
ex = OpenSSL::SSL::Error.new(@ssl, bytes, "SSL_read")
if ex.underlying_eof?
# underlying BIO terminated gracefully, without terminating SSL aspect gracefully first
# some misbehaving servers "do this" so treat as EOF even though it's a protocol error
return 0
end
raise ex
end
end
end
def unbuffered_write(slice : Bytes) : Nil
check_open
return if slice.empty?
count = slice.size
bytes = LibSSL.ssl_write(@ssl, slice.to_unsafe, count)
unless bytes > 0
raise OpenSSL::SSL::Error.new(@ssl, bytes, "SSL_write")
end
end
def unbuffered_flush : Nil
@bio.io.flush
end
# Returns the negotiated ALPN protocol (eg: `"h2"`) of `nil` if no protocol was
# negotiated.
def alpn_protocol
{% if LibSSL.has_method?(:ssl_get0_alpn_selected) %}
LibSSL.ssl_get0_alpn_selected(@ssl, out protocol, out len)
String.new(protocol, len) unless protocol.null?
{% else %}
raise NotImplementedError.new("LibSSL.ssl_get0_alpn_selected")
{% end %}
end
def unbuffered_close : Nil
return if @closed
@closed = true
begin
loop do
begin
ret = LibSSL.ssl_shutdown(@ssl)
break if ret == 1 # done bidirectional
break if ret == 0 && sync_close? # done unidirectional, "this first successful call to SSL_shutdown() is sufficient"
raise OpenSSL::SSL::Error.new(@ssl, ret, "SSL_shutdown") if ret < 0
rescue e : OpenSSL::SSL::Error
case e.error
when .want_read?, .want_write?
# Ignore, shutdown did not complete yet
when .syscall?
# OpenSSL claimed an underlying syscall failed, but that didn't set any error state,
# assume we're done
break
else
raise e
end
end
# ret == 0, retry, shutdown is not complete yet
end
rescue IO::Error
ensure
@bio.io.close if @sync_close
end
end
def unbuffered_rewind : Nil
raise IO::Error.new("Can't rewind OpenSSL::SSL::Socket::Client")
end
# Returns the hostname provided through Server Name Indication (SNI)
def hostname : String?
if host_name = LibSSL.ssl_get_servername(@ssl, LibSSL::TLSExt::NAMETYPE_host_name)
String.new(host_name)
end
end
# Returns the current cipher used by this socket.
def cipher : String
String.new(LibSSL.ssl_cipher_get_name(LibSSL.ssl_get_current_cipher(@ssl)))
end
# Returns the name of the TLS protocol version used by this socket.
def tls_version : String
String.new(LibSSL.ssl_get_version(@ssl))
end
def local_address
io = @bio.io
io.responds_to?(:local_address) ? io.local_address : nil
end
def remote_address
io = @bio.io
io.responds_to?(:remote_address) ? io.remote_address : nil
end
def read_timeout
io = @bio.io
if io.responds_to? :read_timeout
io.read_timeout
else
raise NotImplementedError.new("#{io.class}#read_timeout")
end
end
def read_timeout=(value)
io = @bio.io
if io.responds_to? :read_timeout=
io.read_timeout = value
else
raise NotImplementedError.new("#{io.class}#read_timeout=")
end
end
def write_timeout
io = @bio.io
if io.responds_to? :write_timeout
io.write_timeout
else
raise NotImplementedError.new("#{io.class}#write_timeout")
end
end
def write_timeout=(value)
io = @bio.io
if io.responds_to? :write_timeout=
io.write_timeout = value
else
raise NotImplementedError.new("#{io.class}#write_timeout=")
end
end
# Returns the `OpenSSL::X509::Certificate` the peer presented, if a
# connection was established.
#
# NOTE: Due to the protocol definition, a TLS/SSL server will always send a
# certificate, if present. A client will only send a certificate when
# explicitly requested to do so by the server (see `SSL_CTX_set_verify(3)`). If
# an anonymous cipher is used, no certificates are sent. That a certificate
# is returned does not indicate information about the verification state.
def peer_certificate : OpenSSL::X509::Certificate?
raw_cert = LibSSL.ssl_get_peer_certificate(@ssl)
if raw_cert
begin
OpenSSL::X509::Certificate.new(raw_cert)
ensure
LibCrypto.x509_free(raw_cert)
end
end
end
end