Class: TTTLS13::Client

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/tttls1.3/client.rb

Overview

rubocop: disable Metrics/ClassLength

Constant Summary collapse

HpkeSymmetricCipherSuit =
ECHConfig::ECHConfigContents::HpkeKeyConfig::HpkeSymmetricCipherSuite

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logging

#logger, logger

Constructor Details

#initialize(socket, hostname, **settings) ⇒ Client

Returns a new instance of Client.

Parameters:

  • socket (Socket)
  • hostname (String)
  • settings (Hash)

Raises:



101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/tttls1.3/client.rb', line 101

def initialize(socket, hostname, **settings)
  @connection = Connection.new(socket, :client)
  @hostname = hostname
  @settings = DEFAULT_CLIENT_SETTINGS.merge(settings)
  logger.level = @settings[:loglevel]

  @early_data = ''
  @succeed_early_data = false
  @retry_configs = []
  @rejected_ech = false
  raise Error::ConfigError unless valid_settings?
end

Instance Attribute Details

#transcriptObject (readonly)

Returns the value of attribute transcript.



96
97
98
# File 'lib/tttls1.3/client.rb', line 96

def transcript
  @transcript
end

Class Method Details

.softfail_check_certificate_status(res, cert, chain) ⇒ Boolean

Examples:

m = Client.method(:softfail_check_certificate_status)
Client.new(
  socket,
  hostname,
  check_certificate_status: true,
  process_certificate_status: m
)

Parameters:

  • res (OpenSSL::OCSP::Response)
  • cert (OpenSSL::X509::Certificate)
  • chain (Array of OpenSSL::X509::Certificate, nil)

Returns:

  • (Boolean)


621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
# File 'lib/tttls1.3/client.rb', line 621

def self.softfail_check_certificate_status(res, cert, chain)
  ocsp_response = res
  cid = OpenSSL::OCSP::CertificateId.new(cert, chain.first)

  # When NOT received OCSPResponse in TLS handshake, this method will
  # send OCSPRequest. If ocsp_uri is NOT presented in Certificate, return
  # true. Also, if it sends OCSPRequest and does NOT receive a HTTPresponse
  # within 2 seconds, return true.
  if ocsp_response.nil?
    uri = cert.ocsp_uris&.find { |u| URI::DEFAULT_PARSER.make_regexp =~ u }
    return true if uri.nil?

    begin
      # send OCSP::Request
      ocsp_request = gen_ocsp_request(cid)
      Timeout.timeout(2) do
        ocsp_response = send_ocsp_request(ocsp_request, uri)
      end

      # check nonce of OCSP::Response
      check_nonce = ocsp_request.check_nonce(ocsp_response.basic)
      return true unless [-1, 1].include?(check_nonce)
    rescue StandardError
      return true
    end
  end
  return true \
    if ocsp_response.status != OpenSSL::OCSP::RESPONSE_STATUS_SUCCESSFUL

  status = ocsp_response.basic.status.find { |s| s.first.cmp(cid) }
  status[1] != OpenSSL::OCSP::V_CERTSTATUS_REVOKED
end

Instance Method Details

#closeObject



545
546
547
# File 'lib/tttls1.3/client.rb', line 545

def close
  @connection.close
end

#connectObject

START <—-+

          Send ClientHello |        | Recv HelloRetryRequest
     [K_send = early data] |        |
                           v        |
      /                 WAIT_SH ----+
      |                    | Recv ServerHello
      |                    | K_recv = handshake
  Can |                    V
 send |                 WAIT_EE
early |                    | Recv EncryptedExtensions
 data |           +--------+--------+
      |     Using |                 | Using certificate
      |       PSK |                 v
      |           |            WAIT_CERT_CR
      |           |        Recv |       | Recv CertificateRequest
      |           | Certificate |       v
      |           |             |    WAIT_CERT
      |           |             |       | Recv Certificate
      |           |             v       v
      |           |              WAIT_CV
      |           |                 | Recv CertificateVerify
      |           +> WAIT_FINISHED <+
      |                  | Recv Finished
      \                  | [Send EndOfEarlyData]
                         | K_send = handshake
                         | [Send Certificate [+ CertificateVerify]]

Can send | Send Finished app data –> | K_send = K_recv = application after here v

CONNECTED

datatracker.ietf.org/doc/html/rfc8446#appendix-A.1

