protocol-zmtp 0.10.5 → 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: c8d53545d14bf02a264d165e08adb9ab22b1f948a614856644dea0a093dc1da5
4
- data.tar.gz: cf71224105abc69d8cd6df5d2ab5e45cdcbed0c88ff257a6325fdd3deeb8312c
3
+ metadata.gz: ee205bfb130a7339b633a11d3dc7f6f04b4cc38eebafc296fc92ae1f8e01078e
4
+ data.tar.gz: a71f3704bf7a5b9e95b605f96e3ed9ab9e96fc4d2ebc3f2117aad001b9d90b1d
5
5
  SHA512:
6
- metadata.gz: 677c05b2057178c6c388805c53c9dd1b314c06a4c436cf448b1d0fa2f2cdc6515c7818e0f3995a398b336487bebf74f6c00f8380837f635fd9377e1c11d8b3b1
7
- data.tar.gz: 912e32a6301493475a676952ad1ac1c9ddff7e1f68e0b5415b20fd344dfe32d3e887d51faa00a0dce1f8fe4fb219cd50f899517e21a5c0b47dfd33b1140b3cb9
6
+ metadata.gz: 72c2282908a49b0cc56e79b1503158910a153990dd8589c68c1bd2194eca56a9392c7103142e3c35a14be94da6aeff1e307d986fbca8c712426ea66713e2ff00
7
+ data.tar.gz: 8ed3e02e97f0c039a970fca6b85a52596cf73e35699436e79f9adf7b7242f4bc4aaee187405b9e63ba926996cee23496f4599e05287725da988daa323798623c
data/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
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
+
5
36
  ## [0.10.5] - 2026-10-15
6
37
 
7
38
  ### Added
@@ -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
 
@@ -236,6 +240,7 @@ module Protocol
236
240
  offset += value_len
237
241
 
238
242
  result[name] = value
243
+ raise Error, "more than #{MAX_PROPERTIES} properties" if result.size > MAX_PROPERTIES
239
244
  end
240
245
 
241
246
  result
@@ -25,6 +25,10 @@ module Protocol
25
25
  SHORT_MAX = 255
26
26
  LONG_MAX = (1 << 63) - 1
27
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
31
+
28
32
  # Pre-computed single-byte flag strings (avoids Integer#chr + String#b per frame).
29
33
  FLAG_BYTES = Array.new(256) { |i| i.chr.b.freeze }.freeze
30
34
 
@@ -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,
@@ -47,9 +47,31 @@ module Protocol
47
47
  # @return [Float, nil] monotonic timestamp of last received frame
48
48
  attr_reader :last_received_at
49
49
 
50
- # Transport wrappers may need room for bounded wire envelopes in
51
- # addition to the application message limit they enforce after decoding.
52
- attr_writer :max_message_size
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
53
75
 
54
76
 
55
77
  # @param io [#peek, #read_exactly, #write, #flush, #close] transport IO
@@ -77,8 +99,13 @@ module Protocol
77
99
  @peer_minor = nil
78
100
  @metadata = opts.empty? ? nil : opts.transform_keys(&:to_s)
79
101
  @mutex = Mutex.new
80
- @max_message_size = max_message_size
81
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
82
109
 
83
110
  # Reusable scratch buffer for frame headers. Array#pack(buffer:)
84
111
  # writes in place so the per-message 2-or-9 byte String allocation
@@ -88,6 +115,19 @@ module Protocol
88
115
  end
89
116
 
90
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
+
91
131
  # Performs the full ZMTP handshake via the configured mechanism.
92
132
  #
93
133
  # @return [void]
@@ -106,6 +146,10 @@ module Protocol
106
146
  @peer_major = result[:peer_major]
107
147
  @peer_minor = result[:peer_minor]
108
148
 
149
+ if @peer_identity && @peer_identity.bytesize > 255
150
+ raise Error, "peer identity exceeds 255 bytes"
151
+ end
152
+
109
153
  unless @peer_socket_type
110
154
  raise Error, "peer READY missing Socket-Type"
111
155
  end
@@ -249,6 +293,10 @@ module Protocol
249
293
 
250
294
  frames << frame.body
251
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
252
300
  end
253
301
 
254
302
  frames
@@ -282,17 +330,21 @@ module Protocol
282
330
  # @raise [EOFError] if connection is closed
283
331
  def read_frame
284
332
  loop do
285
- frame = Codec::Frame.read_from(@io, max_message_size: @max_message_size)
333
+ frame = Codec::Frame.read_from(@io, max_message_size: @max_wire_size)
286
334
 
287
335
  touch_heartbeat
288
336
 
289
- 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
290
341
 
291
342
  if frame.command?
292
343
  cmd = Codec::Command.from_body(frame.body)
293
344
  case cmd.name
294
345
  when "PING"
295
- _, context = cmd.ping_ttl_and_context
346
+ ttl, context = cmd.ping_ttl_and_context
347
+ note_peer_ttl(ttl)
296
348
  send_command(Codec::Command.pong(context: context))
297
349
  next
298
350
  when "PONG"
@@ -309,6 +361,27 @@ module Protocol
309
361
  end
310
362
 
311
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
382
+ end
383
+
384
+
312
385
  # Records that a frame was received (for heartbeat expiry tracking).
