Class: Riemann::Tools::TLSCheck

Inherits:
Object
  • Object
show all
Includes:
Riemann::Tools
Defined in:
lib/riemann/tools/tls_check.rb

Defined Under Namespace

Classes: TLSCheckResult, UnexpectedMessage

Constant Summary collapse

OPENSSL_ERROR_STRINGS =

Ruby OpenSSL does not expose ERR_error_string(3), and depending on the version of OpenSSL the available values change. Build a local list of mappings from include/openssl/x509_vfy.h.in and crypto/x509/x509_txt.c for lookups.

[
  'ok',
  'unspecified certificate verification error',
  'unable to get issuer certificate',
  'unable to get certificate CRL',
  "unable to decrypt certificate's signature",
  "unable to decrypt CRL's signature",
  'unable to decode issuer public key',
  'certificate signature failure',
  'CRL signature failure',
  'certificate is not yet valid',
  'certificate has expired',
  'CRL is not yet valid',
  'CRL has expired',
  "format error in certificate's notBefore field",
  "format error in certificate's notAfter field",
  "format error in CRL's lastUpdate field",
  "format error in CRL's nextUpdate field",
  'out of memory',
  'self-signed certificate',
  'self-signed certificate in certificate chain',
  'unable to get local issuer certificate',
  'unable to verify the first certificate',
  'certificate chain too long',
  'certificate revoked',
  "issuer certificate doesn't have a public key",
  'path length constraint exceeded',
  'unsuitable certificate purpose',
  'certificate not trusted',
  'certificate rejected',
].freeze

Constants included from Riemann::Tools

VERSION

Instance Attribute Summary

Attributes included from Riemann::Tools

#argv

Instance Method Summary collapse

Methods included from Riemann::Tools

#attributes, #endpoint_name, included, #options, #report, #riemann, #run

Constructor Details

#initializeTLSCheck

Returns a new instance of TLSCheck.



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
# File 'lib/riemann/tools/tls_check.rb', line 241

def initialize
  super

  opts[:connect_timeout] ||= [10, opts[:interval] / 2].min

  @resolve_queue = Queue.new
  @work_queue = Queue.new

  opts[:resolvers].times do
    Thread.new do
      loop do
        uri = @resolve_queue.pop
        host = uri.host

        addresses = if host == 'localhost'
                      Socket.ip_address_list.select { |address| address.ipv6_loopback? || address.ipv4_loopback? }.map(&:ip_address)
                    else
                      Resolv::DNS.new.getaddresses(host)
                    end
        if addresses.empty?
          host = host[1...-1] if host[0] == '[' && host[-1] == ']'
          begin
            addresses << IPAddr.new(host)
          rescue IPAddr::InvalidAddressError
            # Ignore
          end
        end

        @work_queue.push([uri, addresses])
      end
    end
  end

  opts[:workers].times do
    Thread.new do
      loop do
        uri, addresses = @work_queue.pop
        test_uri_addresses(uri, addresses)
      end
    end
  end
end

Instance Method Details

#imap_tls_socket(uri, address) ⇒ Object



524
525
526
527
528
529
530
531
532
533
# File 'lib/riemann/tools/tls_check.rb', line 524

def imap_tls_socket(uri, address)
  socket = tcp_socket(address, uri.port)
  read_socket_lines_until_prefix_matched(socket, '* OK')
  socket.send(". CAPABILITY\r\n", 0)
  read_socket_lines_until_prefix_matched(socket, '. OK', also_accept_prefixes: ['* CAPABILITY'])
  socket.send(". STARTTLS\r\n", 0)
  read_socket_lines_until_prefix_matched(socket, '. OK')

  tls_handshake(socket, uri.host)
end

#ldap_tls_socket(uri, address) ⇒ Object



535
536
537
538
539
540
541
542
543
544
# File 'lib/riemann/tools/tls_check.rb', line 535

def ldap_tls_socket(uri, address)
  socket = tcp_socket(address, uri.port)
  socket.write(['301d02010177188016312e332e362e312e342e312e313436362e3230303337'].pack('H*'))
  expected_res = ['300c02010178070a010004000400'].pack('H*')
  res = socket.read(expected_res.length)

  return nil unless res == expected_res

  tls_handshake(socket, uri.host)
end

#my_hostnameObject



508
509
510
511
512
# File 'lib/riemann/tools/tls_check.rb', line 508