rubocop: disable Metrics/AbcSize rubocop: disable Metrics/BlockLength rubocop: disable Metrics/CyclomaticComplexity rubocop: disable Metrics/MethodLength rubocop: disable Metrics/PerceivedComplexity



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/tttls1.3/client.rb', line 152

def connect
  @transcript = Transcript.new
  key_schedule = nil # TTTLS13::KeySchedule
  psk = nil
  if use_psk?
    psk = gen_psk_from_nst(
      @settings[:resumption_secret],
      @settings[:ticket_nonce],
      CipherSuite.digest(@settings[:psk_cipher_suite])
    )
    key_schedule = KeySchedule.new(
      psk:,
      shared_secret: nil,
      cipher_suite: @settings[:psk_cipher_suite],
      transcript: @transcript
    )
  end

  shared_secret = nil # TTTLS13::SharedSecret
  hs_wcipher = nil # TTTLS13::Cryptograph::$Object
  hs_rcipher = nil # TTTLS13::Cryptograph::$Object
  e_wcipher = nil # TTTLS13::Cryptograph::$Object
  sslkeylogfile = nil # TTTLS13::SslKeyLogFile::Writer
  ch1_outer = nil # TTTLS13::Message::ClientHello for rejected ECH
  ch_outer = nil # TTTLS13::Message::ClientHello for rejected ECH
  ech_state = nil # TTTLS13::EchState for ECH with HRR
  unless @settings[:sslkeylogfile].nil?
    begin
      sslkeylogfile = SslKeyLogFile::Writer.new(@settings[:sslkeylogfile])
    rescue SystemCallError => e
      msg = "\"#{@settings[:sslkeylogfile]}\" file can NOT open: #{e}"
      logger.warn(msg)
    end
  end

  @connection.state = ClientState::START
  loop do
    case @connection.state
    when ClientState::START
      logger.debug('ClientState::START')

      extensions, shared_secret = gen_ch_extensions
      binder_key = (use_psk? ? key_schedule.binder_key_res : nil)
      ch, inner, ech_state, ech_secret = send_client_hello(extensions, binder_key)
      unless ech_secret.nil?
        sslkeylogfile&.write_ech_secret(ch.random, ech_secret)
        sslkeylogfile&.write_ech_config(ch.random, @settings[:ech_config].encode)
      end

      ch_outer = ch
      # use ClientHelloInner messages for the transcript hash
      ch = inner.nil? ? ch : inner
      @transcript[CH] = [ch, ch.serialize]
      @connection.send_ccs if @settings[:compatibility_mode]
      if use_early_data?
        e_wcipher = Endpoint.gen_cipher(
          @settings[:psk_cipher_suite],
          key_schedule.early_data_write_key,
          key_schedule.early_data_write_iv
        )
        sslkeylogfile&.write_client_early_traffic_secret(
          @transcript[CH].first.random,
          key_schedule.client_early_traffic_secret
        )
        send_early_data(e_wcipher)
      end

      @connection.state = ClientState::WAIT_SH
    when ClientState::WAIT_SH
      logger.debug('ClientState::WAIT_SH')

      sh, = @transcript[SH] = recv_server_hello

      # downgrade protection
      if !sh.negotiated_tls_1_3? && sh.downgraded?
        @connection.terminate(:illegal_parameter)
      # support only TLS 1.3
      elsif !sh.negotiated_tls_1_3?
        @connection.terminate(:protocol_version)
      end

      # validate parameters
      @connection.terminate(:illegal_parameter) \
        unless sh.appearable_extensions?
      @connection.terminate(:illegal_parameter) \
        unless sh.legacy_compression_method == "\x00"

      # validate sh using ch
      ch, = @transcript[CH]
      @connection.terminate(:illegal_parameter) \
        unless sh.legacy_version == ch.legacy_version
      @connection.terminate(:illegal_parameter) \
        unless sh.legacy_session_id_echo == ch.legacy_session_id
      @connection.terminate(:illegal_parameter) \
        unless ch.cipher_suites.include?(sh.cipher_suite)
      @connection.terminate(:unsupported_extension) \
        unless (sh.extensions.keys - ch.extensions.keys).empty?

      # validate sh using hrr
      if @transcript.include?(HRR)
        hrr, = @transcript[HRR]
        @connection.terminate(:illegal_parameter) \
          unless sh.cipher_suite == hrr.cipher_suite

        sh_sv = sh.extensions[Message::ExtensionType::SUPPORTED_VERSIONS]
        hrr_sv = hrr.extensions[Message::ExtensionType::SUPPORTED_VERSIONS]
        @connection.terminate(:illegal_parameter) \
          unless sh_sv.versions == hrr_sv.versions
      end

      # handling HRR
      if sh.hrr?
        @connection.terminate(:unexpected_message) \
          if @transcript.include?(HRR)

        ch1, = @transcript[CH1] = @transcript.delete(CH)
        hrr, = @transcript[HRR] = @transcript.delete(SH)
        ch1_outer = ch_outer
        ch_outer = nil

        # validate cookie
        diff_sets = sh.extensions.keys - ch1.extensions.keys
        @connection.terminate(:unsupported_extension) \
          unless (diff_sets - [Message::ExtensionType::COOKIE]).empty?

        # validate key_share
        # TODO: validate pre_shared_key
        ngl = ch1.extensions[Message::ExtensionType::SUPPORTED_GROUPS]
                 .named_group_list
        kse = ch1.extensions[Message::ExtensionType::KEY_SHARE]
                 .key_share_entry
        group = hrr.extensions[Message::ExtensionType::KEY_SHARE]
                   .key_share_entry.first.group
        @connection.terminate(:illegal_parameter) \
          unless ngl.include?(group) && !kse.map(&:group).include?(group)

        # send new client_hello
        extensions, shared_secret = gen_newch_extensions(ch1, hrr)
        binder_key = (use_psk? ? key_schedule.binder_key_res : nil)
        ch, inner = send_new_client_hello(
          ch1,
          hrr,
          extensions,
          binder_key,
          ech_state
        )
        # use ClientHelloInner messages for the transcript hash
        ch_outer = ch
        ch = inner.nil? ? ch : inner
        @transcript[CH] = [ch, ch.serialize]

        @connection.state = ClientState::WAIT_SH
        next
      end

      # generate shared secret
      if sh.extensions.include?(Message::ExtensionType::PRE_SHARED_KEY)
      # TODO: validate pre_shared_key
      else
        psk = nil
      end
      ch_ks = ch.extensions[Message::ExtensionType::KEY_SHARE]
                .key_share_entry.map(&:group)
      sh_ks = sh.extensions[Message::ExtensionType::KEY_SHARE]
                .key_share_entry.first.group
      @connection.terminate(:illegal_parameter) unless ch_ks.include?(sh_ks)

      kse = sh.extensions[Message::ExtensionType::KEY_SHARE]
              .key_share_entry
              .first
      ke = kse.key_exchange
      @named_group = kse.group
      @cipher_suite = sh.cipher_suite
      key_schedule = KeySchedule.new(
        psk:,
        shared_secret: shared_secret.build(@named_group, ke),
        cipher_suite: @cipher_suite,
        transcript: @transcript
      )

      # rejected ECH
      # It can compute (hrr_)accept_ech until client selects the
      # cipher_suite.
      if !sh.hrr? && use_ech?
        if !@transcript.include?(HRR) && !key_schedule.accept_ech?
          # 1sh SH
          @transcript[CH] = [ch_outer, ch_outer.serialize]
          @rejected_ech = true
        elsif @transcript.include?(HRR) &&
              key_schedule.hrr_accept_ech? != key_schedule.accept_ech?
          # 2nd SH
          @connection.terminate(:illegal_parameter)
        elsif @transcript.include?(HRR) && !key_schedule.hrr_accept_ech?
          # 2nd SH
          @transcript[CH1] = [ch1_outer, ch1_outer.serialize]
          @transcript[CH] = [ch_outer, ch_outer.serialize]
          @rejected_ech = true
        end
      end

      @connection.alert_wcipher = hs_wcipher = Endpoint.gen_cipher(
        @cipher_suite,
        key_schedule.client_handshake_write_key,
        key_schedule.client_handshake_write_iv
      )
      sslkeylogfile&.write_client_handshake_traffic_secret(
        @transcript[CH].first.random,
        key_schedule.client_handshake_traffic_secret
      )
      hs_rcipher = Endpoint.gen_cipher(
        @cipher_suite,
        key_schedule.server_handshake_write_key,
        key_schedule.server_handshake_write_iv
      )
      sslkeylogfile&.write_server_handshake_traffic_secret(
        @transcript[CH].first.random,
        key_schedule.server_handshake_traffic_secret
      )
      @connection.state = ClientState::WAIT_EE
    when ClientState::WAIT_EE
      logger.debug('ClientState::WAIT_EE')

      ee, = @transcript[EE] = recv_encrypted_extensions(hs_rcipher)
      @connection.terminate(:illegal_parameter) \
        unless ee.appearable_extensions?

      ch, = @transcript[CH]
      @connection.terminate(:unsupported_extension) \
        unless (ee.extensions.keys - ch.extensions.keys).empty?

      rsl = ee.extensions[Message::ExtensionType::RECORD_SIZE_LIMIT]
      @recv_record_size = rsl.record_size_limit unless rsl.nil?
      @succeed_early_data = true \
        if ee.extensions.include?(Message::ExtensionType::EARLY_DATA)
      @alpn = ee.extensions[
        Message::ExtensionType::APPLICATION_LAYER_PROTOCOL_NEGOTIATION
      ]&.protocol_name_list&.first
      @retry_configs = ee.extensions[
        Message::ExtensionType::ENCRYPTED_CLIENT_HELLO
      ]&.retry_configs
      @connection.terminate(:unsupported_extension) \
        if !rejected_ech? && !@retry_configs.nil?

      @connection.state = ClientState::WAIT_CERT_CR
      @connection.state = ClientState::WAIT_FINISHED unless psk.nil?
    when ClientState::WAIT_CERT_CR
      logger.debug('ClientState::WAIT_CERT_CR')

      message, orig_msg = @connection.recv_message(
        receivable_ccs: true,
        cipher: hs_rcipher
      )
      case message.msg_type
      when Message::HandshakeType::CERTIFICATE,
           Message::HandshakeType::COMPRESSED_CERTIFICATE
        ct, = @transcript[CT] = [message, orig_msg]
        @connection.terminate(:bad_certificate) \
          if ct.is_a?(Message::CompressedCertificate) &&
             !@settings[:compress_certificate_algorithms]
             .include?(ct.algorithm)

        ct = ct.certificate_message \
          if ct.is_a?(Message::CompressedCertificate)
        alert = check_invalid_certificate(ct, @transcript[CH].first)
        @connection.terminate(alert) unless alert.nil?

        @connection.state = ClientState::WAIT_CV
      when Message::HandshakeType::CERTIFICATE_REQUEST
        @transcript[CR] = [message, orig_msg]
        # TODO: client authentication
        @connection.state = ClientState::WAIT_CERT
      else
        @connection.terminate(:unexpected_message)
      end
    when ClientState::WAIT_CERT
      logger.debug('ClientState::WAIT_CERT')

      ct, = @transcript[CT] = recv_certificate(hs_rcipher)
      if ct.is_a?(Message::CompressedCertificate) &&
         !@settings[:compress_certificate_algorithms].include?(ct.algorithm)
        @connection.terminate(:bad_certificate)
      elsif ct.is_a?(Message::CompressedCertificate)
        ct = ct.certificate_message
      end

      alert = check_invalid_certificate(ct, @transcript[CH].first)
      @connection.terminate(alert) unless alert.nil?

      @connection.state = ClientState::WAIT_CV
    when ClientState::WAIT_CV
      logger.debug('ClientState::WAIT_CV')

      cv, = @transcript[CV] = recv_certificate_verify(hs_rcipher)
      digest = CipherSuite.digest(@cipher_suite)
      hash = @transcript.hash(digest, CT)
      ct, = @transcript[CT]
      ct = ct.certificate_message \
        if ct.is_a?(Message::CompressedCertificate)
      @connection.terminate(:decrypt_error) \
        unless verified_certificate_verify?(ct, cv, hash)

      @signature_scheme = cv.signature_scheme
      @connection.state = ClientState::WAIT_FINISHED
    when ClientState::WAIT_FINISHED
      logger.debug('ClientState::WAIT_FINISHED')

      sf, = @transcript[SF] = recv_finished(hs_rcipher)
      digest = CipherSuite.digest(@cipher_suite)
      @connection.terminate(:decrypt_error) \
        unless Endpoint.verified_finished?(
          finished: sf,
          digest:,
          finished_key: key_schedule.server_finished_key,
          hash: @transcript.hash(digest, CV)
        )

      if use_early_data? && succeed_early_data?
        eoed = send_eoed(e_wcipher)
        @transcript[EOED] = [eoed, eoed.serialize]
      end
      # TODO: Send Certificate [+ CertificateVerify]
      signature = Endpoint.sign_finished(
        digest:,
        finished_key: key_schedule.client_finished_key,
        hash: @transcript.hash(digest, EOED)
      )
      cf = send_finished(signature, hs_wcipher)
      @transcript[CF] = [cf, cf.serialize]
      @connection.ap_wcipher = Endpoint.gen_cipher(
        @cipher_suite,
        key_schedule.client_application_write_key,
        key_schedule.client_application_write_iv
      )
      @connection.alert_wcipher = @connection.ap_wcipher
      sslkeylogfile&.write_client_traffic_secret_0(
        @transcript[CH].first.random,
        key_schedule.client_application_traffic_secret
      )
      @connection.ap_rcipher = Endpoint.gen_cipher(
        @cipher_suite,
        key_schedule.server_application_write_key,
        key_schedule.server_application_write_iv
      )
      sslkeylogfile&.write_server_traffic_secret_0(
        @transcript[CH].first.random,
        key_schedule.server_application_traffic_secret
      )
      @exporter_secret = key_schedule.exporter_secret
      @resumption_secret = key_schedule.resumption_secret
      @connection.state = ClientState::CONNECTED
    when ClientState::CONNECTED
      logger.debug('ClientState::CONNECTED')

      @connection.send_alert(:ech_required) \
        if use_ech? && (!@retry_configs.nil? && !@retry_configs.empty?)
      break
    end
  end
  sslkeylogfile&.close
