protocol-zmtp 0.10.4 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ea36d2dec54002414471143e5dcffcbc6fcedb10a53a52f9c22684e5657c4a0d
4
- data.tar.gz: 17e2377d7534476344dd47164d8b6fde121526b4d2715af4dfb5c4682bd98bf8
3
+ metadata.gz: ee205bfb130a7339b633a11d3dc7f6f04b4cc38eebafc296fc92ae1f8e01078e
4
+ data.tar.gz: a71f3704bf7a5b9e95b605f96e3ed9ab9e96fc4d2ebc3f2117aad001b9d90b1d
5
5
  SHA512:
6
- metadata.gz: 8ecaa0325141c8e1e41f8389aa1b431328b2c9b0c83c912f301119bd49503a001889aec9db285485fe786022033927588e3843dd8af60dfb1597619ca57aff40
7
- data.tar.gz: 67af1e45d9834d9ae7ed47352758eca7b92817691bf80518addfb66de28979d4a0bbaf2ec53ff802c8fbefd788a88bfeb6d794b9669cda1fdc57be20af00f669
6
+ metadata.gz: 72c2282908a49b0cc56e79b1503158910a153990dd8589c68c1bd2194eca56a9392c7103142e3c35a14be94da6aeff1e307d986fbca8c712426ea66713e2ff00
7
+ data.tar.gz: 8ed3e02e97f0c039a970fca6b85a52596cf73e35699436e79f9adf7b7242f4bc4aaee187405b9e63ba926996cee23496f4599e05287725da988daa323798623c
data/CHANGELOG.md CHANGED
@@ -2,6 +2,51 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [0.11.0] - 2026-11-26
6
+
7
+ ### Added
8
+
9
+ - Added `Connection#pause_reading` and `#reading_paused?` so a reader blocked on
10
+ local backpressure can keep heartbeat expiry from treating the peer as silent.
11
+ - Recorded the TTL a peer sends in its PINGs as `Connection#peer_ttl`, with an
12
+ `#on_peer_ttl` callback for the first one.
13
+ - Added `Connection#max_message_parts`: a received message with more frames
14
+ raises `Protocol::ZMTP::Error`.
15
+
16
+ ### Fixed
17
+
18
+ - Checked `max_message_size` against the decrypted frame. CURVE frames were
19
+ checked with their 33-byte MESSAGE envelope, so a message at the limit dropped
20
+ the connection. Encrypted mechanisms can report `#wire_overhead`; others get
21
+ 64 bytes of slack before decryption.
22
+ - Closed the socket under a write that is blocked on a peer that stopped
23
+ reading. `#close` flushed first and waited behind the stuck writer forever.
24
+ Added `#writing?`.
25
+ - Bounded what an unauthenticated peer can send during the handshake: frames
26
+ over 64 KiB (`Codec::Frame::HANDSHAKE_MAX_SIZE`), more than 256 properties, an
27
+ identity over 255 bytes, or an as-server flag other than 0 or 1 now fail the
28
+ handshake. A peer could declare a huge READY or HELLO frame and have it read
29
+ before authentication.
30
+ - Rejected small-order CURVE public keys: a peer's short-term or permanent key,
31
+ or a configured server key, that is one of the X25519 low-order points (with
32
+ or without the top bit) now fails the handshake or raises `ArgumentError`.
33
+ With such a key the shared secret is all zero; the pure Ruby nuckle backend
34
+ did not refuse it. Added `Curve.low_order_key?`.
35
+
36
+ ## [0.10.5] - 2026-10-15
37
+
38
+ ### Added
39
+
40
+ - Allow updating `Connection#max_message_size` after the handshake so
41
+ compressed transports can bound wire envelopes separately from messages.
42
+
43
+ ### Fixed
44
+
45
+ - Reject invalid frame flags, lengths above 2^63-1, and malformed PING commands.
46
+ - Match handshake metadata names case-insensitively for NULL, PLAIN, and CURVE.
47
+ - Raise `FatalHandshakeError` on handshake ERROR responses and send ERROR when
48
+ PLAIN authentication rejects credentials.
49
+
5
50
  ## 0.10.4 - 2026-07-23
6
51
 
7
52
  ### Changed
@@ -17,6 +17,10 @@ module Protocol
17
17
  # N bytes: property value
18
18
  #
