~cypheon/ecertmon

c3d1a0f414843221a1eb98525e9ac0072ba074a2 — Johann Rudloff 1 year, 9 months ago 6aeafd8
Handle connection errors in scanner instead of crashing
1 files changed, 24 insertions(+), 18 deletions(-)

M src/cert_scanner.erl
M src/cert_scanner.erl => src/cert_scanner.erl +24 -18
@@ 64,24 64,30 @@ code_change(_OldVsn, State, _Extra) ->
%% logic
do_scan(State) ->
  Hostname = State#state.hostname,
  {ok, Socket} = ssl:connect(State#state.hostname, State#state.port, []),
  logger:debug("connection established: ~s:~p~n", [Hostname,
                                                State#state.port]),
  {ok, PeerCertBytes} = ssl:peercert(Socket),
  ok = ssl:close(Socket),

  PeerCert = public_key:pkix_decode_cert(PeerCertBytes, otp),
  Validity = (PeerCert#'OTPCertificate'.tbsCertificate)#'OTPTBSCertificate'.validity,
  NotAfterStr = Validity#'Validity'.notAfter,
  NotAfterSeconds = pubkey_cert:time_str_2_gregorian_sec(NotAfterStr),
  NotAfter = calendar:gregorian_seconds_to_datetime(NotAfterSeconds),
  NotAfterEpoch = datetime_to_epoch(NotAfter),
  logger:debug("peer cert ~s valid until: ~p (unix epoch: ~p)~n", [Hostname, NotAfter,
                                                             NotAfterEpoch]),
  NowSeconds = calendar:datetime_to_gregorian_seconds(calendar:universal_time()),
  RemainingDays = NotAfterSeconds - NowSeconds,
  logger:debug("peer cert ~s valid days remaining: ~p~n", [Hostname, RemainingDays / (24 * 3600)]),
  {noreply, State#state{validity = {valid, NotAfterEpoch}}}.
  case ssl:connect(State#state.hostname, State#state.port, []) of
  {ok, Socket} ->
      logger:debug("connection established: ~s:~p~n", [Hostname,
                                                       State#state.port]),
      {ok, PeerCertBytes} = ssl:peercert(Socket),
      ok = ssl:close(Socket),

      PeerCert = public_key:pkix_decode_cert(PeerCertBytes, otp),
      Validity = (PeerCert#'OTPCertificate'.tbsCertificate)
      #'OTPTBSCertificate'.validity,
      NotAfterStr = Validity#'Validity'.notAfter,
      NotAfterSeconds = pubkey_cert:time_str_2_gregorian_sec(NotAfterStr),
      NotAfter = calendar:gregorian_seconds_to_datetime(NotAfterSeconds),
      NotAfterEpoch = datetime_to_epoch(NotAfter),
      NowSeconds = calendar:datetime_to_gregorian_seconds(
                     calendar:universal_time()),
      RemainingDays = (NotAfterSeconds - NowSeconds) / (24 * 3600),
      logger:debug("peer cert ~s valid until: ~p (unix epoch: ~p, remaining days: ~p)~n",
                   [Hostname, NotAfter, NotAfterEpoch, RemainingDays]),
      {noreply, State#state{validity = {valid, NotAfterEpoch}}};
    {error, Reason} ->
      logger:warning("failed to connect to ~p: ~p", [Hostname, Reason]),
      {noreply, State#state{validity = {error, Reason}}}
  end.

%% utilities