end

#early_data(binary) ⇒ Object

Parameters:

  • binary (String)

Raises:



584
585
586
587
588
# File 'lib/tttls1.3/client.rb', line 584

def early_data(binary)
  raise Error::ConfigError unless @connection.state == INITIAL && use_psk?

  @early_data = binary
end

#eof?Boolean

return [Boolean]

Returns:

  • (Boolean)


541
542
543
# File 'lib/tttls1.3/client.rb', line 541

def eof?
  @connection.eof?
end

#exporter(label, context, key_length) ⇒ String?

Parameters:

  • label (String)
  • context (String)
  • key_length (Integer)

Returns:

  • (String, nil)


574
575
576
577
578
579
# File 'lib/tttls1.3/client.rb', line 574

def exporter(label, context, key_length)
  return nil if @exporter_secret.nil? || @cipher_suite.nil?

  digest = CipherSuite.digest(@cipher_suite)
  Endpoint.exporter(@exporter_secret, digest, label, context, key_length)
end

#negotiated_alpnString

Returns:

  • (String)


565
566
567
# File 'lib/tttls1.3/client.rb', line 565

def negotiated_alpn
  @alpn
end

#negotiated_cipher_suiteTTTLS13::CipherSuite?

Returns:



550
551
552
# File 'lib/tttls1.3/client.rb', line 550