19
19
  class Command
20
+ # Most properties a peer may send in one property list.
21
+ MAX_PROPERTIES = 256
22
+
23
+
20
24
  # @return [String] command name (e.g. "READY", "SUBSCRIBE")
21
25
  attr_reader :name
22
26
 
@@ -72,7 +76,7 @@ module Protocol
72
76
 
73
77
  # Builds a READY command with Socket-Type, Identity, and any
74
78
  # extra properties supplied by upper layers (e.g. an extension
75
- # that injects +X-QoS+ or +X-Compression+).
79
+ # that injects +X-Compression+).
76
80
  #
77
81
  # @param metadata [Hash{String => String}, nil] additional READY properties
78
82
  # @return [Command]
@@ -83,6 +87,27 @@ module Protocol
83
87
  end
84
88
 
85
89
 
90
+ # Builds a fatal handshake refusal.
91
+ def self.error(reason)
92
+ raise Error, "ERROR reason exceeds 255 bytes" if reason.bytesize > 255
93
+
94
+ new("ERROR", reason.bytesize.chr.b + reason.b)
95
+ end
96
+
97
+
98
+ # ERROR is fatal even if its reason is malformed.
99
+ def raise_if_error!
100
+ return self unless @name == "ERROR"
101
+
102
+ length = @data.getbyte(0)
103
+ unless length && @data.bytesize == length + 1
104
+ raise FatalHandshakeError, "malformed ERROR command"
105
+ end
106
+
107
+ raise FatalHandshakeError, "peer rejected handshake: #{@data.byteslice(1, length).inspect}"
108
+ end
109
+
110
+
86
111
  # Builds a SUBSCRIBE command.
87
112
  #
88
113
  # @param prefix [String] subscription prefix to match
@@ -125,6 +150,9 @@ module Protocol
125
150
  # @param context [String] optional context bytes (up to 16 bytes)
126
151
  # @return [Command]
127
152
  def self.ping(ttl: 0, context: EMPTY_BINARY)
153
+ raise Error, "PING TTL must be between 0 and 6553.5 seconds" unless (0..6553.5).cover?(ttl)
154
+ raise Error, "PING context exceeds 16 bytes" if context.bytesize > 16
155
+
128
156
  ttl_ds = (ttl * 10).to_i
129
157
  new("PING", [ttl_ds].pack("n") + (context.encoding == Encoding::BINARY ? context : context.b))
130
158
  end
@@ -135,6 +163,8 @@ module Protocol
135
163
  # @param context [String] context bytes echoed from the PING
136
164
  # @return [Command]
137
165
  def self.pong(context: EMPTY_BINARY)
166
+ raise Error, "PONG context exceeds 16 bytes" if context.bytesize > 16
167
+
138
168
  new("PONG", context.encoding == Encoding::BINARY ? context : context.b)
139
169
  end
140
170
 
@@ -143,6 +173,8 @@ module Protocol
143
173
  #
144
174
  # @return [Array(Numeric, String)] [ttl_seconds, context_bytes]
145
175
  def ping_ttl_and_context
176
+ raise Error, "PING data must contain a TTL and at most 16 context bytes" unless (2..18).cover?(@data.bytesize)
177
+
146
178
  ttl_ds = @data.unpack1("n")
147
179
  context = @data.bytesize > 2 ? @data.byteslice(2..) : EMPTY_BINARY
148
180
  [ttl_ds / 10.0, context]
@@ -157,6 +189,16 @@ module Protocol
157
189
  end
158
190
 
159
191
 
192
+ # Property names are case-insensitive; retain their original spelling
193
+ # in the public metadata hash for callers that enumerate it.
194
+ def self.property(props, name)
195
+ props.each_pair do |key, value|
196
+ return value if key.casecmp?(name)
197
+ end
198
+ nil
199
+ end
200
+
201
+
160
202
  # Encodes a hash of properties into ZMTP property list format.
161
203
  #
162
204
  # @param props [Hash{String => String}] property name-value pairs
@@ -198,6 +240,7 @@ module Protocol
198
240
  offset += value_len
199
241
 
200
242
  result[name] = value
243
+ raise Error, "more than #{MAX_PROPERTIES} properties" if result.size > MAX_PROPERTIES
201
244
  end
202
245
 
203
246
  result
