Module: Lich::Common::WebSocket::Handshake

Defined in:
documented/common/websocket/handshake.rb

Overview

Builds the RFC 6455 HTTP/1.1 Upgrade request and validates the server's response -- the opening handshake that precedes framed WebSocket traffic (see Frame).

Defined Under Namespace

Classes: Error

Constant Summary collapse

MAGIC_GUID =

RFC 6455 1.3: fixed GUID concatenated with the client's key before hashing to produce Sec-WebSocket-Accept.

"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

Class Method Summary collapse

Class Method Details

.accept_for(key) ⇒ String

Returns the Sec-WebSocket-Accept value a compliant server must answer with.

Parameters:

  • key (String) —

    the Sec-WebSocket-Key a request sent

Returns:

  • (String) —

    the Sec-WebSocket-Accept value a compliant server must answer with



37
38
39
# File 'documented/common/websocket/handshake.rb', line 37

def self.accept_for(key)
  Base64.strict_encode64(Digest::SHA1.digest("#{key}#{MAGIC_GUID}"))
end

.generate_key ⇒ String

Returns a fresh, base64-encoded 16-byte Sec-WebSocket-Key.

Returns:

  • (String) —

    a fresh, base64-encoded 16-byte Sec-WebSocket-Key



31
32
33
# File 'documented/common/websocket/handshake.rb', line 31

def self.generate_key
  Base64.strict_encode64(SecureRandom.bytes(16))
end

.request(host:, path:, key:, origin: nil, subprotocol: nil, user_agent: nil, extra_headers: {}) ⇒ String

Builds the raw HTTP request bytes for the opening handshake.

Parameters:

  • host (String) —

    Host header value (the game host, not the shim path)

  • path (String) —

    request path, e.g. "/shim/1234"

  • key (String) —

    this request's Sec-WebSocket-Key (see generate_key)

  • origin (String, nil) (defaults to: nil) —

    Origin header -- play.net's WAF has previously been observed rejecting requests missing a browser-like identity (see docs/connection/web-login-protocol-analysis.md); unconfirmed whether the shim itself checks it

  • subprotocol (String, nil) (defaults to: nil) —

    Sec-WebSocket-Protocol to request

  • user_agent (String, nil) (defaults to: nil)
  • extra_headers (Hash) (defaults to: {}) —

    additional/overriding headers, applied last

Returns:

  • (String) —

    the full request, including the trailing blank line

Raises:

  • (ArgumentError) —

    if path, a header name, or a header value contains a CR or LF -- none of the current callers can trigger this (host is remapped to a fixed *.play.net literal, everything else is a static default), but interpolating unvalidated values into raw request/header lines is request-smuggling-shaped regardless of how trusted today's callers happen to be



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'documented/common/websocket/handshake.rb', line 58

def self.request(host:, path:, key:, origin: nil, subprotocol: nil, user_agent: nil, extra_headers: {})
  reject_crlf!("request path", path)

  headers = {
    "Host"                  => host,
    "Upgrade"               => "websocket",
    "Connection"            => "Upgrade",
    "Sec-WebSocket-Key"     => key,
    "Sec-WebSocket-Version" => "13"
  }
  headers["Origin"] = origin if origin
  headers["Sec-WebSocket-Protocol"] = subprotocol if subprotocol
  headers["User-Agent"] = user_agent if user_agent
  headers.merge!(extra_headers)
  headers.each do |name, value|
    reject_crlf!("#{name} header name", name)
    reject_crlf!("#{name} header", value)
  end

  lines = ["GET #{path} HTTP/1.1"]
  headers.each { |name, value| lines << "#{name}: #{value}" }
  "#{lines.join("\r\n")}\r\n\r\n"
end

.validate_response(raw_response, key:, subprotocol: nil) ⇒ Hash{String => String}

Parses and validates the server's handshake response.

Parameters:

  • raw_response (String) —

    the status line + headers block, WITHOUT the trailing "\r\n\r\n" or any bytes beyond it -- the caller (see Stream.connect) is responsible for splitting the header block off from whatever frame bytes may follow it in the same read

  • key (String) —

    the Sec-WebSocket-Key the matching request sent

  • subprotocol (String, nil) (defaults to: nil) —

    if given, the response's negotiated Sec-WebSocket-Protocol must match exactly

Returns:

Raises:

  • (Error) —

    on a non-101 status, a missing/mismatched Upgrade or Connection header, an accept-key mismatch, or an unexpected subprotocol



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
# File 'documented/common/websocket/handshake.rb', line 103

def self.validate_response(raw_response, key:, subprotocol: nil)
  lines = raw_response.split("\r\n")
  status_line = lines.shift.to_s
  raise Error, "handshake rejected: #{status_line.empty? ? '(empty response)' : status_line}" unless status_line =~ %r{\AHTTP/1\.[01]\s+101\b}

  headers = parse_headers(lines)

  unless headers["upgrade"]&.downcase == "websocket"
    raise Error, "handshake response missing 'Upgrade: websocket' header: #{headers.inspect}"
  end
  unless headers["connection"]&.downcase&.split(/,\s*/)&.include?("upgrade")
    raise Error, "handshake response missing 'Connection: Upgrade' header: #{headers.inspect}"
  end

  expected_accept = accept_for(key)
  actual_accept = headers["sec-websocket-accept"]
  if actual_accept != expected_accept
    raise Error, "Sec-WebSocket-Accept mismatch (expected #{expected_accept.inspect}, got #{actual_accept.inspect})"
  end

  if subprotocol && headers["sec-websocket-protocol"] != subprotocol
    raise Error, "server did not accept subprotocol #{subprotocol.inspect} (got #{headers['sec-websocket-protocol'].inspect})"
  end

  headers
end