Check certificate expiration for domains

I manage a handful of websites (around 60), and to automate my job I wrote a script to check for the expiration of SSL certificates.

Most of the sites I manage use LetsEncrypt and are self-hosted by me on Linode, but sometimes (never?) the certbot renew doesn’t work or some external hosting company decides to renew the certificate 2 days before the expiration. Why? I don’t know.

LetsEncrypt will automatically renew the certificate if less than 30 days are remaining, so this script will rarely report a problem.

So this script runs daily and warns me if some host certificate will expire soon, so I can manually check.

This script used Net::SSL::ExpireDate to check for expiration date, but it seems it doesn’t like Cloudflare certificates, so I added another function to get the certificate expiration date using openssl.

This script is available via github:

https://gist.github.com/sburlot/9a26255cc5b7d6b703fb37d40867baec

Usage: enter the list of sites by modifying the line:

my @sites = qw/coriolis.ch textfiles.com/;

and run (via crontab, after your certbot renew cron)

Helpful links:

https://prefetch.net/articles/checkcertificate.html
https://www.cilogon.org/cert-expire

#!/usr/bin/perl
# vi:set ts=4 nu: 

use strict;

use POSIX 'strftime';
use Net::SSL::ExpireDate;
use Date::Parse;
use Data::Dumper;
use MIME::Lite;

my $status = "";

my @sites = qw/coriolis.ch textfiles.com/;

my $error_sites = "";

my %expiration_sites;

################################################################################################
sub check_site_with_openssl($) {
    my $site = shift @_;

    my $expire_date = `echo | openssl s_client -servername $site -connect $site:443 2>&1 | openssl x509 -noout -enddate 2>&1`;
    if ($expire_date !~ /notAfter/) {
        print "Error while getting info for certificate: $site\n";
        $error_sites .= "$site has no expiration date\n";
        return;
    }
    $expire_date =~ s/notAfter=//g;
    my $time = str2time($expire_date);
    my $now = time;
    my $days = int(($time-$now)/86400);
    $expiration_sites{$site} = $days;
    $status .= "$site expires in $days days\n";
    print "$site expires in $days days\n";
    if ($days < 25) {
      $error_sites .= "$site => in $days day" . ($days > 1 ? "s":"") . "\n";
    }
}

################################################################################################
sub check_site($) {

    my $site = shift @_;

    # we have an error for sites served via Cloudflare: record type is SSL3_AL_FATAL
    # Net::SSL doesnt support SSL3??
    my $ed = Net::SSL::ExpireDate->new( https => $site );
    #print Dumper $ed;
    if (defined $ed->expire_date) {
        my $expire_date = $ed->expire_date;         # return DateTime instance
        my $time = str2time($expire_date);
        my $now = time;
        my $days = int(($time-$now)/86400);
        $expiration_sites{$site} = $days;
        print "$site expires in $days days\n";
        if ($days < 25) {
          $error_sites .= "$site => in $days day" . ($days > 1 ? "s":"") . "\n";
        }
    } else {
        $error_sites .= "$site has no expiration date\n"; # or has another error, but I'll check manually.
    }
  
}

################################################################################################
sub send_email($) {

    my $message = shift @_;

    my $msg = MIME::Lite->new(
        From    => 'me@website.com',
        To      => 'me@website.com',
        Subject => 'SSL Certificates',
        Data    => "One or more certificates should be renewed:\n\n$message\n"
    );
    $msg->send;
}

################################################################################################
print strftime "%F\n", localtime;
print "="x30 . "\n";

for my $site (sort @sites) {
  check_site_with_openssl($site);
}

# sort desc by expiration
foreach my $site (sort { $expiration_sites{$a} <=> $expiration_sites{$b} } keys %expiration_sites) {
    $status .= "$site expires in " . $expiration_sites{$site} . " days\n" ;
}

print "="x30 . "\n";

if ($error_sites ne "") {
    send_email($error_sites);
}

Check for new Dropbox folders on Linux

For a customer, I created a service on a remote server that processes files delivered via Dropbox. Problem is Dropbox on Linux will sync all the folders in its root folder, unless it’s excluded. You can exclude all folders except the one you’re interested in, but as soon as you add a folder to your Dropbox, it will appear on your Linux server.

This script will warn you if a new folder appears. It doesn’t exclude automatically new folders, but this feature could be added if you’re brave enough.