def my_hostname
  Addrinfo.tcp(Socket.gethostname, 8023).getnameinfo.first
rescue SocketError
  Socket.gethostname
end

#mysql_tls_socket(uri, address) ⇒ Object



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/riemann/tools/tls_check.rb', line 473

def mysql_tls_socket(uri, address)
  socket = tcp_socket(address, uri.port)
  length = "#{socket.read(3)}\0".unpack1('L*')
  _sequence = socket.read(1)
  body = socket.read(length)
  initial_handshake_packet = body.unpack('cZ*La8aScSS')

  capabilities = initial_handshake_packet[5] | (initial_handshake_packet[8] << 16)

  ssl_flag = 1 << 11
  raise 'No TLS support' if capabilities.nobits?(ssl_flag)

  socket.write(['2000000185ae7f0000000001210000000000000000000000000000000000000000000000'].pack('H*'))
  tls_handshake(socket, uri.host)
end

#not_after_state(tls_check_result) ⇒ Object

not_before not_after

|<----------------------------->|         validity_duration
                    |<--------->|         renewal_duration
                    | ⅓ | ⅓ | ⅓ |

…oooooooooooooooooooooooooooooooowwwwcccccccccc… not_after_state

time --->>>>


442
443
444
445
446
447
448
449
450
# File 'lib/riemann/tools/tls_check.rb', line 442

def not_after_state(tls_check_result)
  if tls_check_result.expired_or_expire_soon?
    'critical'
  elsif tls_check_result.expire_soonish?
    'warning'
  else
    'ok'
  end
end

#not_before_state(tls_check_result) ⇒ Object

not_before not_after

|<----------------------------->|         validity_duration

…ccccccccoooooooooooooooooooooooooooooooooooooo… not_before_state

time --->>>>


431
432
433
# File 'lib/riemann/tools/tls_check.rb', line 431

def not_before_state(tls_check_result)
  tls_check_result.not_valid_yet? ? 'critical' : 'ok'
end

#postgres_tls_socket(uri, address) ⇒ Object



489
490
491
492
493
494
495
# File 'lib/riemann/tools/tls_check.rb', line 489

def postgres_tls_socket(uri, address)
  socket = tcp_socket(address, uri.port)
  socket.write(['0000000804d2162f'].pack('H*'))
  raise 'Unexpected reply' unless socket.read(1) == 'S'

  tls_handshake(socket, uri.host)
end

#raw_tls_socket(uri, address) ⇒ Object



546
547
548
549
550
551
# File 'lib/riemann/tools/tls_check.rb', line 546

def raw_tls_socket(uri, address)
  raise "No default port for #{uri.scheme} scheme" unless uri.port

  socket = tcp_socket(address, uri.port)
  tls_handshake(socket, uri.host)
end

#read_socket_lines_until_prefix_matched(socket, prefix, also_accept_prefixes: []) ⇒ Object



514
515
516
517
518
519
520
521
522
# File 'lib/riemann/tools/tls_check.rb', line 514

def read_socket_lines_until_prefix_matched(socket, prefix, also_accept_prefixes: [])
  loop do
    line = socket.gets
    break if line.start_with?(prefix)
    next if also_accept_prefixes.map { |accepted_prefix| line.start_with?(accepted_prefix) }.any?

    raise UnexpectedMessage, line
  end
end

#report_availability(tls_check_result) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/riemann/tools/tls_check.rb', line 336

def report_availability(tls_check_result)
  if tls_check_result.exception
    report(
      service: "#{tls_endpoint_name(tls_check_result)} availability",
      state: 'critical',
      description: tls_check_result.exception.message,
    )
  else
    issues = []

    issues << 'Certificate is not valid yet' if tls_check_result.not_valid_yet?
    issues << 'Certificate has expired' if tls_check_result.expired?
    issues << 'Certificate identity could not be verified' unless tls_check_result.valid_identity?
    issues << 'Certificate is not trusted' unless tls_check_result.trusted?
    issues << 'Certificate OCSP verification failed' if tls_check_result.ocsp? && !tls_check_result.valid_ocsp?

    report(
      service: "#{tls_endpoint_name(tls_check_result)} availability",
      state: issues.empty? ? 'ok' : 'critical',
      description: issues.join("\n"),
    )
  end
end

#report_identity(tls_check_result) ⇒ Object



