Class: TTTLS13::Client

Inherits:
Connection show all
Defined in:
lib/tttls1.3/client.rb

Overview

rubocop: disable Metrics/ClassLength

Defined Under Namespace

Classes: EchState

Constant Summary collapse

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Connection

#close, #eof?, #exporter, gen_ocsp_request, #negotiated_alpn, #negotiated_cipher_suite, #negotiated_named_group, #negotiated_signature_scheme, #read, send_ocsp_request

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:



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/tttls1.3/client.rb', line 98

def initialize(socket, hostname, **settings)
  super(socket)

  @endpoint = :client
  @hostname = hostname
  @settings = DEFAULT_CLIENT_SETTINGS.merge(settings)
  # NOTE: backward compatibility
  if @settings[:resumption_secret].nil? &&
     !@settings[:resumption_master_secret].nil?
    @settings[:resumption_secret] =
      @settings.delete(:resumption_master_secret) \
  end
  raise Error::ConfigError if @settings[:resumption_secret] !=
                              @settings[:resumption_master_secret]

  logger.level = @settings[:loglevel]

  @early_data = ''
  @succeed_early_data = false
  @retry_configs = []
  @rejected_ech = false
  raise Error::ConfigError unless valid_settings?
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)


574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
# File 'lib/tttls1.3/client.rb', line 574

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

#connectObject

NOTE:

                         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



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
512
513
# File 'lib/tttls1.3/client.rb', line 161

def connect
  transcript = Transcript.new
  key_schedule = nil # TTTLS13::KeySchedule
  psk = nil
  priv_keys = {} # Hash of NamedGroup => OpenSSL::PKey::$Object
  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: psk,
      shared_secret: nil,
      cipher_suite: @settings[:psk_cipher_suite],
      transcript: transcript
    )
  end

  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::Client::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

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

      extensions, priv_keys = gen_ch_extensions
      binder_key = (use_psk? ? key_schedule.binder_key_res : nil)
      ch, inner, ech_state = send_client_hello(extensions, binder_key)
      ch_outer = ch
      # use ClientHelloInner messages for the transcript hash
      ch = inner.nil? ? ch : inner
      transcript[CH] = [ch, ch.serialize]
      send_ccs if @settings[:compatibility_mode]
      if use_early_data?
        e_wcipher = 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

      @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?
        terminate(:illegal_parameter)
      # support only TLS 1.3
      elsif !sh.negotiated_tls_1_3?
        terminate(:protocol_version)
      end

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

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

      # validate sh using hrr
      if transcript.include?(HRR)
        hrr, = transcript[HRR]
        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]
        terminate(:illegal_parameter) \
          unless sh_sv.versions == hrr_sv.versions
      end

      # handling HRR
      if sh.hrr?
        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
        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
        terminate(:illegal_parameter) \
          unless ngl.include?(group) && !kse.map(&:group).include?(group)

        # send new client_hello
        extensions, pk = gen_newch_extensions(ch1, hrr)
        priv_keys = pk.merge(priv_keys)
        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]

        @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
      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
      priv_key = priv_keys[@named_group]
      shared_secret = gen_shared_secret(ke, priv_key, @named_group)
      @cipher_suite = sh.cipher_suite
      key_schedule = KeySchedule.new(
        psk: psk,
        shared_secret: shared_secret,
        cipher_suite: @cipher_suite,
        transcript: transcript
      )

      # rejected ECH
      # NOTE: 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
          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

      @alert_wcipher = hs_wcipher = 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 = 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
      )
      @state = ClientState::WAIT_EE
    when ClientState::WAIT_EE
      logger.debug('ClientState::WAIT_EE')

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

      ch, = transcript[CH]
      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
      terminate(:unsupported_extension) \
        if !rejected_ech? && !@retry_configs.nil?

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

      message, orig_msg = 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]
        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)
        terminate(alert) unless alert.nil?

        @state = ClientState::WAIT_CV
      when Message::HandshakeType::CERTIFICATE_REQUEST
        transcript[CR] = [message, orig_msg]
        # TODO: client authentication
        @state = ClientState::WAIT_CERT
      else
        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)
        terminate(:bad_certificate)
      elsif ct.is_a?(Message::CompressedCertificate)
        ct = ct.certificate_message
      end

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

      @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)
      terminate(:decrypt_error) \
        unless verified_certificate_verify?(ct, cv, hash)

      @signature_scheme = cv.signature_scheme
      @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)
      terminate(:decrypt_error) unless verified_finished?(
        finished: sf,
        digest: 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 = sign_finished(
        digest: digest,
        finished_key: key_schedule.client_finished_key,
        hash: transcript.hash(digest, EOED)
      )
      cf = send_finished(signature, hs_wcipher)
      transcript[CF] = [cf, cf.serialize]
      @alert_wcipher = @ap_wcipher = gen_cipher(
        @cipher_suite,
        key_schedule.client_application_write_key,
        key_schedule.client_application_write_iv
      )
      sslkeylogfile&.write_client_traffic_secret_0(
        transcript[CH].first.random,
        key_schedule.client_application_traffic_secret
      )
      @ap_rcipher = 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
      @state = ClientState::CONNECTED
    when ClientState::CONNECTED
      logger.debug('ClientState::CONNECTED')

      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:



537
538
539
540
541
# File 'lib/tttls1.3/client.rb', line 537

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

  @early_data = binary
end

#rejected_ech?Boolean

Returns:

  • (Boolean)


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

def rejected_ech?
  @rejected_ech
end

#retry_configsArray of ECHConfig

Returns:

  • (Array of ECHConfig)


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

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

#succeed_early_data?Boolean

Returns:

  • (Boolean)


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

def succeed_early_data?
  @succeed_early_data
end

#write(binary) ⇒ Object

Parameters:

  • binary (String)


521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/tttls1.3/client.rb', line 521

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

  super(binary)
end