#!/usr/bin/perl
# When using Dropbox on Linux, the complete dropbox folder is 
# sync'ed by default, which can use precious disk space if 
# we only need some folders.
# Because we cant choose which folders will be sync'ed on
# Linux, we can only exclude folders we don't want. So this script
# reports when a new folder is added to the Dropbox top folder.
# A nice feature would be to be able to only allow some folders.
# Note: since we can't exclude files, they are not reported.
# Dont add a large file to the root of Dropbox, you can't exclude it from syncing.

# if this script finds folders not in the allowed list, it sends
# an email and a notification, in case the mail is flagged as spam.

# I choose not to exclude new folders directly in this script,
# in case something breaks. This script is run on a server used by
# a customer as a WebService endpoint, so better be safe.

# To exclude a folder from syncing, use the dropbox-cli script available at
# https://www.dropbox.com/download?dl=packages/dropbox.py
# then do
# ./dropbox.py exclude add "Folder to exclude"
#
# Coriolis Stephan Burlot, Apr 11, 2018

use strict;
use Data::Dumper;
use MIME::Lite;
use WebService::Prowl;

## the path to the Dropbox folder
my $dropbox_folder = '/home/stephan/Dropbox/';

## email settings
my $email_address = 'EMAIL_ADDRESS';

## I use Prowl (prowlapp.com) to send notifications to my phone.
## prowl settings
my $prowl_api_key = 'PROWL_API_KEY';

## Allowed folders
# famous last words:
# customer: "the folder is named TEST_Service, we'll change the
# name when we go in production."
my @allowed_folders = qw/TEST_Service/;

#################################
## sends a email with the message passed as parameter
sub send_email($) {
  my $content = shift @_;
  
  my $msg = MIME::Lite->new(
    From  => $email_address,
    To    => $email_address,
    Subject => 'Dropbox Bot',
    Data  => $content
  );
  $msg->send;
}

#################################
## sends a notification via Prowl
sub send_notification($$) {
  my ($app, $event, $message) = @_;
  if ($event eq "") {
    $event = ' ';
  }
  
  # grab your API key from prowlapp.com
  my $ws = WebService::Prowl->new(apikey => $prowl_api_key);
  $ws->verify || die $ws->error();
  $ws->add(application => "$app",
       event     => "$event",
       description => "$message",
       url     => "");

}

#################################
## MAIN
#################################

# I dont use smartmatch, ie
# if ($file ~~ @allowed_folders)
# so I create a hash for simple matching.
my %allowed = map { $_ => 1 } @allowed_folders;

chdir $dropbox_folder;
if (opendir(my $dh, $dropbox_folder)) {
  my @folders = grep !/^\./, readdir($dh);
  closedir $dh;
  
  # array of bad folders
  my @bad = map { -f $_ || exists $allowed{$_} ? (): $_ } @folders;
  if (scalar(@bad) != 0) {
    print "New folders: " . join(", ", @bad) . "\n";
    send_notification('Linode_Small', 'Dropbox Bot', "There are new folders in Dropbox: you should exclude them.");
    send_email("Hello,\n\nI found these new folders in Dropbox:\n\n" . join("\n", @bad) . "\n\nThey should be excluded.\n");
  }
} else {
  send_notification('Linode_SMALL', 'Dropbox Bot', "I cant open Dropbox folder. Is it still there?");
  send_email("Hello,\n\nI can't opendir $dropbox_folder\n\nIs Dropbox still here?");
  die "Can't opendir $dropbox_folder: $!\n";
}

Enjoy.

Liste des appels Swisscom

(English version available here)

Ici en Suisse, mon opérateur téléphonique (Swisscom) a une option qui me permet de voir la liste des 20 derniers appels reçus ou manqués sur la page web de mon compte.

Ne désirant pas me connecter à cette page a chaque fois que je veux consulter cette liste afin de vérifier qui m’a appelé, j’ai écris quelques scripts qui récupèrent le contenu de cette page et l’affiche sur mon iPhone via une application iOS. Les noms sont récupérés depuis le carnet d’adresse et une notification est envoyée (via Prowl) quand un appel est reçu mais personne ne répond.

screen

