OpenVPN Server / ca certificate expiration check for Nagios

#!/usr/bin/python3

import argparse, os, sys, subprocess, time, math, datetime

def timeify(seconds):
    from collections import OrderedDict
    from math import floor

    units = dict()
    units["s"] = 1
    units["m"] = 60
    units["h"] = 60 * units["m"]
    units["d"] = 24 * units["h"]
    units["w"] = 7 * units["d"]
    units["y"] = 52 * units["w"]

    result = []
    for unit in reversed(units):
        if (s:=floor(seconds / units[unit])) != 0:
                result.append(str(s)+unit)
                seconds = seconds - s * units[unit];

    return (" ".join(result))

ap = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter)
ap.add_argument('certificate', help='Run cron-helper')
ap.add_argument('-c','--critical', help='Critical threshold', action='store', default=10)
ap.add_argument('-w','--warning', help='Warning threshold', action='store', default=30)
ap.add_argument('-d','--description', help='Add description to output', action='store')

args = ap.parse_args();

if not os.path.isfile(args.certificate):
    print ("ERROR: File `"+args.certificate+"` not found!");
    sys.exit(-1);

if not os.access(args.certificate, os.R_OK):
    print ("ERROR: File `"+args.certificate+"` not readable!");
    sys.exit(-1);

result = subprocess.run("openssl x509 -enddate -noout -in "+args.certificate+" | cut -c10- | date +%s -f -", shell=True, capture_output=True);

if result.returncode != 0:
    print ("ERROR: Could not run / failed to parse openssl output");
    sys.exit(-1);

try:
    expires = int(result.stdout)
except:
    print ("ERROR: Failed to parse openssl output");
    sys.exit(-1);

now = int(time.time())

if args.description:
    desc = " ("+args.description+")"
else:
    desc = "";

if expires < now:    # Expired
    print ("CRITICAL: Certificate "+args.certificate+desc+" expired "+timeify(now - expires)+" ago");
    sys.exit(2);

days_left = math.floor((expires-now) / 60 / 60 / 24)
valid_until = datetime.datetime.fromtimestamp(expires).strftime("%c");

if days_left <= int(args.critical):
    print ("CRITICAL: Certificate "+args.certificate+desc+" expires "+valid_until+" ("+str(days_left)+" days left)");
    sys.exit(2);

if days_left <= int(args.warning):
    print ("WARNING: Certificate "+args.certificate+desc+" expires "+valid_until+" ("+str(days_left)+" days left)");
    sys.exit(1);

print ("OK: Certificate "+args.certificate+desc+" valid until "+valid_until+" ("+str(days_left)+" days left)");
sys.exit(0);
Udgivet i Python | Skriv en kommentar

Timify routine for Python3

Takes a number of seconds i.e. “120000002” and converts into “3y 42w 2d 21h 20m 2s”.

#!/usr/bin/python3

def timeify(seconds):
    from collections import OrderedDict
    from math import floor

    units = dict()
    units["s"] = 1
    units["m"] = 60
    units["h"] = 60 * units["m"]
    units["d"] = 24 * units["h"]
    units["w"] = 7 * units["d"]
    units["y"] = 52 * units["w"]

    result = []
    for unit in reversed(units):
        if (s:=floor(seconds / units[unit])) != 0:
                result.append(str(s)+unit)
                seconds = seconds - s * units[unit];

    return (" ".join(result))

print (timeify(120000002));
Udgivet i Python | Skriv en kommentar

Adding drop-shadow to columns in WordPress / Gutenberg using Twenty Twenty Four

In backend left-side menu click “Appearance” and then “Editor”:

You are not in the customizer, click “Styles”:

This takes you to the style-selector, click the edit-button in the op right. Looks like a pen:

This opens the style-editor in the right site of the screen:

Now click “Blocks”, this brings up a list of blocks you can customize, pick “Column”:

This brings you to an interface that lets you change the default design for columns:

You need to scroll to the bottom, open the “Additional CSS” option:

And add the code you see there:

.dropshadow { 
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.3);
 }

Then click the “Save” button in the top-right corner:

Button changes a bit, just in case you changed your mind. Click it again:

Now navigate to the page and the column in the editor where you wish to add drop shadow:

And add “dropshadow” as a css-class:

Very pwetty and very phancey 😍

Udgivet i Wordpress | Skriv en kommentar

Simple Javascript clock

As the title says:

<html>
  <head>
    <title>Clock</title>
    <script 
      src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
    </script>
    <style>
      /* Needed for positioning div */
      body {
        font-size: 58pt;
        height: 100vh;
        height: 100%;
        display: flex;
        justify-content: center;
      }
      #clock {
        margin: auto;
        text-align: center;
        margin: auto;
      }
      /* Just styling */
      body {
        background-color: black;
        color: yellow;
        font-family: 'Arial';
      }
    </style>
  </head>
  <body>
    <div id=clock>
      <div id=date></div>
      <div id=time> </div>
    </div>
    <script>
      function nf(i)
      {
        if (i < 10)
          return "0"+i;
        else return i;
      }
      function updateClock()
      {
        const d = new Date();
        d.getTime();
        $("#time").html( d.getHours()+":"+
                         nf(d.getMinutes())+":"+
                         nf(d.getSeconds()));

        let days = ["S&oslash;ndag", "Mandag", "Tirsdag", "Onsdag","Torsdag",   
                    "Fredag","L&oslash;rdag"];

        let months = ["Januar","Februar","Marts","April","Maj","Juni","Juli",
                      "August","September","Oktober","November","December"];

        $("#date").html( days[d.getDay()]+" d. "+
                         d.getDate()+" "+
                         months[d.getMonth()]+" "+
                        (1900+d.getYear()));
        setTimeout(updateClock, 500);
      }
      updateClock();
    </script>
  </body>
</html>
Udgivet i Javascript | Skriv en kommentar

Faking time on Debian 12

Sometimes you need to test stuff that only happens once a day, that can be tiresome to wait around for, so playing a bit of Deloran-style-prank on you Linux systems can be handy.

Start by disabling ntp:

root@lab1:~# timedatectl
               Local time: Sat 2023-12-02 05:54:58 CET
           Universal time: Sat 2023-12-02 04:54:58 UTC
                 RTC time: Sat 2023-12-02 04:54:59
                Time zone: Europe/Copenhagen (CET, +0100)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no
root@lab1:~# timedatectl set-ntp false
root@lab1:~# timedatectl
               Local time: Sat 2023-12-02 05:55:09 CET
           Universal time: Sat 2023-12-02 04:55:09 UTC
                 RTC time: Sat 2023-12-02 04:55:10
                Time zone: Europe/Copenhagen (CET, +0100)
System clock synchronized: yes
              NTP service: inactive
          RTC in local TZ: no
root@lab1:~#

And then you can simply set whatever time you want:

root@test1:~/test# timedatectl set-time '2123-12-05 12:00:00'
root@test1:~/test# date
Sun Dec  5 12:00:01 PM CET 2123
Udgivet i Linux | Skriv en kommentar

Styling Nagios output for a large display

Theres not really any built in features for styling Nagios, so i devised a simple workaround that utilizes html, css and jquery to do the trick.

We need to run this on the same domain as Nagios itself or disable cors for this to work.

<html>        
 <head>
  <title>Nagios Services Monitor</title>
  <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
  </script>
  <style>
   body {
    padding: 0;
    margin: 0;
   }
   #nagios {
    height: 100%;
    width: 100%;
    overflow: hidden;
    zoom: 175%;
   }  
  </style>
 </head>
 <body>
  <div id=nagios></div>
  <script>
   $(document).ready(function(){                               
   setInterval(function()                                
   {
    $.get('/cgi-bin/nagios4/status.cgi?host=all&servicestatustypes=28',
     function(data) {    
      data = data.replace("Updated every 90 seconds",
                          "Updated every second");
      data = data.replaceAll(/<script[\s\S]+<\/script>/g,
                            "<!-- scripts removed -->");
      $('#nagios').html(data);
                       });
      },1000);
   });
   </script>
 </body>
</html>

Tested in Chromium.

Udgivet i Nagios | Skriv en kommentar

Delete USB partitions on Windows