@@ -23,6 +23,11 @@ module Protocol
23
23
 
24
24
  # Short frame: 1-byte size, max body 255 bytes.
25
25
  SHORT_MAX = 255
26
+ LONG_MAX = (1 << 63) - 1
27
+
28
+ # Largest frame accepted before the handshake completes. A peer
29
+ # that isn't authenticated yet must not make us read a huge frame.
30
+ HANDSHAKE_MAX_SIZE = 64 * 1024
26
31
 
27
32
  # Pre-computed single-byte flag strings (avoids Integer#chr + String#b per frame).
28
33
  FLAG_BYTES = Array.new(256) { |i| i.chr.b.freeze }.freeze
@@ -102,6 +107,9 @@ module Protocol
102
107
  long = (flags & FLAGS_LONG) != 0
103
108
  command = (flags & FLAGS_COMMAND) != 0
104
109
 
110
+ raise Error, "reserved frame flags must be zero" unless (flags & 0xF8).zero?
111
+ raise Error, "command frames cannot have MORE set" if command && more
112
+
105
113
  if long
106
114
  raise EOFError, "Stream finished before reading long frame size" if buf.bytesize < 9
107
115
 
@@ -119,6 +127,8 @@ module Protocol
119
127
  header_size = 2
120
128
  end
121
129
 
130
+ raise Error, "frame size exceeds ZMTP's 63-bit limit" if size > LONG_MAX
131
+
122
132
  if max_message_size && size > max_message_size
123
133
  raise Error, "frame size #{size} exceeds max_message_size #{max_message_size}"
124
134
  end
@@ -141,6 +151,8 @@ module Protocol
141
151
  # @param more [Boolean] more frames follow
142
152
  # @param command [Boolean] this is a command frame
143
153
  def initialize(body, more: false, command: false)
154
+ raise Error, "command frames cannot have MORE set" if command && more
155
+
144
156
  @body = body
145
157
  @more = more
146
158
  @command = command
@@ -94,7 +94,10 @@ module Protocol
94
94
  end
95
95
 
96
96
  mechanism = data.byteslice(MECHANISM_OFFSET, MECHANISM_LENGTH).delete("\x00")
97
- as_server = data.getbyte(AS_SERVER_OFFSET) == 1
97
+ as_server = data.getbyte(AS_SERVER_OFFSET)
98
+ raise Error, "invalid as-server flag 0x%02x" % as_server unless as_server <= 1
99
+
100
+ as_server = as_server == 1
98
101
 