313
386
  #
314
387
  # @return [void]
@@ -331,13 +404,66 @@ module Protocol
331
404
  #
332
405
  # @return [void]
333
406
  def close
334
- @io.close
335
- 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
336
421
  # already closed
337
422
  end
338
423
 
424
+
425
+ # @return [Boolean] whether a frame write is in progress
426
+ def writing?
427
+ @mutex.locked?
428
+ end
429
+
339
430
  private
340
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
+
341
467
  # Defers task cancellation around a block of wire writes so the
342
468
  # peer never sees a half-written frame or partial multipart
343
469
  # message. Without this, an +Async::Cancel+ arriving between
@@ -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
@@ -257,7 +290,7 @@ module Protocol
257
290
  io.flush
258
291
 
259
292
  # --- Read WELCOME ---
260
- welcome_frame = Codec::Frame.read_from(io)
293
+ welcome_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
261
294
  raise Error, "expected command frame" unless welcome_frame.command?
262
295
  welcome_cmd = Codec::Command.from_body(welcome_frame.body).raise_if_error!
263
296
  raise Error, "expected WELCOME, got #{welcome_cmd.name}" unless welcome_cmd.name == "WELCOME"
@@ -275,7 +308,7 @@ module Protocol
275
308
  raise Error, "WELCOME decryption failed"
276
309
  end
277
310
 
278
- 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")
279
312
  cookie = w_plaintext.byteslice(32, 96)
280
313
 
281
314
  session = @crypto::Box.new(sn_public, cn_secret)
@@ -309,7 +342,7 @@ module Protocol
309
342
  io.flush
310
343
 
311
344
  # --- Read READY ---
312
- ready_frame = Codec::Frame.read_from(io)
345
+ ready_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
313
346
  raise Error, "expected command frame" unless ready_frame.command?
314
347
  ready_cmd = Codec::Command.from_body(ready_frame.body).raise_if_error!
315
348
  raise Error, "expected READY, got #{ready_cmd.name}" unless ready_cmd.name == "READY"
@@ -363,7 +396,7 @@ module Protocol
363
396
 
364
397
 
365
398
  # --- Read HELLO ---
366
- hello_frame = Codec::Frame.read_from(io)
399
+ hello_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
367
400
  raise Error, "expected command frame" unless hello_frame.command?
368
401
  hello_cmd = Codec::Command.from_body(hello_frame.body).raise_if_error!
369
402
  raise Error, "expected HELLO, got #{hello_cmd.name}" unless hello_cmd.name == "HELLO"
@@ -371,7 +404,7 @@ module Protocol
371
404
  hdata = hello_cmd.data
372
405
  raise Error, "HELLO wrong size (#{hdata.bytesize})" unless hdata.bytesize == 194
373
406
 
374
- cn_public = @crypto::PublicKey.new(hdata.byteslice(74, 32))
407
+ cn_public = peer_public_key(hdata.byteslice(74, 32), "client short-term key")
375
408
  h_short_nonce = hdata.byteslice(106, 8)
376
409
  h_signature = hdata.byteslice(114, 80)
377
410
 
@@ -409,7 +442,7 @@ module Protocol
409
442
  io.flush
410
443
 
411
444
  # --- Read INITIATE ---
412
- init_frame = Codec::Frame.read_from(io)
445
+ init_frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
413
446
  raise Error, "expected command frame" unless init_frame.command?
414
447
  init_cmd = Codec::Command.from_body(init_frame.body).raise_if_error!
415
448
  raise Error, "expected INITIATE, got #{init_cmd.name}" unless init_cmd.name == "INITIATE"
@@ -444,7 +477,7 @@ module Protocol
444
477
 
445
478
  raise Error, "INITIATE plaintext too short" if i_plaintext.bytesize < 32 + 16 + 80
446
479
 
447
- client_permanent = @crypto::PublicKey.new(i_plaintext.byteslice(0, 32))
480
+ client_permanent = peer_public_key(i_plaintext.byteslice(0, 32), "client permanent key")
448
481
  vouch_short_nonce = i_plaintext.byteslice(32, 16)
449
482
  vouch_ciphertext = i_plaintext.byteslice(48, 80)
450
483
  metadata_bytes = i_plaintext.byteslice(128..) || "".b
@@ -558,6 +591,14 @@ module Protocol
558
591
  end
559
592
 
560
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
+
561
602
  def validate_key!(key, name)
562
603
  raise ArgumentError, "#{name} is required" if key.nil?
563
604
  raise ArgumentError, "#{name} must be 32 bytes (got #{key.b.bytesize})" unless key.b.bytesize == 32
@@ -43,7 +43,7 @@ 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
@@ -163,7 +163,7 @@ module Protocol
163
163
 
164
164
 
165
165
  def read_command(io)
166
- frame = Codec::Frame.read_from(io)
166
+ frame = Codec::Frame.read_from(io, max_message_size: Codec::Frame::HANDSHAKE_MAX_SIZE)
167
167
  raise Error, "expected command frame, got data frame" unless frame.command?
168
168
 
169
169
  Codec::Command.from_body(frame.body).raise_if_error!
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Protocol
4
4
  module ZMTP
5
- VERSION = "0.10.5"
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.5
4
+ version: 0.11.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrik Wenger