Really useful if you have a USB Stick which have been used for installing Debian or another Linux and you wish to use it for something on Windows, the graphical partition manager in Windows are way to retarded to do this, but luckily there’s a CLI tool who can do it:

C:\Users\mike> diskpart

Now windows will show a popup asking for permissions to run this tool with administrator privileges, after you granted this you will be in a “DISKPART” prompt, now do this:

Microsoft DiskPart version 10.0.19041.3636

Copyright (C) Microsoft Corporation.
On computer: OFFICEPC

DISKPART> list disk

  Disk ###  Status         Size     Free     Dyn  Gpt
  --------  -------------  -------  -------  ---  ---
  Disk 0    Online          111 GB  1024 KB
  Disk 1    Online           28 GB  1024 KB

DISKPART> select disk 1

Disk 1 is now the selected disk.

DISKPART> list partition

  Partition ###  Type              Size     Offset
  -------------  ----------------  -------  -------
  Partition 1    Primary              1 GB  1024 KB
  Partition 2    Primary             27 GB     1 KB

DISKPART> select partition 1

Partition 1 is now the selected partition.

DISKPART> delete partition

DiskPart successfully deleted the selected partition.

DISKPART> exit

You obviously need to repeat this for all the partitions you need to delete.

More info: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/diskpart

Udgivet i Windows | Skriv en kommentar

Automating USBIP server

In a prior post we installed USBIP and used it manually, in this post I will set it up “the correct Debian(systemd) way”.

But first, for completeness sake, we will go through installation progress again, first install the package:

root@host:~# apt-get install usbip

Load the main module and make it persistent:

root@server:~# modprobe usbip_core
root@server:~# modprobe usbip_host
root@server:~# echo usbip_core >> /etc/modules
root@server:~# echo usbip_host >> /etc/modules

Create service-file for usbip-deamon, create /etc/systemd/system/usbipd.service with following content:

[Unit]
Description=Usbipd
After=network.target

[Service]
Type=forking
ExecStart=/usr/sbin/usbipd -D

[Install]
WantedBy=multi-user.target

Enable and start it:

root@server:~# systemctl enable usbipd --now
Created symlink /etc/systemd/system/multi-user.target.wants/usbipd.service → /etc/systemd/system/usbipd.service.

Then we need a systemd service file for sharing usb-devices, create /etc/systemd/system/usbip-device@.service containing the following:

[Unit]
Description=USBIP Device %I
Requires=usbipd.service
After=usbipd.service

[Service]
RemainAfterExit=yes
ExecStart=/usr/sbin/usbip bind --busid=%i
ExecStop=/usr/sbin/usbip unbind --busid=%i

[Install]
WantedBy=multi-user.target

And Finally start and enable this pseudo-service:

root@server:/etc/systemd/system# systemctl enable usbip-device@3-3 --now
Created symlink /etc/systemd/system/multi-user.target.wants/usbip-device@3-3.service → /etc/systemd/system/usbip-device@.service.

Try to reboot and verify from the client:

root@backup2:~# usbip list -r backup1
Exportable USB devices
======================
 - backup1
        3-3: Sony Corp. : unknown product (054c:05b9)
           : /sys/devices/pci0000:00/0000:00:10.0/usb3/3-3
           : (Defined at Interface level) (00/00/00)
Udgivet i Linux | Skriv en kommentar

USBIP on Debian 12 – USB Device Sharing over IP network

In a world were virtualization is slowly creeping in everywhere the demand for virtual USB cables are growing, luckily the USBIP protocol are implemented in the Linux kernel – and the userland tools are partly implemented in Debian, at least enough for us to mount it manually. If you want to automate it I made another post for that.

On both client and server:

Install the package:

root@system:~# apt-get install usbip

Load the main module and make it persistent:

root@system:~# modprobe usbip_core
root@system:~# echo usbip_core >> /etc/modules

Setting up the server:

The server needs an aditional kernel module:

root@server:~# modprobe usbip_host
root@server:~# echo usbip_host >> /etc/modules

Now you can share the usb device, I plugged in a USB stick into my server:

root@server:~# usbip list -l
 - busid 3-3 (054c:05b9)
   Sony Corp. : unknown product (054c:05b9)