99
102
  {
100
103
  major: major,
@@ -48,6 +48,32 @@ module Protocol
48
48
  attr_reader :last_received_at
49
49
 
50
50
 
51
+ # @return [Float, nil] TTL in seconds the peer put in its last PING,
52
+ # nil if it never sent a non-zero one. The connection should be
53
+ # closed when nothing arrives for that long.
54
+ attr_reader :peer_ttl
55
+
56
+
57
+ # @return [#call, nil] called once, when the peer first sends a PING
58
+ # with a non-zero TTL, so a caller without its own heartbeat can
59
+ # start watching {#peer_ttl}
60
+ attr_accessor :on_peer_ttl
61
+
62
+ # @return [Integer, nil] largest frame body accepted after decryption,
63
+ # nil = unlimited
64
+ attr_reader :max_message_size
65
+
66
+
67
+ # @return [Integer, nil] most frames one received message may have,
68
+ # nil = unlimited
69
+ attr_accessor :max_message_parts
70
+
71
+
72
+ # Encrypted mechanisms that don't report their per-frame overhead
73
+ # get this much room on the wire before decryption.
74
+ ENCRYPTED_WIRE_SLACK = 64
75
+
76
+
51
77
  # @param io [#peek, #read_exactly, #write, #flush, #close] transport IO
52
78
  # @param socket_type [String] our socket type name (e.g. "REQ")
53
79
  # @param identity [String] our identity
@@ -55,7 +81,7 @@ module Protocol
55
81
  # @param mechanism [Mechanism::Null, Mechanism::Curve] security mechanism
56
82
  # @param max_message_size [Integer, nil] max frame size in bytes, nil = unlimited
57
83
  # @param opts [Hash{String => String}] extra READY properties to
58
- # advertise (e.g. +"X-QoS" => "1"+). Upper-layer extensions use
84
+ # advertise (e.g. +"X-Compression" => "lz4"+). Upper-layer extensions use
59
85
  # this to inject their own negotiated properties without the
60
86
  # codec needing to know about them.
61
87
  def initialize(io, socket_type:, identity: "", as_server: false,
@@ -73,8 +99,13 @@ module Protocol
73
99
  @peer_minor = nil
74
100
  @metadata = opts.empty? ? nil : opts.transform_keys(&:to_s)
75
101
  @mutex = Mutex.new
76
- @max_message_size = max_message_size
77
102
  @last_received_at = nil
103
+ @reading_paused = false
104
+ @peer_ttl = nil
105
+ @max_message_parts = nil
106
+ @on_peer_ttl = nil
107
+
108
+ self.max_message_size = max_message_size
78
109
 
79
110
  # Reusable scratch buffer for frame headers. Array#pack(buffer:)
80
111
  # writes in place so the per-message 2-or-9 byte String allocation
@@ -84,6 +115,19 @@ module Protocol
84
115
  end
85
116
 
86
117
 
118
+ # Sets the frame size limit. Transport wrappers may need room for
119
+ # bounded wire envelopes in addition to the application message
120
+ # limit they enforce after decoding. Encrypted frames are allowed
121
+ # the mechanism's overhead on the wire and checked against +size+
122
+ # after decryption.
123
+ #
124
+ # @param size [Integer, nil] max frame body in bytes, nil = unlimited
125
+ def max_message_size=(size)
126
+ @max_message_size = size
127
+ @max_wire_size = size && size + wire_overhead
128
+ end
129
+
130
+
87
131
  # Performs the full ZMTP handshake via the configured mechanism.
88
132
  #
89
133
  # @return [void]
@@ -102,6 +146,10 @@ module Protocol
102
146
  @peer_major = result[:peer_major]
103
147
  @peer_minor = result[:peer_minor]
104
148
 
149
+ if @peer_identity && @peer_identity.bytesize > 255
150
+ raise Error, "peer identity exceeds 255 bytes"
151
+ end
152
+
105
153
  unless @peer_socket_type
106
154
  raise Error, "peer READY missing Socket-Type"
107
155
  end
@@ -245,6 +293,10 @@ module Protocol
245
293
 
246
294
  frames << frame.body
247
295
  break unless frame.more?
296
+
297
+ if @max_message_parts && frames.size >= @max_message_parts
298
+ raise Error, "message exceeds max_message_parts #{@max_message_parts}"
299
+ end
248
300
  end
249
301
 
250
302
  frames
@@ -278,31 +330,55 @@ module Protocol
278
330
  # @raise [EOFError] if connection is closed
279
331
  def read_frame
280
332
  loop do
281
- begin
282
- frame = Codec::Frame.read_from(@io, max_message_size: @max_message_size)
283
- rescue Error
284
- close
285
- raise
286
- end
333
+ frame = Codec::Frame.read_from(@io, max_message_size: @max_wire_size)
287
334
 
288
335
  touch_heartbeat
289
336
 
290
- frame = @mechanism.decrypt(frame) if @mechanism.encrypted?
337
+ if @mechanism.encrypted?
338
+ frame = @mechanism.decrypt(frame)
339
+ check_decrypted_size!(frame) if @max_message_size
340
+ end
291
341
 
292
342
  if frame.command?
293
343
  cmd = Codec::Command.from_body(frame.body)
294
344
  case cmd.name
295
345
  when "PING"
296
- _, context = cmd.ping_ttl_and_context
346
+ ttl, context = cmd.ping_ttl_and_context
347
+ note_peer_ttl(ttl)
297
348
  send_command(Codec::Command.pong(context: context))
298
349
  next
299
350
  when "PONG"
351
+ raise Error, "PONG context exceeds 16 bytes" if cmd.data.bytesize > 16
300
352
  next
301
353
  end
302
354
  end
303
355
 
304
356
  return frame
305
357
  end
358
+ rescue Error
359
+ close
360
+ raise
361
+ end
362
+
363
+
364
+ # Marks a stretch where the reader stopped on purpose, e.g. while
365
+ # it waits for room in a full receive queue. Frames may be sitting
366
+ # unread, so silence from the peer means nothing then: heartbeat
367
+ # expiry ignores it, and the clock restarts when reading resumes.
368
+ #
369
+ # @yield the blocking step
370
+ def pause_reading
371
+ @reading_paused = true
372
+ yield
373
+ ensure
374
+ @reading_paused = false
375
+ touch_heartbeat
376
+ end
377
+
378
+
379
+ # @return [Boolean] whether the reader is paused by local backpressure
380
+ def reading_paused?
381
+ @reading_paused
306
382
  end
307
383
 
308
384
 
@@ -328,13 +404,66 @@ module Protocol
328
404
  #
329
405
  # @return [void]
330
406
  def close
331
- @io.close
332
- rescue IOError
407
+ raw = @io.respond_to?(:io) ? @io.io : @io
408
+
409
+ if writing? && stalled?(raw)
410
+ # A writer is blocked on a peer that stopped reading. A
411
+ # buffered close would flush behind it and never return. Shut
412
+ # the socket down under it, which fails the blocked write,
413
+ # then close it.
414
+ raw.shutdown if raw.respond_to?(:shutdown)
415
+ raw.close
416
+ else
417
+ # Idle, or a write still making progress: flush and close.
418
+ @io.close
419
+ end
420
+ rescue IOError, SystemCallError
333
421
  # already closed
334
422
  end
335
423
 
424
+
425
+ # @return [Boolean] whether a frame write is in progress
426
+ def writing?
427
+ @mutex.locked?
428
+ end
429
+
336
430
  private
337
431
 
432
+
433
+ # @return [Boolean] true if +raw+ can't take more bytes right now
434
+ def stalled?(raw)
435
+ return false unless raw.respond_to?(:wait_writable)
436
+
437
+ !raw.wait_writable(0)
438
+ end
439
+
440
+
441
+ def note_peer_ttl(ttl)
442
+ return unless ttl.positive?
443
+
444
+ first = @peer_ttl.nil?
445
+ @peer_ttl = ttl
446
+ @on_peer_ttl&.call if first
447
+ end
448
+
449
+
450
+ # Per-frame wire overhead of the mechanism (0 for plaintext).
451
+ def wire_overhead
452
+ return 0 unless @mechanism.encrypted?
453
+ return @mechanism.wire_overhead if @mechanism.respond_to?(:wire_overhead)
454
+
455
+ ENCRYPTED_WIRE_SLACK
456
+ end
457
+
458
+
459
+ def check_decrypted_size!(frame)
460
+ size = frame.body.bytesize
461
+ return if size <= @max_message_size
462
+
463
+ raise Error, "frame size #{size} exceeds max_message_size #{@max_message_size}"
464
+ end
465
+
466
+
338
467
  # Defers task cancellation around a block of wire writes so the
339
468
  # peer never sees a half-written frame or partial multipart
340
469
  # message. Without this, an +Async::Cancel+ arriving between
@@ -5,5 +5,10 @@ module Protocol
5
5
  # Raised on ZMTP protocol violations.
6
6
  class Error < RuntimeError
7
7
  end
8
+
9
+
10
+ # An explicit handshake refusal. Do not retry with the same credentials.
11
+ class FatalHandshakeError < Error
12
+ end
8
13
  end
9
14
  end
@@ -35,8 +35,24 @@ module Protocol
35
35
  NONCE_PREFIX_COOKIE = "COOKIE--"
36
36
 
37
37
 
38
- BOX_OVERHEAD = 16
39
- MAX_NONCE = (2**64) - 1
38
+ BOX_OVERHEAD = 16
39
+ MAX_NONCE = (2**64) - 1
40
+
41
+ # "\x07MESSAGE" prefix + short nonce + flags byte + Poly1305 tag.
42
+ WIRE_OVERHEAD = 8 + 8 + 1 + BOX_OVERHEAD
43
+
44
+ # X25519 public keys of small order, as libsodium lists them,
45
+ # compared with the top bit cleared. Each makes the shared secret
46
+ # all zero, so a box built from it protects nothing.
47
+ LOW_ORDER_KEYS = %w[
48
+ 0000000000000000000000000000000000000000000000000000000000000000
49
+ 0100000000000000000000000000000000000000000000000000000000000000
50
+ e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800
51
+ 5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157
52
+ ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f
53
+ edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f
54
+ eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f
55
+ ].map { |hex| [hex].pack("H*").freeze }.freeze
40
56
 
41
57
 
42
58
  # Creates a CURVE server mechanism.
@@ -65,6 +81,15 @@ module Protocol
65
81
  end
66
82
 
67
83
 
84
+ # @param key [String] 32-byte X25519 public key
85
+ # @return [Boolean] whether +key+ is a small-order point
86
+ def self.low_order_key?(key)
87
+ masked = key.b.dup
88
+ masked.setbyte(31, masked.getbyte(31) & 0x7F)
89
+ LOW_ORDER_KEYS.include?(masked)
90
+ end
91
+
92
+
68
93
  # @param public_key [String, nil] 32-byte permanent public key
69
94
  # @param secret_key [String, nil] 32-byte permanent secret key
70
95
  # @param server_key [String, nil] 32-byte server permanent public key (client only)
@@ -84,6 +109,7 @@ module Protocol
84
109
  @cookie_key = crypto::Random.random_bytes(32)
85
110
  else
86
111
  validate_key!(server_key, "server_key")
112
+ raise ArgumentError, "server_key is a low-order point" if self.class.low_order_key?(server_key.b)
87
113
  @server_public = crypto::PublicKey.new(server_key.b)
88
114
  if public_key && secret_key
89
115
  validate_key!(public_key, "public_key")
@@ -119,6 +145,13 @@ module Protocol
119
145
  # @return [Boolean] true -- CURVE always encrypts frames
120
146
  def encrypted? = true
121
147
 
148
+
149
+ # @return [Integer] bytes a MESSAGE adds to each frame body on the wire
150
+ def wire_overhead
151
+ WIRE_OVERHEAD
152
+ end
153
+
154
+
122
155
  # Returns a periodic maintenance task for rotating the cookie key (server only).
123
156
  #
124
157
  # @return [Hash, nil] a hash with +:interval+ (seconds) and +:task+ (Proc), or nil for clients
@@ -153,6 +186,8 @@ module Protocol
153
186
  # @param command [Boolean] whether this is a command frame
154
187
  # @return [String] binary wire bytes ready for writing
155
188
  def encrypt(body, more: false, command: false)
189
+ raise Error, "command frames cannot have MORE set" if command && more
190
+
156
191
  flags = 0
157
192
  flags |= 0x01 if more
158
193
  flags |= 0x02 if command
@@ -211,6 +246,8 @@ module Protocol
211
246
  end
212
247
 
213
248
  flags = plaintext.getbyte(0)
249
+ raise Error, "invalid MESSAGE flags" unless flags && (flags & 0xFC).zero?
250
+
214
251
  body = plaintext.byteslice(1..) || "".b
215
252
  Codec::Frame.new(body, more: (flags & 0x01) != 0, command: (flags & 0x02) != 0)
216
253
  end
@@ -253,9 +290,9 @@ module Protocol
253
290
  io.flush
254
291
 
255
292
  # --- Read WELCOME ---
256
- welcome_frame = Codec::Frame.read_from(io)
293
+ welcome_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
257
294
  raise Error, "expected command frame" unless welcome_frame.command?
258
- welcome_cmd = Codec::Command.from_body(welcome_frame.body)
295
+ welcome_cmd = Codec::Command.from_body(welcome_frame.body).raise_if_error!
259
296
  raise Error, "expected WELCOME, got #{welcome_cmd.name}" unless welcome_cmd.name == "WELCOME"
260
297
 
261
298
  wdata = welcome_cmd.data
@@ -271,7 +308,7 @@ module Protocol
271
308
  raise Error, "WELCOME decryption failed"
272
309
  end
273
310
 
274
- sn_public = @crypto::PublicKey.new(w_plaintext.byteslice(0, 32))
311
+ sn_public = peer_public_key(w_plaintext.byteslice(0, 32), "server short-term key")
275
312
  cookie = w_plaintext.byteslice(32, 96)
276
313
 
277
314
  session = @crypto::Box.new(sn_public, cn_secret)
@@ -305,9 +342,9 @@ module Protocol
305
342
  io.flush
306
343
 
307
344
  # --- Read READY ---
308
- ready_frame = Codec::Frame.read_from(io)
345
+ ready_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
309
346
  raise Error, "expected command frame" unless ready_frame.command?
310
- ready_cmd = Codec::Command.from_body(ready_frame.body)
347
+ ready_cmd = Codec::Command.from_body(ready_frame.body).raise_if_error!
311
348
  raise Error, "expected READY, got #{ready_cmd.name}" unless ready_cmd.name == "READY"
312
349
 
313
350
  rdata = ready_cmd.data
@@ -324,8 +361,8 @@ module Protocol
324
361
  end
325
362
 
326
363
  props = Codec::Command.decode_properties(r_plaintext)
327
- peer_socket_type = props["Socket-Type"]
328
- peer_identity = props["Identity"] || ""
364
+ peer_socket_type = Codec::Command.property(props, "Socket-Type")
365
+ peer_identity = Codec::Command.property(props, "Identity") || ""
329
366
 
330
367
  @session_box = session
331
368
  @send_nonce = 1
@@ -359,15 +396,15 @@ module Protocol
359
396
 
360
397
 
361
398
  # --- Read HELLO ---
362
- hello_frame = Codec::Frame.read_from(io)
399
+ hello_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
363
400
  raise Error, "expected command frame" unless hello_frame.command?
364
- hello_cmd = Codec::Command.from_body(hello_frame.body)
401
+ hello_cmd = Codec::Command.from_body(hello_frame.body).raise_if_error!
365
402
  raise Error, "expected HELLO, got #{hello_cmd.name}" unless hello_cmd.name == "HELLO"
366
403
 
367
404
  hdata = hello_cmd.data
368
405
  raise Error, "HELLO wrong size (#{hdata.bytesize})" unless hdata.bytesize == 194
369
406
 
370
- cn_public = @crypto::PublicKey.new(hdata.byteslice(74, 32))
407
+ cn_public = peer_public_key(hdata.byteslice(74, 32), "client short-term key")
371
408
  h_short_nonce = hdata.byteslice(106, 8)
372
409
  h_signature = hdata.byteslice(114, 80)
373
410
 
@@ -405,9 +442,9 @@ module Protocol
405
442
  io.flush
406
443
 
407
444
  # --- Read INITIATE ---
408
- init_frame = Codec::Frame.read_from(io)
445
+ init_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
409
446
  raise Error, "expected command frame" unless init_frame.command?
410
- init_cmd = Codec::Command.from_body(init_frame.body)
447
+ init_cmd = Codec::Command.from_body(init_frame.body).raise_if_error!
411
448
  raise Error, "expected INITIATE, got #{init_cmd.name}" unless init_cmd.name == "INITIATE"
412
449
 
413
450
  idata = init_cmd.data
@@ -440,7 +477,7 @@ module Protocol
440
477
 
441
478
  raise Error, "INITIATE plaintext too short" if i_plaintext.bytesize < 32 + 16 + 80
442
479
 
443
- client_permanent = @crypto::PublicKey.new(i_plaintext.byteslice(0, 32))
480
+ client_permanent = peer_public_key(i_plaintext.byteslice(0, 32), "client permanent key")
444
481
  vouch_short_nonce = i_plaintext.byteslice(32, 16)
445
482
  vouch_ciphertext = i_plaintext.byteslice(48, 80)
446
483
  metadata_bytes = i_plaintext.byteslice(128..) || "".b
@@ -468,7 +505,7 @@ module Protocol
468
505
  peer = PeerInfo.new(public_key: client_permanent, identity: "")
469
506
  unless @authenticator.call(peer)
470
507
  send_error(io, "client key not authorized")
471
- raise Error, "client key not authorized"
508
+ raise FatalHandshakeError, "client key not authorized"
472
509
  end
473
510
  end
474
511
 
@@ -498,8 +535,8 @@ module Protocol
498
535
  init_nonce_buffers!
499
536
 
500
537
  {
501
- peer_socket_type: props["Socket-Type"],
502
- peer_identity: props["Identity"] || "",
538
+ peer_socket_type: Codec::Command.property(props, "Socket-Type"),
539
+ peer_identity: Codec::Command.property(props, "Identity") || "",
503
540
  peer_public_key: client_permanent,
504
541
  peer_properties: props,
505
542
  peer_major: @peer_major,
@@ -554,6 +591,14 @@ module Protocol
554
591
  end
555
592
 
556
593
 
594
+ # Wraps a public key the peer sent, refusing small-order points.
595
+ def peer_public_key(bytes, name)
596
+ raise Error, "#{name} is a low-order point" if self.class.low_order_key?(bytes)
597
+
598
+ @crypto::PublicKey.new(bytes)
599
+ end
600
+
601
+
557
602
  def validate_key!(key, name)
558
603
  raise ArgumentError, "#{name} is required" if key.nil?
559
604
  raise ArgumentError, "#{name} must be 32 bytes (got #{key.b.bytesize})" unless key.b.bytesize == 32
@@ -43,19 +43,19 @@ module Protocol
43
43
  io.write(ready_cmd.to_frame.to_wire)
44
44
  io.flush
45
45
 
46
- frame = Codec::Frame.read_from(io)
46
+ frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
47
47
  unless frame.command?
48
48
  raise Error, "expected command frame, got data frame"
49
49
  end
50
50
 
51
- peer_cmd = Codec::Command.from_body(frame.body)
51
+ peer_cmd = Codec::Command.from_body(frame.body).raise_if_error!
52
52
  unless peer_cmd.name == "READY"
53
53
  raise Error, "expected READY command, got #{peer_cmd.name}"
54
54
  end
55
55
 
56
56
  props = peer_cmd.properties
57
- peer_socket_type = props["Socket-Type"]
58
- peer_identity = props["Identity"] || ""
57
+ peer_socket_type = Codec::Command.property(props, "Socket-Type")
58
+ peer_identity = Codec::Command.property(props, "Identity") || ""
59
59
 
60
60
  unless peer_socket_type
61
61
  raise Error, "peer READY missing Socket-Type"
@@ -92,7 +92,8 @@ module Protocol
92
92
  username, password = decode_credentials(cmd.data)
93
93
 
94
94
  if @authenticator && !@authenticator.call(username, password)
95
- raise Error, "authentication failed"
95
+ send_command(io, Codec::Command.error("authentication failed"))
96
+ raise FatalHandshakeError, "authentication failed"
96
97
  end
97
98
 
98
99
  send_command(io, Codec::Command.new("WELCOME"))
@@ -143,13 +144,13 @@ module Protocol
143
144
 
144
145
  def extract_peer_info(cmd)
145
146
  props = cmd.properties
146
- peer_socket_type = props["Socket-Type"]
147
+ peer_socket_type = Codec::Command.property(props, "Socket-Type")
147
148
 
148
149
  raise Error, "peer command missing Socket-Type" unless peer_socket_type
149
150
 
150
151
  {
151
152
  peer_socket_type: peer_socket_type,
152
- peer_identity: props["Identity"] || "",
153
+ peer_identity: Codec::Command.property(props, "Identity") || "",
153
154
  peer_properties: props,
154
155
  }
155
156
  end
@@ -162,10 +163,10 @@ module Protocol
162
163
 
163
164
 
164
165
  def read_command(io)
165
- frame = Codec::Frame.read_from(io)
166
+ frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
166
167
  raise Error, "expected command frame, got data frame" unless frame.command?
167
168
 
168
- Codec::Command.from_body(frame.body)
169
+ Codec::Command.from_body(frame.body).raise_if_error!
169
170
  end
170
171
  end
171
172
  end
@@ -9,7 +9,7 @@ module Protocol
9
9
  # - +identity+ is the peer's +ZMQ_IDENTITY+ string, or +""+ when no
10
10
  # identity was advertised in the READY metadata.
11
11
  #
12
- # Used as a peer key by upper layers (e.g. omq-qos levels 2/3): the
12
+ # Used as a peer key by upper layers: the
13
13
  # whole value object is frozen and equality-comparable, so it can be
14
14
  # stored directly in a Hash without picking one anchor over the other.
15
15
  #
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Protocol
4
4
  module ZMTP
5
- VERSION = "0.10.4"
5
+ VERSION = "0.11.0"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: protocol-zmtp
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.10.4
4
+ version: 0.11.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrik Wenger
@@ -54,7 +54,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
54
54
  - !ruby/object:Gem::Version
55
55
  version: '0'
56
56
  requirements: []
57
- rubygems_version: 4.0.16
57
+ rubygems_version: 4.0.20
58
58
  specification_version: 4
59
59
  summary: ZMTP 3.1 wire protocol codec and connection
60
60
  test_files: []