def negotiated_cipher_suite
  @cipher_suite
end

#negotiated_named_groupTTTLS13::NamedGroup?

Returns:



555
556
557
# File 'lib/tttls1.3/client.rb', line 555

def negotiated_named_group
  @named_group
end

#negotiated_signature_schemeTTTLS13::SignatureScheme?

Returns:



560
561
562
# File 'lib/tttls1.3/client.rb', line 560

def negotiated_signature_scheme
  @signature_scheme
end

#readString

Returns:

  • (String)

Raises:



521
522
523
524
# File 'lib/tttls1.3/client.rb', line 521

def read
  nst_process = method(:process_new_session_ticket)
  @connection.read(nst_process)
end

#rejected_ech?Boolean

Returns:

  • (Boolean)


603
604
605
# File 'lib/tttls1.3/client.rb', line 603

def rejected_ech?
  @rejected_ech
end

#retry_configsArray of ECHConfig

Returns:

  • (Array of ECHConfig)


591
592
593
594
595
# File 'lib/tttls1.3/client.rb', line 591

def retry_configs
  @retry_configs.filter do |c|
    SUPPORTED_ECHCONFIG_VERSIONS.include?(c.version)
  end
end

#succeed_early_data?Boolean

Returns:

  • (Boolean)


598
599
600
# File 'lib/tttls1.3/client.rb', line 598

def succeed_early_data?
  @succeed_early_data
end

#write(binary) ⇒ Object

Parameters:

  • binary (String)


527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/tttls1.3/client.rb', line 527

def write(binary)
  # the client can regard ECH as securely disabled by the server, and it
  # SHOULD retry the handshake with a new transport connection and ECH
  # disabled.
  if !@retry_configs.nil? && !@retry_configs.empty?
    msg = 'SHOULD retry the handshake with a new transport connection'
    logger.warn(msg)
    return
  end

  @connection.write(binary)
end