This server only have one usb device attached making the output pretty simple, in this case the busid is “3-3”, but on your system it may have a different format depending on your hardware.

Bind this device to usbip:

root@server:~# usbip bind --busid=3-3
usbip: info: bind device on busid 3-3: complete

And finally start the deamon:

root@server:~# usbipd
usbipd: info: starting usbipd (usbip-utils 2.0)
usbipd: info: listening on 0.0.0.0:3240
usbipd: info: listening on :::3240

This is still a very manual process, later I will create an additional post with an example on how to automate this on Debian 12.

Setting up the client

The client also need a module:

root@client:~# modprobe vhci-hcd
root@client:~# echo vhci-hcd >> /etc/modules

And now you can connect to the remote server and list available devices:

root@client:~# usbip list -r server
Exportable USB devices
======================
 - backup1
        3-3: Sony Corp. : unknown product (054c:05b9)
           : /sys/devices/pci0000:00/0000:00:10.0/usb3/3-3
           : (Defined at Interface level) (00/00/00)

… and attach it:

root@client:~# usbip attach -r server -b 3-3

Which will cause it pop up in dmesg:

root@client:~# dmesg | tail -n10
[3425534.758312] usb-storage 5-1:1.0: USB Mass Storage device detected
[3425534.758672] scsi host9: usb-storage 5-1:1.0
[3425535.790312] scsi 9:0:0:0: Direct-Access     Sony     Storage Media    PMAP PQ: 0 ANSI: 6
[3425535.790979] sd 9:0:0:0: Attached scsi generic sg5 type 0
[3425535.792699] sd 9:0:0:0: [sde] 30375936 512-byte logical blocks: (15.6 GB/14.5 GiB)
[3425535.793509] sd 9:0:0:0: [sde] Write Protect is off
[3425535.793521] sd 9:0:0:0: [sde] Mode Sense: 45 00 00 00
[3425535.794265] sd 9:0:0:0: [sde] Write cache: disabled, read cache: enabled, doesn't support DPO or FUA
[3425535.801659]  sde:
[3425535.801757] sd 9:0:0:0: [sde] Attached SCSI removable disk

Now you can mount the device:

root@client:~# mount /dev/sde /mnt
mount: /mnt: WARNING: source write-protected, mounted read-only.
root@backup2:~# ls /mnt
boot  client_install  EFI  EULA  install.img  LICENSES  Packages  repodata  RPM-GPG-KEY-CH-8  RPM-GPG-KEY-CH-8-LCM  RPM-GPG-KEY-Platform-V1

And now your Debian Install USB stick from “server” is mounted on “client”, I have not yet done any kind of methodical testing so I don’t really know how the performance is, but right now I was more concerned with getting it to work, than what kind of performance it would deliver, it is probably “good enough” for anything except for maybe high latency gaming and huge data transfers.

But I still made a quick benchmark using:

root@system:~# hdparm -t /dev/sde

On both systems where i got around 200MB/sec on the local system and 85MB/sec on the remote client. But my current use-case is to connect printers and scanners, and the occasional USB Stick to transfer small amounts of files.

For any kind of serious ingestion of video materials I would not recommend this solution.

Detaching USB Device

root@client:~# umount /mnt
root@client:~# usbip port
Imported USB devices
====================
Port 15: <Port in Use> at Super Speed(5000Mbps)
       Sony Corp. : unknown product (054c:05b9)
       5-1 -> usbip://backup1:3240/3-3
           -> remote bus/dev 003/002
root@client:~# usbip detach -p 15
usbip: info: Port 15 is now detached!

Next task is to automate this.

Udgivet i Linux, Uncategorized | Skriv en kommentar

Logging output of cronjobs

If you wish to send output of cronjobs to syslog instead of email use the following:

20 10 * * * /opt/script/dostuff.py 2>&1 | /usr/bin/logger -t stuffdoer

If you want live-updates in the log file it can be necessary to unbuffer it, install the “expect” package and modify the command like so:

20 10 * * * /usr/bin/unbuffer /opt/script/dostuff.py 2>&1 | /usr/bin/logger -t stuffdoer

If it’s a python script you can accomplish the same thing by adding “-u” to the shebang.

Udgivet i Linux | Skriv en kommentar