386
387
388
389
390
391
392
# File 'lib/riemann/tools/tls_check.rb', line 386

def report_identity(tls_check_result)
  report(
    service: "#{tls_endpoint_name(tls_check_result)} identity",
    state: tls_check_result.valid_identity? ? 'ok' : 'critical',
    description: "Valid for:\n#{tls_check_result.acceptable_identities.join("\n")}",
  )
end

#report_not_after(tls_check_result) ⇒ Object



368
369
370
371
372
373
374
375
# File 'lib/riemann/tools/tls_check.rb', line 368

def report_not_after(tls_check_result)
  report(
    service: "#{tls_endpoint_name(tls_check_result)} not after",
    state: not_after_state(tls_check_result),
    metric: tls_check_result.not_after_ago,
    description: tls_check_result.not_after_ago_in_words,
  )
end

#report_not_before(tls_check_result) ⇒ Object



377
378
379
380
381
382
383
384
# File 'lib/riemann/tools/tls_check.rb', line 377

def report_not_before(tls_check_result)
  report(
    service: "#{tls_endpoint_name(tls_check_result)} not before",
    state: not_before_state(tls_check_result),
    metric: tls_check_result.not_before_away,
    description: tls_check_result.not_before_away_in_words,
  )
end

#report_ocsp(tls_check_result) ⇒ Object



416
417
418
419
420
421
422
423
424
# File 'lib/riemann/tools/tls_check.rb', line 416

def report_ocsp(tls_check_result)
  return unless tls_check_result.ocsp?

  report(
    service: "#{tls_endpoint_name(tls_check_result)} OCSP status",
    state: tls_check_result.valid_ocsp? ? 'ok' : 'critical',
    description: tls_check_result.ocsp_status,
  )
end

#report_trust(tls_check_result) ⇒ Object



394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/riemann/tools/tls_check.rb', line 394

def report_trust(tls_check_result)
  commont_attrs = {
    service: "#{tls_endpoint_name(tls_check_result)} trust",
  }
  extra_attrs = if tls_check_result.exception
                  {
                    state: 'critical',
                    description: tls_check_result.exception.message,
                  }
                else
                  {
                    state: tls_check_result.trusted? ? 'ok' : 'critical',
                    description: if OPENSSL_ERROR_STRINGS[tls_check_result.verify_result]
                                   format('%<code>d - %<msg>s', code: tls_check_result.verify_result, msg: OPENSSL_ERROR_STRINGS[tls_check_result.verify_result])
                                 else
                                   tls_check_result.verify_result.to_s
                                 end,
                  }
                end
  report(commont_attrs.merge(extra_attrs))
end

#report_unavailability(uri, address, exception) ⇒ Object



360
361
362
363
364
365
366
# File 'lib/riemann/tools/tls_check.rb', line 360

def report_unavailability(uri, address, exception)
  report(
    service: "#{tls_endpoint_name2(uri, address)} availability",
    state: 'critical',
    description: exception.message,
  )
end

#smtp_tls_socket(uri, address) ⇒ Object



497
498
499
500
501
502
503
504
505
506
# File 'lib/riemann/tools/tls_check.rb', line 497

def smtp_tls_socket(uri, address)
  socket = tcp_socket(address, uri.port)
  read_socket_lines_until_prefix_matched(socket, '220 ', also_accept_prefixes: ['220-'])
  socket.send("EHLO #{my_hostname}\r\n", 0)
  read_socket_lines_until_prefix_matched(socket, '250 ', also_accept_prefixes: ['250-'])
  socket.send("STARTTLS\r\n", 0)
  socket.gets

  tls_handshake(socket, uri.host)
end

#ssl_contextObject



572
573
574
575
576
577
578
579
580
# File 'lib/riemann/tools/tls_check.rb', line 572

def ssl_context
  @ssl_context ||= begin
    ctx = OpenSSL::SSL::SSLContext.new
    ctx.cert_store = store
    ctx.verify_hostname = false
    ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
    ctx
  end
end

#storeObject



582
583
584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/riemann/tools/tls_check.rb', line 582

def store
  @store ||= begin
    store = OpenSSL::X509::Store.new
    store.set_default_paths
    opts[:trust].each do |path|
      if File.directory?(path)
        store.add_path(path)
      else
        store.add_file(path)
      end
    end
    store
  end
end

#tcp_socket(host, port) ⇒ Object



