1009 lines
34 KiB
Ruby
1009 lines
34 KiB
Ruby
# encoding: UTF-8
|
|||
|
|
|
||
|
|
|
||
|
|
# LonaRPG application-layer secure channel for mkxp-z.
|
||
|
|
# Uses only Ruby stdlib + native Windows BCryptGenRandom through Fiddle.
|
||
|
|
# No OpenSSL::SSL::SSLSocket is required.
|
||
|
|
|
||
|
|
begin
|
||
|
|
require 'socket'
|
||
|
|
rescue LoadError
|
||
|
|
end
|
||
|
|
begin
|
||
|
|
require 'digest'
|
||
|
|
require 'digest/sha2'
|
||
|
|
rescue LoadError
|
||
|
|
end
|
||
|
|
begin
|
||
|
|
require 'base64'
|
||
|
|
rescue LoadError
|
||
|
|
end
|
||
|
|
begin
|
||
|
|
require 'securerandom'
|
||
|
|
rescue LoadError
|
||
|
|
end
|
||
|
|
|
||
|
|
module MPNativeSecureChannel
|
||
|
|
PROTOCOL = 'LSEC1'
|
||
|
|
HANDSHAKE_TIMEOUT = 6.0
|
||
|
|
MAX_FRAME_BYTES = 262_144
|
||
|
|
MAX_BUFFER_BYTES = 4 * 1024 * 1024
|
||
|
|
|
||
|
|
# Selective encryption mode: only credentials, chat and persistent save data
|
||
|
|
# use ChaCha20-Poly1305. Realtime map/NPC/player packets stay as raw UTF-8
|
||
|
|
# lines to keep the MKXP-Z game thread free from per-frame crypto work.
|
||
|
|
CLIENT_PROTECTED_PREFIXES = [
|
||
|
|
'auth:', 'nick:', 'vip_code:',
|
||
|
|
'chat:', 'chat_global:', 'chat_clan:', 'chat_last:',
|
||
|
|
'sync_state:', 'bank_req', 'bootstrap_loaded',
|
||
|
|
'home_req', 'home_sync:', 'home_visit_list', 'home_visit:', 'home_map:', 'home_ids:'
|
||
|
|
].freeze
|
||
|
|
|
||
|
|
SERVER_PROTECTED_PREFIXES = [
|
||
|
|
'secure_ready:',
|
||
|
|
'auth_ok:', 'auth_error:', 'vip_',
|
||
|
|
'chat_msg:', 'chat_msg2:', 'chat_error:', 'chat_history:',
|
||
|
|
'bootstrap_mode:', 'bootstrap_map:', 'bootstrap_pos:', 'bootstrap_state:', 'bootstrap_body:',
|
||
|
|
'bank_state:', 'cloud_save_ok:', 'sync_unlocked', 'sync_wait:',
|
||
|
|
'home_state:', 'home_sync_ok', 'home_sync_ok:', 'home_visit_list:', 'home_visit_ok:', 'home_update:', 'home_error:'
|
||
|
|
].freeze
|
||
|
|
|
||
|
|
# RSA signing public key pinned into the client. The private key exists only on the server.
|
||
|
|
SERVER_KEY_ID = '01b65c6df8a802a1c52ea9a34e3bb70a5946a361347c1fee0695fe744a16f252'
|
||
|
|
SERVER_RSA_E = 65_537
|
||
|
|
SERVER_RSA_N_HEX = 'D4AF5207B22107866B6B758C22076D56A47DEC6EABB152628F048DBC03A157A251B0810466E5A3BFF26F70EADB099B50D5FFD55A344DF36D5CD764E3A33A77E9739D20867989A0FAF8E53DD0BC30DDCFF20AD612CBECB7F49D0179A037EC64389398695CB4D46B956A764E28AE131EF839BEFB7F79480170306E8BA7214F5DD3BED4667D2EE680F8DF0C883B3CF2607B3C53A8721F559AAF737C2B44F0560EB78573E109F021661B428CD0F663A68E81C68BD25C41D5375F6E817C9E913B8F787A5FE96FB36D24FAD76A1E080103028E969D76B66436BD06E17863626B5CD140193A8CB00E64919885A89F2F8D6D3954DBCD494425465AE53A5ECAD5A7996393'
|
||
|
|
SERVER_RSA_N = SERVER_RSA_N_HEX.to_i(16)
|
||
|
|
SERVER_RSA_BYTES = (SERVER_RSA_N_HEX.length + 1) / 2
|
||
|
|
|
||
|
|
# RFC 3526 MODP Group 14 (2048-bit safe prime), generator 2.
|
||
|
|
DH_P_HEX = (
|
||
|
|
'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' \
|
||
|
|
'29024E088A67CC74020BBEA63B139B22514A08798E3404DD' \
|
||
|
|
'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' \
|
||
|
|
'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' \
|
||
|
|
'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' \
|
||
|
|
'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' \
|
||
|
|
'83655D23DCA3AD961C62F356208552BB9ED529077096966D' \
|
||
|
|
'670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' \
|
||
|
|
'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' \
|
||
|
|
'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' \
|
||
|
|
'15728E5A8AACAA68FFFFFFFFFFFFFFFF'
|
||
|
|
)
|
||
|
|
DH_P = DH_P_HEX.to_i(16)
|
||
|
|
DH_G = 2
|
||
|
|
DH_BYTES = 256
|
||
|
|
|
||
|
|
SHA256_DIGEST_INFO_PREFIX = [
|
||
|
|
'3031300d060960864801650304020105000420'
|
||
|
|
].pack('H*').freeze
|
||
|
|
|
||
|
|
class SecureChannelError < StandardError; end
|
||
|
|
|
||
|
|
# Native Windows CNG backend. bcrypt.dll is a Windows system component;
|
||
|
|
# no copy of the Microsoft DLL is bundled with the game. The backend is
|
||
|
|
# loaded through the mkxp-z Fiddle bridge and falls back to the Ruby
|
||
|
|
# implementation when CNG ChaCha20-Poly1305 is unavailable.
|
||
|
|
module BCryptChaCha20Poly1305
|
||
|
|
module_function
|
||
|
|
|
||
|
|
TAG_BYTES = 16
|
||
|
|
ALG_NAME = "CHACHA20_POLY1305".encode(Encoding::UTF_16LE).b + "\0\0".b
|
||
|
|
|
||
|
|
def pointer_size
|
||
|
|
defined?(Fiddle::SIZEOF_VOIDP) ? Fiddle::SIZEOF_VOIDP : 8
|
||
|
|
end
|
||
|
|
|
||
|
|
def pointer_pack
|
||
|
|
pointer_size == 8 ? 'Q<' : 'L<'
|
||
|
|
end
|
||
|
|
|
||
|
|
def pointer_buffer
|
||
|
|
"\0".b * pointer_size
|
||
|
|
end
|
||
|
|
|
||
|
|
def pointer_value(buffer)
|
||
|
|
buffer.to_s.b.unpack1(pointer_pack).to_i
|
||
|
|
end
|
||
|
|
|
||
|
|
def ptr(value)
|
||
|
|
return 0 if value.nil?
|
||
|
|
return value if defined?(Fiddle::Pointer) && value.is_a?(Fiddle::Pointer)
|
||
|
|
return Fiddle::Pointer[value] if value.is_a?(String)
|
||
|
|
value.to_i
|
||
|
|
end
|
||
|
|
|
||
|
|
def function(handle, name, args, result)
|
||
|
|
Fiddle::Function.new(
|
||
|
|
handle[name],
|
||
|
|
args,
|
||
|
|
result,
|
||
|
|
(defined?(Ruby310Compat) && Ruby310Compat.respond_to?(:stdcall_abi)) ? Ruby310Compat.stdcall_abi : Fiddle::Function::DEFAULT
|
||
|
|
)
|
||
|
|
end
|
||
|
|
|
||
|
|
def init_unlocked
|
||
|
|
@initialized = true
|
||
|
|
@available = false
|
||
|
|
return false unless defined?(Ruby310Compat) && Ruby310Compat.respond_to?(:windows?) && Ruby310Compat.windows?
|
||
|
|
return false unless Ruby310Compat.respond_to?(:fiddle_ready?) && Ruby310Compat.fiddle_ready?
|
||
|
|
|
||
|
|
require 'fiddle' unless defined?(Fiddle)
|
||
|
|
handle = Ruby310Compat.open_library('bcrypt.dll')
|
||
|
|
p_type = Fiddle::TYPE_VOIDP
|
||
|
|
i_type = Fiddle::TYPE_INT
|
||
|
|
|
||
|
|
@open_algorithm = function(handle, 'BCryptOpenAlgorithmProvider', [p_type, p_type, p_type, i_type], i_type)
|
||
|
|
@generate_key = function(handle, 'BCryptGenerateSymmetricKey', [p_type, p_type, p_type, i_type, p_type, i_type, i_type], i_type)
|
||
|
|
@encrypt = function(handle, 'BCryptEncrypt', [p_type, p_type, i_type, p_type, p_type, i_type, p_type, i_type, p_type, i_type], i_type)
|
||
|
|
@decrypt = function(handle, 'BCryptDecrypt', [p_type, p_type, i_type, p_type, p_type, i_type, p_type, i_type, p_type, i_type], i_type)
|
||
|
|
@destroy_key = function(handle, 'BCryptDestroyKey', [p_type], i_type)
|
||
|
|
@close_algorithm = function(handle, 'BCryptCloseAlgorithmProvider', [p_type, i_type], i_type)
|
||
|
|
|
||
|
|
alg_out = pointer_buffer
|
||
|
|
status = @open_algorithm.call(ptr(alg_out), ptr(ALG_NAME), 0, 0)
|
||
|
|
return false unless status.to_i == 0
|
||
|
|
@algorithm = pointer_value(alg_out)
|
||
|
|
return false if @algorithm == 0
|
||
|
|
|
||
|
|
@available = true
|
||
|
|
rescue Exception
|
||
|
|
@available = false
|
||
|
|
end
|
||
|
|
|
||
|
|
def available?
|
||
|
|
return @available if @initialized
|
||
|
|
if defined?(Mutex)
|
||
|
|
(@init_mutex ||= Mutex.new).synchronize do
|
||
|
|
return @available if @initialized
|
||
|
|
init_unlocked
|
||
|
|
end
|
||
|
|
else
|
||
|
|
init_unlocked
|
||
|
|
end
|
||
|
|
!!@available
|
||
|
|
rescue Exception
|
||
|
|
false
|
||
|
|
end
|
||
|
|
|
||
|
|
def build_auth_info(nonce_ptr, nonce_size, aad_ptr, aad_size, tag_ptr, tag_size)
|
||
|
|
if pointer_size == 8
|
||
|
|
# x64 BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO, sizeof == 88.
|
||
|
|
[
|
||
|
|
88, 1,
|
||
|
|
nonce_ptr.to_i, nonce_size.to_i,
|
||
|
|
aad_ptr.to_i, aad_size.to_i,
|
||
|
|
tag_ptr.to_i, tag_size.to_i,
|
||
|
|
0, 0, 0, 0, 0
|
||
|
|
].pack('L<L<Q<L<x4Q<L<x4Q<L<x4Q<L<L<Q<L<x4')
|
||
|
|
else
|
||
|
|
# x86 BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO, sizeof == 56.
|
||
|
|
[
|
||
|
|
56, 1,
|
||
|
|
nonce_ptr.to_i, nonce_size.to_i,
|
||
|
|
aad_ptr.to_i, aad_size.to_i,
|
||
|
|
tag_ptr.to_i, tag_size.to_i,
|
||
|
|
0, 0, 0, 0, 0
|
||
|
|
].pack('L<L<L<L<L<L<L<L<L<L<L<Q<L<')
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def with_key(key)
|
||
|
|
raise SecureChannelError, 'native BCrypt backend is unavailable' unless available?
|
||
|
|
secret = key.to_s.b
|
||
|
|
raise SecureChannelError, 'bad ChaCha20 key' unless secret.bytesize == 32
|
||
|
|
|
||
|
|
key_out = pointer_buffer
|
||
|
|
status = @generate_key.call(@algorithm, ptr(key_out), 0, 0, ptr(secret), secret.bytesize, 0)
|
||
|
|
raise SecureChannelError, format('BCryptGenerateSymmetricKey failed: 0x%08X', status.to_i & 0xffffffff) unless status.to_i == 0
|
||
|
|
key_handle = pointer_value(key_out)
|
||
|
|
raise SecureChannelError, 'BCryptGenerateSymmetricKey returned a null handle' if key_handle == 0
|
||
|
|
|
||
|
|
begin
|
||
|
|
yield key_handle
|
||
|
|
ensure
|
||
|
|
begin
|
||
|
|
@destroy_key.call(key_handle) if key_handle && key_handle != 0
|
||
|
|
rescue Exception
|
||
|
|
end
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def encrypt(key, nonce, aad, plaintext)
|
||
|
|
nonce = nonce.to_s.b
|
||
|
|
aad = aad.to_s.b
|
||
|
|
plain = plaintext.to_s.b
|
||
|
|
raise SecureChannelError, 'bad ChaCha20 nonce' unless nonce.bytesize == 12
|
||
|
|
|
||
|
|
with_key(key) do |key_handle|
|
||
|
|
tag = "\0".b * TAG_BYTES
|
||
|
|
output = "\0".b * [plain.bytesize, 1].max
|
||
|
|
result_size = "\0".b * 4
|
||
|
|
|
||
|
|
nonce_ptr = ptr(nonce)
|
||
|
|
aad_ptr = aad.empty? ? 0 : ptr(aad)
|
||
|
|
tag_ptr = ptr(tag)
|
||
|
|
auth = build_auth_info(nonce_ptr.to_i, nonce.bytesize, aad_ptr.respond_to?(:to_i) ? aad_ptr.to_i : aad_ptr, aad.bytesize, tag_ptr.to_i, TAG_BYTES)
|
||
|
|
input_ptr = plain.empty? ? 0 : ptr(plain)
|
||
|
|
|
||
|
|
status = @encrypt.call(
|
||
|
|
key_handle,
|
||
|
|
input_ptr,
|
||
|
|
plain.bytesize,
|
||
|
|
ptr(auth),
|
||
|
|
0,
|
||
|
|
0,
|
||
|
|
ptr(output),
|
||
|
|
plain.bytesize,
|
||
|
|
ptr(result_size),
|
||
|
|
0
|
||
|
|
)
|
||
|
|
raise SecureChannelError, format('BCryptEncrypt failed: 0x%08X', status.to_i & 0xffffffff) unless status.to_i == 0
|
||
|
|
written = result_size.unpack1('L<').to_i
|
||
|
|
raise SecureChannelError, 'BCryptEncrypt returned an invalid output size' unless written == plain.bytesize
|
||
|
|
output.byteslice(0, written).to_s.b + tag
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def decrypt(key, nonce, aad, sealed)
|
||
|
|
nonce = nonce.to_s.b
|
||
|
|
aad = aad.to_s.b
|
||
|
|
blob = sealed.to_s.b
|
||
|
|
raise SecureChannelError, 'bad ChaCha20 nonce' unless nonce.bytesize == 12
|
||
|
|
raise SecureChannelError, 'encrypted frame is too short' if blob.bytesize < TAG_BYTES
|
||
|
|
|
||
|
|
ciphertext = blob.byteslice(0, blob.bytesize - TAG_BYTES).to_s.b
|
||
|
|
tag = blob.byteslice(blob.bytesize - TAG_BYTES, TAG_BYTES).to_s.b
|
||
|
|
|
||
|
|
with_key(key) do |key_handle|
|
||
|
|
output = "\0".b * [ciphertext.bytesize, 1].max
|
||
|
|
result_size = "\0".b * 4
|
||
|
|
|
||
|
|
nonce_ptr = ptr(nonce)
|
||
|
|
aad_ptr = aad.empty? ? 0 : ptr(aad)
|
||
|
|
tag_ptr = ptr(tag)
|
||
|
|
auth = build_auth_info(nonce_ptr.to_i, nonce.bytesize, aad_ptr.respond_to?(:to_i) ? aad_ptr.to_i : aad_ptr, aad.bytesize, tag_ptr.to_i, TAG_BYTES)
|
||
|
|
input_ptr = ciphertext.empty? ? 0 : ptr(ciphertext)
|
||
|
|
|
||
|
|
status = @decrypt.call(
|
||
|
|
key_handle,
|
||
|
|
input_ptr,
|
||
|
|
ciphertext.bytesize,
|
||
|
|
ptr(auth),
|
||
|
|
0,
|
||
|
|
0,
|
||
|
|
ptr(output),
|
||
|
|
ciphertext.bytesize,
|
||
|
|
ptr(result_size),
|
||
|
|
0
|
||
|
|
)
|
||
|
|
unless status.to_i == 0
|
||
|
|
raise SecureChannelError, 'encrypted frame authentication failed'
|
||
|
|
end
|
||
|
|
written = result_size.unpack1('L<').to_i
|
||
|
|
raise SecureChannelError, 'BCryptDecrypt returned an invalid output size' unless written == ciphertext.bytesize
|
||
|
|
output.byteslice(0, written).to_s.b
|
||
|
|
end
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
module_function
|
||
|
|
|
||
|
|
def monotonic_now
|
||
|
|
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||
|
|
rescue
|
||
|
|
Time.now.to_f
|
||
|
|
end
|
||
|
|
|
||
|
|
def sha256(data)
|
||
|
|
raise SecureChannelError, 'Digest::SHA256 is unavailable' unless defined?(Digest::SHA256)
|
||
|
|
Digest::SHA256.digest(data.to_s.b)
|
||
|
|
end
|
||
|
|
|
||
|
|
def hmac_sha256(key, data)
|
||
|
|
block = 64
|
||
|
|
key = key.to_s.b
|
||
|
|
key = sha256(key) if key.bytesize > block
|
||
|
|
key = key.ljust(block, "\0")
|
||
|
|
o_key = xor_bytes(key, ("\x5c" * block).b)
|
||
|
|
i_key = xor_bytes(key, ("\x36" * block).b)
|
||
|
|
sha256(o_key + sha256(i_key + data.to_s.b))
|
||
|
|
end
|
||
|
|
|
||
|
|
def hkdf_extract(salt, ikm)
|
||
|
|
hmac_sha256(salt.to_s.b, ikm.to_s.b)
|
||
|
|
end
|
||
|
|
|
||
|
|
def hkdf_expand(prk, info, length)
|
||
|
|
raise SecureChannelError, 'HKDF output too long' if length.to_i > 8160
|
||
|
|
out = ''.b
|
||
|
|
t = ''.b
|
||
|
|
counter = 1
|
||
|
|
while out.bytesize < length.to_i
|
||
|
|
t = hmac_sha256(prk, t + info.to_s.b + [counter].pack('C'))
|
||
|
|
out << t
|
||
|
|
counter += 1
|
||
|
|
end
|
||
|
|
out.byteslice(0, length.to_i)
|
||
|
|
end
|
||
|
|
|
||
|
|
def xor_bytes(a, b)
|
||
|
|
aa = a.to_s.b
|
||
|
|
bb = b.to_s.b
|
||
|
|
raise SecureChannelError, 'XOR size mismatch' unless aa.bytesize == bb.bytesize
|
||
|
|
out = String.new(capacity: aa.bytesize, encoding: Encoding::BINARY) rescue ''.b
|
||
|
|
aa.bytes.each_with_index { |v, i| out << (v ^ bb.getbyte(i)) }
|
||
|
|
out
|
||
|
|
end
|
||
|
|
|
||
|
|
def constant_time_equal?(a, b)
|
||
|
|
aa = a.to_s.b
|
||
|
|
bb = b.to_s.b
|
||
|
|
return false unless aa.bytesize == bb.bytesize
|
||
|
|
diff = 0
|
||
|
|
aa.bytes.each_with_index { |v, i| diff |= v ^ bb.getbyte(i) }
|
||
|
|
diff == 0
|
||
|
|
end
|
||
|
|
|
||
|
|
# mkxp-z distributions may omit Ruby's optional base64.rb stdlib file.
|
||
|
|
# String#pack/unpack with the m0 directive is implemented by Ruby itself,
|
||
|
|
# so it is a dependency-free RFC 4648 fallback.
|
||
|
|
def b64e(data)
|
||
|
|
raw = data.to_s.b
|
||
|
|
if defined?(Base64) && Base64.respond_to?(:strict_encode64)
|
||
|
|
Base64.strict_encode64(raw)
|
||
|
|
else
|
||
|
|
[raw].pack('m0')
|
||
|
|
end
|
||
|
|
rescue Exception => e
|
||
|
|
raise e if e.is_a?(SecureChannelError)
|
||
|
|
raise SecureChannelError, "Base64 encode failed: #{e.message}"
|
||
|
|
end
|
||
|
|
|
||
|
|
def b64d(data)
|
||
|
|
text = data.to_s
|
||
|
|
if defined?(Base64) && Base64.respond_to?(:strict_decode64)
|
||
|
|
return Base64.strict_decode64(text)
|
||
|
|
end
|
||
|
|
|
||
|
|
# Strict validation is required because unpack('m0') can otherwise accept
|
||
|
|
# malformed input on some Ruby builds. Re-encoding also verifies padding.
|
||
|
|
unless text.bytesize % 4 == 0 &&
|
||
|
|
/\A(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?\z/.match?(text)
|
||
|
|
raise SecureChannelError, 'invalid Base64 data'
|
||
|
|
end
|
||
|
|
decoded = text.unpack('m0').first.to_s.b
|
||
|
|
raise SecureChannelError, 'invalid Base64 data' unless [decoded].pack('m0') == text
|
||
|
|
decoded
|
||
|
|
rescue ArgumentError
|
||
|
|
raise SecureChannelError, 'invalid Base64 data'
|
||
|
|
rescue Exception => e
|
||
|
|
raise e if e.is_a?(SecureChannelError)
|
||
|
|
raise SecureChannelError, "Base64 decode failed: #{e.message}"
|
||
|
|
end
|
||
|
|
|
||
|
|
def int_from_bytes(bytes)
|
||
|
|
n = 0
|
||
|
|
bytes.to_s.b.each_byte { |v| n = (n << 8) | v }
|
||
|
|
n
|
||
|
|
end
|
||
|
|
|
||
|
|
def int_to_bytes(value, size)
|
||
|
|
n = value.to_i
|
||
|
|
out = "\0".b * size.to_i
|
||
|
|
i = size.to_i - 1
|
||
|
|
while i >= 0
|
||
|
|
out.setbyte(i, n & 0xff)
|
||
|
|
n >>= 8
|
||
|
|
i -= 1
|
||
|
|
end
|
||
|
|
raise SecureChannelError, 'integer does not fit requested size' unless n == 0
|
||
|
|
out
|
||
|
|
end
|
||
|
|
|
||
|
|
def mod_pow(base, exponent, modulus)
|
||
|
|
result = 1
|
||
|
|
b = base.to_i % modulus.to_i
|
||
|
|
e = exponent.to_i
|
||
|
|
m = modulus.to_i
|
||
|
|
while e > 0
|
||
|
|
result = (result * b) % m if (e & 1) == 1
|
||
|
|
e >>= 1
|
||
|
|
b = (b * b) % m if e > 0
|
||
|
|
end
|
||
|
|
result
|
||
|
|
end
|
||
|
|
|
||
|
|
def random_bytes(length)
|
||
|
|
n = length.to_i
|
||
|
|
raise SecureChannelError, 'invalid random byte count' if n <= 0
|
||
|
|
|
||
|
|
# Windows mkxp-z: use the OS CNG generator directly through the bundled Fiddle bridge.
|
||
|
|
begin
|
||
|
|
windows = defined?(Ruby310Compat) && Ruby310Compat.respond_to?(:windows?) && Ruby310Compat.windows?
|
||
|
|
if windows && Ruby310Compat.respond_to?(:native_api)
|
||
|
|
@bcrypt_gen_random ||= Ruby310Compat.native_api('bcrypt.dll', 'BCryptGenRandom', 'PPII', 'I')
|
||
|
|
buf = "\0".b * n
|
||
|
|
status = @bcrypt_gen_random.call(nil, buf, n, 0x00000002)
|
||
|
|
return buf if status.to_i == 0
|
||
|
|
end
|
||
|
|
rescue Exception
|
||
|
|
end
|
||
|
|
|
||
|
|
begin
|
||
|
|
return SecureRandom.random_bytes(n) if defined?(SecureRandom)
|
||
|
|
rescue Exception
|
||
|
|
end
|
||
|
|
|
||
|
|
begin
|
||
|
|
File.open('/dev/urandom', 'rb') do |f|
|
||
|
|
data = f.read(n)
|
||
|
|
return data if data && data.bytesize == n
|
||
|
|
end
|
||
|
|
rescue Exception
|
||
|
|
end
|
||
|
|
|
||
|
|
raise SecureChannelError, 'cryptographic random generator is unavailable'
|
||
|
|
end
|
||
|
|
|
||
|
|
def verify_server_signature(message, signature)
|
||
|
|
sig = signature.to_s.b
|
||
|
|
return false unless sig.bytesize == SERVER_RSA_BYTES
|
||
|
|
s = int_from_bytes(sig)
|
||
|
|
return false if s <= 0 || s >= SERVER_RSA_N
|
||
|
|
em = int_to_bytes(mod_pow(s, SERVER_RSA_E, SERVER_RSA_N), SERVER_RSA_BYTES)
|
||
|
|
digest_info = SHA256_DIGEST_INFO_PREFIX + sha256(message.to_s.b)
|
||
|
|
pad_len = SERVER_RSA_BYTES - digest_info.bytesize - 3
|
||
|
|
return false if pad_len < 8
|
||
|
|
expected = "\x00\x01".b + ("\xff".b * pad_len) + "\x00".b + digest_info
|
||
|
|
constant_time_equal?(em, expected)
|
||
|
|
rescue
|
||
|
|
false
|
||
|
|
end
|
||
|
|
|
||
|
|
def rotl32(v, n)
|
||
|
|
x = v & 0xffffffff
|
||
|
|
((x << n) | (x >> (32 - n))) & 0xffffffff
|
||
|
|
end
|
||
|
|
|
||
|
|
def quarter_round(state, a, b, c, d)
|
||
|
|
state[a] = (state[a] + state[b]) & 0xffffffff
|
||
|
|
state[d] ^= state[a]
|
||
|
|
state[d] = rotl32(state[d], 16)
|
||
|
|
state[c] = (state[c] + state[d]) & 0xffffffff
|
||
|
|
state[b] ^= state[c]
|
||
|
|
state[b] = rotl32(state[b], 12)
|
||
|
|
state[a] = (state[a] + state[b]) & 0xffffffff
|
||
|
|
state[d] ^= state[a]
|
||
|
|
state[d] = rotl32(state[d], 8)
|
||
|
|
state[c] = (state[c] + state[d]) & 0xffffffff
|
||
|
|
state[b] ^= state[c]
|
||
|
|
state[b] = rotl32(state[b], 7)
|
||
|
|
end
|
||
|
|
|
||
|
|
def chacha20_block(key, counter, nonce)
|
||
|
|
key = key.to_s.b
|
||
|
|
nonce = nonce.to_s.b
|
||
|
|
raise SecureChannelError, 'bad ChaCha20 key' unless key.bytesize == 32
|
||
|
|
raise SecureChannelError, 'bad ChaCha20 nonce' unless nonce.bytesize == 12
|
||
|
|
constants = [0x61707865, 0x3320646e, 0x79622d32, 0x6b206574]
|
||
|
|
initial = constants + key.unpack('V8') + [counter.to_i & 0xffffffff] + nonce.unpack('V3')
|
||
|
|
work = initial.dup
|
||
|
|
10.times do
|
||
|
|
quarter_round(work, 0, 4, 8, 12)
|
||
|
|
quarter_round(work, 1, 5, 9, 13)
|
||
|
|
quarter_round(work, 2, 6, 10, 14)
|
||
|
|
quarter_round(work, 3, 7, 11, 15)
|
||
|
|
quarter_round(work, 0, 5, 10, 15)
|
||
|
|
quarter_round(work, 1, 6, 11, 12)
|
||
|
|
quarter_round(work, 2, 7, 8, 13)
|
||
|
|
quarter_round(work, 3, 4, 9, 14)
|
||
|
|
end
|
||
|
|
16.times { |i| work[i] = (work[i] + initial[i]) & 0xffffffff }
|
||
|
|
work.pack('V16')
|
||
|
|
end
|
||
|
|
|
||
|
|
def chacha20_xor(key, nonce, counter, data)
|
||
|
|
src = data.to_s.b
|
||
|
|
out = String.new(capacity: src.bytesize, encoding: Encoding::BINARY) rescue ''.b
|
||
|
|
block_index = 0
|
||
|
|
offset = 0
|
||
|
|
while offset < src.bytesize
|
||
|
|
stream = chacha20_block(key, counter.to_i + block_index, nonce)
|
||
|
|
take = [64, src.bytesize - offset].min
|
||
|
|
take.times { |i| out << (src.getbyte(offset + i) ^ stream.getbyte(i)) }
|
||
|
|
offset += take
|
||
|
|
block_index += 1
|
||
|
|
end
|
||
|
|
out
|
||
|
|
end
|
||
|
|
|
||
|
|
def le_int(bytes)
|
||
|
|
n = 0
|
||
|
|
bytes.to_s.b.bytes.each_with_index { |v, i| n |= v << (8 * i) }
|
||
|
|
n
|
||
|
|
end
|
||
|
|
|
||
|
|
def int_to_le(value, size)
|
||
|
|
n = value.to_i
|
||
|
|
out = ''.b
|
||
|
|
size.to_i.times do
|
||
|
|
out << (n & 0xff)
|
||
|
|
n >>= 8
|
||
|
|
end
|
||
|
|
out
|
||
|
|
end
|
||
|
|
|
||
|
|
def poly1305_mac(message, one_time_key)
|
||
|
|
key = one_time_key.to_s.b
|
||
|
|
raise SecureChannelError, 'bad Poly1305 key' unless key.bytesize == 32
|
||
|
|
r = le_int(key.byteslice(0, 16))
|
||
|
|
r &= 0x0ffffffc0ffffffc0ffffffc0fffffff
|
||
|
|
s = le_int(key.byteslice(16, 16))
|
||
|
|
p = (1 << 130) - 5
|
||
|
|
acc = 0
|
||
|
|
msg = message.to_s.b
|
||
|
|
offset = 0
|
||
|
|
while offset < msg.bytesize
|
||
|
|
chunk = msg.byteslice(offset, [16, msg.bytesize - offset].min)
|
||
|
|
n = le_int(chunk) + (1 << (8 * chunk.bytesize))
|
||
|
|
acc = ((acc + n) * r) % p
|
||
|
|
offset += chunk.bytesize
|
||
|
|
end
|
||
|
|
int_to_le((acc + s) & ((1 << 128) - 1), 16)
|
||
|
|
end
|
||
|
|
|
||
|
|
def pad16(data)
|
||
|
|
rem = data.to_s.b.bytesize % 16
|
||
|
|
rem == 0 ? ''.b : ("\0".b * (16 - rem))
|
||
|
|
end
|
||
|
|
|
||
|
|
def pack_u64_le(value)
|
||
|
|
n = value.to_i
|
||
|
|
[n & 0xffffffff, (n >> 32) & 0xffffffff].pack('V2')
|
||
|
|
end
|
||
|
|
|
||
|
|
def ruby_aead_encrypt(key, nonce, aad, plaintext)
|
||
|
|
key = key.to_s.b
|
||
|
|
nonce = nonce.to_s.b
|
||
|
|
aad = aad.to_s.b
|
||
|
|
plain = plaintext.to_s.b
|
||
|
|
poly_key = chacha20_block(key, 0, nonce).byteslice(0, 32)
|
||
|
|
ciphertext = chacha20_xor(key, nonce, 1, plain)
|
||
|
|
mac_data = aad + pad16(aad) + ciphertext + pad16(ciphertext) + pack_u64_le(aad.bytesize) + pack_u64_le(ciphertext.bytesize)
|
||
|
|
ciphertext + poly1305_mac(mac_data, poly_key)
|
||
|
|
end
|
||
|
|
|
||
|
|
def ruby_aead_decrypt(key, nonce, aad, sealed)
|
||
|
|
blob = sealed.to_s.b
|
||
|
|
raise SecureChannelError, 'encrypted frame is too short' if blob.bytesize < 16
|
||
|
|
ciphertext = blob.byteslice(0, blob.bytesize - 16)
|
||
|
|
tag = blob.byteslice(blob.bytesize - 16, 16)
|
||
|
|
poly_key = chacha20_block(key.to_s.b, 0, nonce.to_s.b).byteslice(0, 32)
|
||
|
|
mac_data = aad.to_s.b + pad16(aad) + ciphertext + pad16(ciphertext) + pack_u64_le(aad.to_s.b.bytesize) + pack_u64_le(ciphertext.bytesize)
|
||
|
|
expected = poly1305_mac(mac_data, poly_key)
|
||
|
|
raise SecureChannelError, 'encrypted frame authentication failed' unless constant_time_equal?(tag, expected)
|
||
|
|
chacha20_xor(key.to_s.b, nonce.to_s.b, 1, ciphertext)
|
||
|
|
end
|
||
|
|
|
||
|
|
def verify_native_bcrypt_backend
|
||
|
|
return @native_bcrypt_verified if defined?(@native_bcrypt_verified)
|
||
|
|
|
||
|
|
verifier = proc do
|
||
|
|
return @native_bcrypt_verified if defined?(@native_bcrypt_verified)
|
||
|
|
unless BCryptChaCha20Poly1305.available?
|
||
|
|
@native_bcrypt_verified = false
|
||
|
|
return false
|
||
|
|
end
|
||
|
|
|
||
|
|
begin
|
||
|
|
key = (0...32).map { |i| i }.pack('C*')
|
||
|
|
nonce = (0...12).map { |i| 0xA0 + i }.pack('C*')
|
||
|
|
aad = 'LSEC1|BCrypt|self-test'.b
|
||
|
|
plain = 'native ChaCha20-Poly1305 self-test'.b
|
||
|
|
expected = ruby_aead_encrypt(key, nonce, aad, plain)
|
||
|
|
actual = BCryptChaCha20Poly1305.encrypt(key, nonce, aad, plain)
|
||
|
|
roundtrip = BCryptChaCha20Poly1305.decrypt(key, nonce, aad, actual)
|
||
|
|
@native_bcrypt_verified = constant_time_equal?(expected, actual) && constant_time_equal?(plain, roundtrip)
|
||
|
|
rescue Exception
|
||
|
|
@native_bcrypt_verified = false
|
||
|
|
end
|
||
|
|
@native_bcrypt_verified
|
||
|
|
end
|
||
|
|
|
||
|
|
if defined?(Mutex)
|
||
|
|
(@native_bcrypt_verify_mutex ||= Mutex.new).synchronize { verifier.call }
|
||
|
|
else
|
||
|
|
verifier.call
|
||
|
|
end
|
||
|
|
rescue Exception
|
||
|
|
@native_bcrypt_verified = false
|
||
|
|
end
|
||
|
|
|
||
|
|
def crypto_backend
|
||
|
|
verify_native_bcrypt_backend ? 'windows-bcrypt-chacha20-poly1305' : 'ruby-chacha20-poly1305'
|
||
|
|
end
|
||
|
|
|
||
|
|
def aead_encrypt(key, nonce, aad, plaintext)
|
||
|
|
if verify_native_bcrypt_backend
|
||
|
|
begin
|
||
|
|
return BCryptChaCha20Poly1305.encrypt(key, nonce, aad, plaintext)
|
||
|
|
rescue Exception
|
||
|
|
# A provider/runtime failure must not break compatibility. Disable the
|
||
|
|
# native path for the rest of this process and use the verified Ruby
|
||
|
|
# implementation instead.
|
||
|
|
@native_bcrypt_verified = false
|
||
|
|
end
|
||
|
|
end
|
||
|
|
ruby_aead_encrypt(key, nonce, aad, plaintext)
|
||
|
|
end
|
||
|
|
|
||
|
|
def aead_decrypt(key, nonce, aad, sealed)
|
||
|
|
if verify_native_bcrypt_backend
|
||
|
|
begin
|
||
|
|
return BCryptChaCha20Poly1305.decrypt(key, nonce, aad, sealed)
|
||
|
|
rescue Exception
|
||
|
|
# Re-check with the portable implementation. Valid frames still work;
|
||
|
|
# invalid authentication tags are rejected by ruby_aead_decrypt.
|
||
|
|
@native_bcrypt_verified = false
|
||
|
|
end
|
||
|
|
end
|
||
|
|
ruby_aead_decrypt(key, nonce, aad, sealed)
|
||
|
|
end
|
||
|
|
|
||
|
|
def sequence_nonce(direction, sequence)
|
||
|
|
prefix = direction == :c2s ? "\x43\x32\x53\x01".b : "\x53\x32\x43\x01".b
|
||
|
|
seq = sequence.to_i
|
||
|
|
prefix + [((seq >> 32) & 0xffffffff), (seq & 0xffffffff)].pack('N2')
|
||
|
|
end
|
||
|
|
|
||
|
|
def aad_for(direction, sequence)
|
||
|
|
"#{PROTOCOL}|#{direction == :c2s ? 'C2S' : 'S2C'}|#{sequence}".b
|
||
|
|
end
|
||
|
|
|
||
|
|
def client_protected_line?(line)
|
||
|
|
value = line.to_s
|
||
|
|
CLIENT_PROTECTED_PREFIXES.any? { |prefix| value.start_with?(prefix) }
|
||
|
|
end
|
||
|
|
|
||
|
|
def server_protected_line?(line)
|
||
|
|
value = line.to_s
|
||
|
|
SERVER_PROTECTED_PREFIXES.any? { |prefix| value.start_with?(prefix) }
|
||
|
|
end
|
||
|
|
|
||
|
|
def protected_payload_only?(payload, direction)
|
||
|
|
lines = payload.to_s.split("\n", -1)
|
||
|
|
lines.pop while !lines.empty? && lines[-1].to_s.empty?
|
||
|
|
return false if lines.empty?
|
||
|
|
lines.all? do |line|
|
||
|
|
direction == :c2s ? client_protected_line?(line) : server_protected_line?(line)
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
class ClientConnection
|
||
|
|
attr_reader :socket, :host, :port, :server_key_id
|
||
|
|
|
||
|
|
def initialize(socket, host = nil, port = nil)
|
||
|
|
@socket = socket
|
||
|
|
@host = host.to_s
|
||
|
|
@port = port.to_i
|
||
|
|
@raw_buffer = ''.b
|
||
|
|
@plain_buffer = ''.b
|
||
|
|
@send_seq = 0
|
||
|
|
@recv_seq = 0
|
||
|
|
@established = false
|
||
|
|
@closed = false
|
||
|
|
@peer_eof = false
|
||
|
|
@server_key_id = nil
|
||
|
|
@send_key = nil
|
||
|
|
@recv_key = nil
|
||
|
|
end
|
||
|
|
|
||
|
|
def established?
|
||
|
|
@established
|
||
|
|
end
|
||
|
|
|
||
|
|
def closed?
|
||
|
|
@closed
|
||
|
|
end
|
||
|
|
|
||
|
|
def handshake!(timeout = HANDSHAKE_TIMEOUT)
|
||
|
|
line = read_raw_line(timeout)
|
||
|
|
parts = line.to_s.strip.split(' ', 6)
|
||
|
|
unless parts.length == 6 && parts[0] == PROTOCOL && parts[1] == 'HELLO'
|
||
|
|
raise SecureChannelError, 'server did not start a secure handshake'
|
||
|
|
end
|
||
|
|
|
||
|
|
key_id = parts[2].to_s.downcase
|
||
|
|
raise SecureChannelError, 'server signing key is not trusted' unless key_id == SERVER_KEY_ID
|
||
|
|
server_nonce = MPNativeSecureChannel.b64d(parts[3])
|
||
|
|
server_public_bytes = MPNativeSecureChannel.b64d(parts[4])
|
||
|
|
signature = MPNativeSecureChannel.b64d(parts[5])
|
||
|
|
raise SecureChannelError, 'invalid server nonce' unless server_nonce.bytesize == 16
|
||
|
|
raise SecureChannelError, 'invalid server DH public key size' unless server_public_bytes.bytesize == DH_BYTES
|
||
|
|
|
||
|
|
signed = "#{PROTOCOL}|HELLO|#{key_id}|".b + server_nonce + server_public_bytes
|
||
|
|
unless MPNativeSecureChannel.verify_server_signature(signed, signature)
|
||
|
|
raise SecureChannelError, 'server signature verification failed'
|
||
|
|
end
|
||
|
|
|
||
|
|
server_public = MPNativeSecureChannel.int_from_bytes(server_public_bytes)
|
||
|
|
unless server_public >= 2 && server_public <= DH_P - 2
|
||
|
|
raise SecureChannelError, 'invalid server DH public key'
|
||
|
|
end
|
||
|
|
|
||
|
|
private_exp = MPNativeSecureChannel.int_from_bytes(MPNativeSecureChannel.random_bytes(32))
|
||
|
|
private_exp = 2 if private_exp < 2
|
||
|
|
client_public = MPNativeSecureChannel.mod_pow(DH_G, private_exp, DH_P)
|
||
|
|
client_public_bytes = MPNativeSecureChannel.int_to_bytes(client_public, DH_BYTES)
|
||
|
|
client_nonce = MPNativeSecureChannel.random_bytes(16)
|
||
|
|
shared = MPNativeSecureChannel.mod_pow(server_public, private_exp, DH_P)
|
||
|
|
raise SecureChannelError, 'invalid DH shared secret' if shared <= 1
|
||
|
|
shared_bytes = MPNativeSecureChannel.int_to_bytes(shared, DH_BYTES)
|
||
|
|
|
||
|
|
write_raw("#{PROTOCOL} KEY #{MPNativeSecureChannel.b64e(client_nonce)} #{MPNativeSecureChannel.b64e(client_public_bytes)}\n")
|
||
|
|
derive_keys(shared_bytes, server_nonce, client_nonce)
|
||
|
|
@server_key_id = key_id
|
||
|
|
|
||
|
|
ready = read_secure_line(timeout)
|
||
|
|
raise SecureChannelError, 'secure channel confirmation failed' unless ready == 'secure_ready:1'
|
||
|
|
@established = true
|
||
|
|
true
|
||
|
|
rescue Exception => e
|
||
|
|
close
|
||
|
|
raise
|
||
|
|
end
|
||
|
|
|
||
|
|
def write_plain(data)
|
||
|
|
raise SecureChannelError, 'secure channel is not established' unless @established
|
||
|
|
text = data.to_s
|
||
|
|
lines = text.split("\n", -1)
|
||
|
|
lines.pop if text.end_with?("\n")
|
||
|
|
lines.each do |line|
|
||
|
|
if MPNativeSecureChannel.client_protected_line?(line)
|
||
|
|
write_secure_line(line)
|
||
|
|
else
|
||
|
|
# Realtime world traffic intentionally remains unencrypted.
|
||
|
|
write_raw(line.to_s + "\n")
|
||
|
|
end
|
||
|
|
end
|
||
|
|
text.bytesize
|
||
|
|
end
|
||
|
|
|
||
|
|
def write_line(line)
|
||
|
|
write_plain(line.to_s + "\n")
|
||
|
|
end
|
||
|
|
|
||
|
|
def read_available
|
||
|
|
return :closed if @closed
|
||
|
|
pull_available_raw
|
||
|
|
process_secure_frames
|
||
|
|
if @plain_buffer.empty?
|
||
|
|
if @peer_eof
|
||
|
|
close
|
||
|
|
return :closed
|
||
|
|
end
|
||
|
|
return ''.dup
|
||
|
|
end
|
||
|
|
out = @plain_buffer
|
||
|
|
@plain_buffer = ''.b
|
||
|
|
out.force_encoding(Encoding::UTF_8) if defined?(Encoding)
|
||
|
|
# A server may send a final critical packet (for example
|
||
|
|
# auth_error:wrong_password) and close immediately. Return that packet
|
||
|
|
# once before exposing the closed state to the caller.
|
||
|
|
close if @peer_eof
|
||
|
|
out
|
||
|
|
rescue IO::WaitReadable
|
||
|
|
''.dup
|
||
|
|
rescue Exception => e
|
||
|
|
close
|
||
|
|
raise e
|
||
|
|
end
|
||
|
|
|
||
|
|
def read_plain_until(timeout = HANDSHAKE_TIMEOUT)
|
||
|
|
deadline = MPNativeSecureChannel.monotonic_now + timeout.to_f
|
||
|
|
out = ''.b
|
||
|
|
loop do
|
||
|
|
chunk = read_available
|
||
|
|
raise SecureChannelError, 'connection closed' if chunk == :closed
|
||
|
|
out << chunk.to_s.b unless chunk.to_s.empty?
|
||
|
|
return out.force_encoding(Encoding::UTF_8) unless out.empty?
|
||
|
|
left = deadline - MPNativeSecureChannel.monotonic_now
|
||
|
|
raise SecureChannelError, 'secure read timed out' if left <= 0
|
||
|
|
IO.select([@socket], nil, nil, [left, 0.1].min)
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def close
|
||
|
|
return if @closed
|
||
|
|
@closed = true
|
||
|
|
@established = false
|
||
|
|
begin
|
||
|
|
@socket.close if @socket
|
||
|
|
rescue
|
||
|
|
end
|
||
|
|
@socket = nil
|
||
|
|
end
|
||
|
|
|
||
|
|
private
|
||
|
|
|
||
|
|
def derive_keys(shared, server_nonce, client_nonce)
|
||
|
|
salt = MPNativeSecureChannel.sha256(server_nonce.to_s.b + client_nonce.to_s.b)
|
||
|
|
prk = MPNativeSecureChannel.hkdf_extract(salt, shared.to_s.b)
|
||
|
|
@send_key = MPNativeSecureChannel.hkdf_expand(prk, "LonaRPG #{PROTOCOL} c2s".b, 32)
|
||
|
|
@recv_key = MPNativeSecureChannel.hkdf_expand(prk, "LonaRPG #{PROTOCOL} s2c".b, 32)
|
||
|
|
@send_seq = 0
|
||
|
|
@recv_seq = 0
|
||
|
|
end
|
||
|
|
|
||
|
|
def write_raw(data)
|
||
|
|
payload = data.to_s.b
|
||
|
|
total = 0
|
||
|
|
while total < payload.bytesize
|
||
|
|
part = payload.byteslice(total, payload.bytesize - total)
|
||
|
|
written = if @socket.respond_to?(:write_nonblock)
|
||
|
|
begin
|
||
|
|
@socket.write_nonblock(part)
|
||
|
|
rescue IO::WaitWritable
|
||
|
|
IO.select(nil, [@socket], nil, 0.2)
|
||
|
|
retry
|
||
|
|
end
|
||
|
|
else
|
||
|
|
@socket.write(part)
|
||
|
|
end
|
||
|
|
raise SecureChannelError, 'socket write failed' if written.to_i <= 0
|
||
|
|
total += written.to_i
|
||
|
|
end
|
||
|
|
total
|
||
|
|
end
|
||
|
|
|
||
|
|
def write_secure_line(plaintext)
|
||
|
|
seq = @send_seq
|
||
|
|
nonce = MPNativeSecureChannel.sequence_nonce(:c2s, seq)
|
||
|
|
aad = MPNativeSecureChannel.aad_for(:c2s, seq)
|
||
|
|
sealed = MPNativeSecureChannel.aead_encrypt(@send_key, nonce, aad, plaintext.to_s.b)
|
||
|
|
frame = "#{PROTOCOL} DATA #{seq} #{MPNativeSecureChannel.b64e(sealed)}\n"
|
||
|
|
write_raw(frame)
|
||
|
|
@send_seq += 1
|
||
|
|
end
|
||
|
|
|
||
|
|
def read_secure_line(timeout)
|
||
|
|
deadline = MPNativeSecureChannel.monotonic_now + timeout.to_f
|
||
|
|
loop do
|
||
|
|
line = extract_raw_line
|
||
|
|
if line
|
||
|
|
return decrypt_frame(line)
|
||
|
|
end
|
||
|
|
left = deadline - MPNativeSecureChannel.monotonic_now
|
||
|
|
raise SecureChannelError, 'secure handshake timed out' if left <= 0
|
||
|
|
ready = IO.select([@socket], nil, nil, left)
|
||
|
|
raise SecureChannelError, 'secure handshake timed out' unless ready
|
||
|
|
pull_one_raw
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def read_raw_line(timeout)
|
||
|
|
deadline = MPNativeSecureChannel.monotonic_now + timeout.to_f
|
||
|
|
loop do
|
||
|
|
line = extract_raw_line
|
||
|
|
return line if line
|
||
|
|
left = deadline - MPNativeSecureChannel.monotonic_now
|
||
|
|
raise SecureChannelError, 'secure handshake timed out' if left <= 0
|
||
|
|
ready = IO.select([@socket], nil, nil, left)
|
||
|
|
raise SecureChannelError, 'secure handshake timed out' unless ready
|
||
|
|
pull_one_raw
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def pull_one_raw
|
||
|
|
chunk = @socket.recv(4096)
|
||
|
|
raise EOFError if chunk.nil? || chunk.empty?
|
||
|
|
@raw_buffer << chunk.to_s.b
|
||
|
|
raise SecureChannelError, 'secure receive buffer exceeds maximum size' if @raw_buffer.bytesize > MAX_BUFFER_BYTES
|
||
|
|
end
|
||
|
|
|
||
|
|
def pull_available_raw
|
||
|
|
loop do
|
||
|
|
chunk = if @socket.respond_to?(:read_nonblock)
|
||
|
|
@socket.read_nonblock(4096)
|
||
|
|
else
|
||
|
|
ready = IO.select([@socket], nil, nil, 0)
|
||
|
|
break unless ready && ready[0] && !ready[0].empty?
|
||
|
|
@socket.recv(4096)
|
||
|
|
end
|
||
|
|
if chunk.nil? || chunk.empty?
|
||
|
|
@peer_eof = true
|
||
|
|
break
|
||
|
|
end
|
||
|
|
@raw_buffer << chunk.to_s.b
|
||
|
|
raise SecureChannelError, 'secure receive buffer exceeds maximum size' if @raw_buffer.bytesize > MAX_BUFFER_BYTES
|
||
|
|
end
|
||
|
|
rescue IO::WaitReadable
|
||
|
|
rescue EOFError
|
||
|
|
@peer_eof = true
|
||
|
|
end
|
||
|
|
|
||
|
|
def extract_raw_line
|
||
|
|
idx = @raw_buffer.index("\n".b)
|
||
|
|
return nil unless idx
|
||
|
|
raise SecureChannelError, 'secure frame exceeds maximum size' if idx > MAX_FRAME_BYTES
|
||
|
|
line = @raw_buffer.byteslice(0, idx)
|
||
|
|
@raw_buffer = @raw_buffer.byteslice(idx + 1, @raw_buffer.bytesize - idx - 1) || ''.b
|
||
|
|
line = line.byteslice(0, line.bytesize - 1) if line.end_with?("\r".b)
|
||
|
|
line
|
||
|
|
end
|
||
|
|
|
||
|
|
def process_secure_frames
|
||
|
|
while (line = extract_raw_line)
|
||
|
|
wire = line.to_s
|
||
|
|
if wire.start_with?("#{PROTOCOL} DATA ")
|
||
|
|
plain = decrypt_frame(wire)
|
||
|
|
unless MPNativeSecureChannel.protected_payload_only?(plain, :s2c)
|
||
|
|
raise SecureChannelError, 'server encrypted a non-protected realtime packet'
|
||
|
|
end
|
||
|
|
@plain_buffer << plain.to_s.b
|
||
|
|
@plain_buffer << "\n".b unless plain.to_s.end_with?("\n")
|
||
|
|
else
|
||
|
|
if MPNativeSecureChannel.server_protected_line?(wire)
|
||
|
|
raise SecureChannelError, 'protected server packet arrived without encryption'
|
||
|
|
end
|
||
|
|
@plain_buffer << wire.to_s.b << "\n".b
|
||
|
|
end
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def decrypt_frame(line)
|
||
|
|
parts = line.to_s.split(' ', 4)
|
||
|
|
unless parts.length == 4 && parts[0] == PROTOCOL && parts[1] == 'DATA'
|
||
|
|
raise SecureChannelError, 'unencrypted or malformed server frame'
|
||
|
|
end
|
||
|
|
seq_text = parts[2]
|
||
|
|
raise SecureChannelError, 'invalid encrypted sequence' unless seq_text =~ /\A\d+\z/
|
||
|
|
seq = seq_text.to_i
|
||
|
|
raise SecureChannelError, 'replayed or out-of-order server frame' unless seq == @recv_seq
|
||
|
|
sealed = MPNativeSecureChannel.b64d(parts[3])
|
||
|
|
nonce = MPNativeSecureChannel.sequence_nonce(:s2c, seq)
|
||
|
|
aad = MPNativeSecureChannel.aad_for(:s2c, seq)
|
||
|
|
plain = MPNativeSecureChannel.aead_decrypt(@recv_key, nonce, aad, sealed)
|
||
|
|
@recv_seq += 1
|
||
|
|
plain.force_encoding(Encoding::UTF_8) if defined?(Encoding)
|
||
|
|
plain
|
||
|
|
end
|
||
|
|
end
|
||
|
|
|
||
|
|
def connect(host, port, timeout = HANDSHAKE_TIMEOUT)
|
||
|
|
sock = TCPSocket.new(host.to_s, port.to_i)
|
||
|
|
begin
|
||
|
|
sock.sync = true if sock.respond_to?(:sync=)
|
||
|
|
rescue
|
||
|
|
end
|
||
|
|
conn = ClientConnection.new(sock, host, port)
|
||
|
|
conn.handshake!(timeout)
|
||
|
|
conn
|
||
|
|
rescue Exception => e
|
||
|
|
raise
|
||
|
|
end
|
||
|
|
|
||
|
|
def status_probe(host, port, timeout = 3.0)
|
||
|
|
conn = connect(host, port, timeout)
|
||
|
|
begin
|
||
|
|
conn.write_line('status_req')
|
||
|
|
deadline = monotonic_now + timeout.to_f
|
||
|
|
payload = ''.b
|
||
|
|
loop do
|
||
|
|
chunk = conn.read_available
|
||
|
|
raise SecureChannelError, 'connection closed during status probe' if chunk == :closed
|
||
|
|
payload << chunk.to_s.b unless chunk.to_s.empty?
|
||
|
|
break if payload.include?('server_status:')
|
||
|
|
left = deadline - monotonic_now
|
||
|
|
break if left <= 0
|
||
|
|
IO.select([conn.socket], nil, nil, [left, 0.1].min)
|
||
|
|
end
|
||
|
|
payload.force_encoding(Encoding::UTF_8) if defined?(Encoding)
|
||
|
|
payload
|
||
|
|
rescue Exception => e
|
||
|
|
raise
|
||
|
|
ensure
|
||
|
|
conn.close
|
||
|
|
end
|
||
|
|
end
|
||
|
|
end
|