Cette application iOS ne peut être distribuée en l’état sur l’AppStore car:

  • J’ai besoin des identifiants et mot de passe du compte Swisscom pour accéder à ces données et je n’aurai pas confiance dans un service qui me demanderait ces infos. Comme vous, je suppose.
  • La méthode utilisée pour récupérer la liste des appels n’est pas une méthode officielle et peut (comme cela est déjà arrivé) ne plus fonctionner si Swisscom change l’aspect de la page web.
  • L’application iOS peut rechercher le nom d’après un numéro inconnu via un appel à Local.ch (qui est plus ou moins l’annuaire suisse en ligne officiel). Bien sûr, il n’y a pas d’API officielle pour ce service et ils peuvent couper l’accès à tout moment. Soyez sympa et n’abusez pas de service.

J’ai mis le source à disposition sur GitHub: https://github.com/sburlot/phonecalls

Pour Swisscom

Si vous travaillez pour Swisscom, ou connaissez quelqu’un qui y travaille, demandez une méthode publique pour accéder à ces données, en proposant un login authentifié. Ca serait pratique et permettrait à cette app (et à d’autres!) d’être disponible pour le grand public.

Ou Swisscom pourrait ajouter cette fonctionnalité à leur application officielle,

Ou Swisscom pourrait m’embaucher pour implémenter cette fonctionnalité dans leur application. Je suis développeur freelance et disponible!

Quelques détails techniques

Sur le serveur, un script Perl va récupérer les données (via cron) du portail Swisscom et les enregistre dans une base MySQL (n’importe quelle base fonctionnerait).

L’application iOS appelle un script PHP sur le serveur: le serveur va récupérer les données de la base et renvoie un objet JSON.

Amusez-vous bien!

PS: bien sûr, je peux attendre d’être chez moi pour consulter les appels en absence sur mon téléphone, mais c’est moins geek et drôle. 😉

(Ceci est une version plus longue du post précédent en anglais)

Swisscom Phonecalls

(Version française disponible ici)

Here in Switzerland the major telco (Swisscom) has an option to let you see your last 20 answered and missed calls on your account webpage.

Not wanting to log in every time I want to check if I missed a call, I wrote some scripts and that fetches the content of my account web page and display them on an iOS app.

The names are fetched from the iPhone address book, and the iPhone receives a notification via Prowl when a call is missed.

screen

Or perhaps all this was an excuse to write some code during the holidays. Who knows.

I can’t make this app an official app because:

  • I need the Swisscom credentials to access the portal and I wouldn’t trust a stranger and give them access to my account. As you do.
  • The process of fetching the list of calls is not an officially approved method and may break (and did) when Swisscom changes the layout of the page.
  • The iOS app can also retrieve the owner of an unknown number via a call to the local.ch (more or less the official swiss white pages site). Of course, the API endpoint is not official nor public. Please be nice and don’t abuse this unofficial endpoint.

So I made the source available on GitHub: https://github.com/sburlot/phonecalls

For Swisscom

Oh, if you work for Swisscom, or know someone who does, ask for a method to fetch this data with a secure login option. That would be great, because I could make this app available via the AppStore.

Or Swisscom could add this feature to their official app. PLEASE.

Or Swisscom could hire me to implement this feature in their official app. I’m a freelance developer and I’m available!

Some tech details

On the server a Perl script fetches the data (via cron) from the Swisscom and stores the numbers in a MySQL database (any DB would work).
The iOS app calls a PHP script on the server to access the data: the PHP scripts fetches the data from the database and returns a JSON object.

Have fun!

PS: of course I can wait to return home and check my calls on my phone, but where’s the fun? 😉

I wrote this app 2 years ago and I still use it.

(this is a longer version of the original post)

Check your missed calls from your iPhone

Here in Switzerland the major telco (Swisscom) has an option to let you see your last 20 answered and missed calls on your account webpage.

Not wanting to log in every time I want to check if I missed a call, I wrote some scripts and that fetches the content of my account web page and display them on an iOS app.

Lire la suite…

Perl is fun

When I reinstalled my iMac 24″, I restored a backup of the iPhoto Library.

But the software I’m working on (eXaPhoto Publisher) couldn’t import correctly an iPhoto album: a lot of pictures were missing. The imedia browser had the same problem, but iPhoto seems smart enough to find the pictures.

When you manage yourself your picture, iPhoto maintains a dummy structure inside the « iPhoto Library ». This structure contains links (aliases) to the original files.

I don’t know how it happened, but all the iPhoto aliases were marked as being on the backup volume. So instead of reimporting all my pictures and risk losing all my albums, I’ve written a Perl script to update all the aliases in « iPhoto Library/Originals » so they point now to the right location.

Lire la suite…