452
453
454
# File 'lib/riemann/tools/tls_check.rb', line 452

def tcp_socket(host, port)
  Socket.tcp(host, port, connect_timeout: opts[:connect_timeout])
end

#test_uri_address(uri, address) ⇒ Object



321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/riemann/tools/tls_check.rb', line 321

def test_uri_address(uri, address)
  socket = tls_socket(uri, address)
  tls_check_result = TLSCheckResult.new(uri, address, socket, self)
  report_availability(tls_check_result)
  return unless socket.peer_cert

  report_not_before(tls_check_result) if opts[:checks].include?('not-before')
  report_not_after(tls_check_result) if opts[:checks].include?('not-after')
  report_identity(tls_check_result) if opts[:checks].include?('identity')
  report_trust(tls_check_result) if opts[:checks].include?('trust')
  report_ocsp(tls_check_result) if opts[:checks].include?('ocsp')
rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT, UnexpectedMessage => e
  report_unavailability(uri, address, e)
end

#test_uri_addresses(uri, addresses) ⇒ Object



315
316
317
318
319
# File 'lib/riemann/tools/tls_check.rb', line 315

def test_uri_addresses(uri, addresses)
  addresses.each do |address|
    test_uri_address(uri, address.to_s)
  end
end

#tickObject



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
# File 'lib/riemann/tools/tls_check.rb', line 284

def tick
  report(
    service: 'riemann tls-check resolvers utilization',
    metric: (opts[:resolvers].to_f - @resolve_queue.num_waiting) / opts[:resolvers],
    state: @resolve_queue.num_waiting.positive? ? 'ok' : 'critical',
    tags: %w[riemann],
  )
  report(
    service: 'riemann tls-check resolvers saturation',
    metric: @resolve_queue.length,
    state: @resolve_queue.empty? ? 'ok' : 'critical',
    tags: %w[riemann],
  )
  report(
    service: 'riemann tls-check workers utilization',
    metric: (opts[:workers].to_f - @work_queue.num_waiting) / opts[:workers],
    state: @work_queue.num_waiting.positive? ? 'ok' : 'critical',
    tags: %w[riemann],
  )
  report(
    service: 'riemann tls-check workers saturation',
    metric: @work_queue.length,
    state: @work_queue.empty? ? 'ok' : 'critical',
    tags: %w[riemann],
  )

  opts[:uri].each do |uri|
    @resolve_queue.push(URI(uri))
  end
end

#tls_endpoint_name(tls_check_result) ⇒ Object



597
598
599
# File 'lib/riemann/tools/tls_check.rb', line 597

def tls_endpoint_name(tls_check_result)
  tls_endpoint_name2(tls_check_result.uri, tls_check_result.address)
end

#tls_endpoint_name2(uri, address) ⇒ Object



601
602
603
# File 'lib/riemann/tools/tls_check.rb', line 601

def tls_endpoint_name2(uri, address)
  "TLS certificate #{uri} #{endpoint_name(IPAddr.new(address), uri.port)}"
end

#tls_handshake(raw_socket, hostname) ⇒ Object



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/riemann/tools/tls_check.rb', line 553

def tls_handshake(raw_socket, hostname)
  tls_socket = OpenSSL::SSL::SSLSocket.new(raw_socket, ssl_context)
  tls_socket.hostname = hostname
  begin
    tls_socket.connect
  rescue OpenSSL::SSL::SSLError => e
    # This may fail for example if a client certificate is required but
    # not provided. In this case, the remote certificate is available and
    # we can ignore this issue. In other cases, the remote certificate is
    # not available, in this case we want to stop and report the issue
    # (e.g. connecting to a host with a SNI for a name not handled by
    # that host).
    tls_socket.define_singleton_method(:exception) do
      e
    end
  end
  tls_socket
end

#tls_socket(uri, address) ⇒ Object



456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/riemann/tools/tls_check.rb', line 456

def tls_socket(uri, address)
  case uri.scheme
  when 'smtp'
    smtp_tls_socket(uri, address)
  when 'imap'
    imap_tls_socket(uri, address)
  when 'ldap'
    ldap_tls_socket(uri, address)
  when 'mysql'
    mysql_tls_socket(uri, address)
  when 'postgres'
    postgres_tls_socket(uri, address)
  else
    raw_tls_socket(uri, address)
  end
end