Archive for the ‘Linux and FreeBSD Desktop’ Category

Automatically Re-plug all USB devices on system resume on Debian Linux using systemd

Thursday, March 26th, 2026

automatically-replug-all-usb-devices-on-system-resume-on-Debian-Ubuntu-Linux
Lets say you’re like me and you have an old but gold USB device like USB joystick Maxfire G-08XU (i've described how to configure Joystick / Gamepad on Debian Ubuntu easily), an USB flash drive stick or even some obscure USB keyboard model, that are not among the most compatible device on earth for linux. The result is in device plug and Sleeping the system or Hibernating it for a while (when go to bed) you end up with USB device being undetected by the system. Once you recover the Laptop / PC from being in Sleep mode / hibernate, the device becomes undetected by system, even though, even though the Linux kernel recognizes in lsusb. That weirdity continues until you do the manual hard workaround, which is to manually unplug the device cable and replug it again.
Though Linux has advanced much with this stuff over last years still this problems can occur every now and then. Thanksfully there is a quick fix to that. You can create a small script that reloads all the USB devices on PC
want the script to run automatically after your Debian laptop wakes up from suspend/hibernate. On Linux, the way to do this is using systemd sleep hooks. Here’s how to do it properly by using a small script + systemd.

1. Create a systemd sleep script

Create a new directory and file:

# mkdir -p /etc/systemd/system-sleep
# vim /etc/systemd/system-sleep/usb-replug.sh

Add this content:

#!/bin/bash
# Only run on resume (wake up)
case "$1" in
post)
# Replace '1-3' with your USB bus-port ID
echo '1-3' | tee /sys/bus/usb/drivers/usb/unbind
sleep 2
echo '1-3' | tee /sys/bus/usb/drivers/usb/bind
;;
esac
If 


If you need script logging use instead this small script:

 

#!/bin/bash

case $1/$2 in
pre/*)
# before suspend: you can put commands here if needed
;;
post/*)
# after resume: run your USB replug commands
echo "$(date) – Running USB replug script" >> /var/log/usb-replug.log
# Example command: trigger USB rescan
for bus in /sys/bus/usb/devices/*/authorized; do
echo 0 | sudo tee $bus
echo 1 | sudo tee $bus
done
;;
esac

2. Make it executable and reload systemd services

# chmod +x /etc/systemd/system-sleep/usb-replug.sh

Once you’ve created the script in /etc/systemd/system-sleep/ and made it executable, systemd will automatically call it on suspend/resume.

To make sure everything is recognized, you can:

  1. Reload systemd units (optional but recommended)

# systemctl daemon-reload
  1. Test it manually by suspending and resuming your machine

# systemctl suspend

After resuming, your script should run automatically and you should see the missing devices that you had to physically unplug and plug back to normal.
Hooray ! 🙂

3. How it works (systemd respawn)

  • systemd runs scripts in /etc/systemd/system-sleep/ on suspend and resume.

  • $1 is either pre (before sleep) or post (after wake).

  • The script unbinds and rebinds your USB device right after the system resumes.

Tip: You can also use usbreset instead of unbind/bind if you prefer, just replace the echo lines with:

# usbreset /dev/bus/usb/001/005

Alternatively you can use one time a simple one liner script that does the job like this:
 

# cat replug_usbs_linux.sh
#!/bin/bash

# one liner script to replug all USB devices like you have physically replugged all USBs useful if for example some of USB devices stuck after linux computer sleep

# for example my old maxfire g-08 usb joystick does mess up and i have to physically replug it (to work around this i simply run this script

d=$(lsusb -t | grep -m1 'Driver=' | sed -E 's|.*Port ([0-9]+):.*Bus ([0-9]+).*|\2-\1|') && echo $d | sudo tee /sys/bus/usb/drivers/usb/unbind && sleep 2 && echo $d | sudo tee /sys/bus/usb/drivers/usb/bind

 

How I Stopped My AWS workspace Linux Desktop From Going to Sleep… Without Root Access

Thursday, November 20th, 2025

keeping-session-alive-stop-aws-workspace-to-auto-suspend-with-systemd-inhibit-or-a-simple-loop-scriptcover

If you've spent enough time around Linux servers and desktops, you already know one universal truth:

Linux never does exactly what you expect… especially when you don’t have root.

A few weeks ago, I found myself in a situation that’s probably familiar to anyone who works on shared servers, university machines, or restricted corporate environments:

My session kept going to sleep, killing long-running scripts, dropping SSH tunnels, freezing terminals—for absolutely no good reason.

To make things worse, I didn’t have sudo on this box.
No changing systemd settings, no tweaking /etc/systemd/logind.conf, and definitely no masking sleep targets.

So I went down the rabbit hole of how to keep a Linux machine awake without any superuser privileges.
Here’s the write-up of that journey—and yes, the final solution is surprisingly elegant.

The Problem: When the System Sleeps, Your Work Dies

My main issue: every 15 minutes of inactivity, the system would suspend the session.
Not the entire PC — just my user session. It didn't matter if I had background jobs running or SSH tunnels open; if I wasn’t interacting, the session was toast.

The machines were managed centrally, so root was a luxury I simply didn’t have.

What followed was a typical sysadmin debugging sequence:

  1. Angry at the stupidity
  2. Google.
  3. Try things that shouldn’t work.
  4. Try things that definitely shouldn't work.
  5. Accidentally discover the correct solution while reading some random docs if point 3 doesn’t already solve it

The Trick: systemd-inhibit (Works Without Root!)

While digging through the systemd documentation, I discovered something beautiful:

Non-root users can create inhibitor locks.

This means your normal user account can ask systemd:
Please don’t put this session to sleep while this program is running.”

And systemd says:
“Okay. I respect that.”

All it takes is:

systemd-inhibit –what=handle-lid-switch:sleep –mode=block sleep infinity

This command runs a never-ending sleep process—
and while it runs, the system is forbidden to suspend.

You can even run it in the background:

$ nohup systemd-inhibit sleep infinity &

Want to verify it’s working?

$ systemd-inhibit –list

You’ll see your inhibitor lock listed like a VIP pass at a nightclub.

If You Have caffeinate, Even Better

Some Linux distros ship with a utility called caffeinate (similar to macOS).
It’s almost poetic:

$ caffeinate -di sleep infinity

This one also blocks sleep while the command runs.
Just leave it running as a background job and your session stays alive.

The Primitive but Always-Working Hack: Keepalive Script

If neither systemd-inhibit nor caffeinate exist, you can fall back to a caveman approach and still have the basic functionality of the Move Mouse Windows tool on Linux :):
 

#!/bin/bash

while true; do

    echo "Still here: $(date)"

    sleep 60

done

This prevents session idleness by emitting activity every minute.
Not elegant, but reliable.

Sometimes the caveman wins.

Why This Matters

Keeping a session awake might sound trivial, but for sysadmins, developers, pentesters, researchers, or anyone running long processes on managed machines, it’s a lifesaver.

You avoid:

  • broken SSH tunnels
  • silent failure of long-running scripts
  • GUI sessions locking themselves
  • losing tmux/screen sessions
  • interrupted compiles or renders
  • VPN disconnects

And you don’t need to bug IT or break policy.

Final Thoughts

What surprised me most is how simple the final solution was:

  • No root
  • No configuration changes
  • No hacks
  • No kernel tweaks

Just one systemd command used properly.

Sometimes Linux feels like an inscrutable labyrinth… and sometimes it gives you a quiet, elegant tool hiding in plain sight.

If you ever find yourself fighting unwanted auto-suspend on a machine you don’t control –
give systemd-inhibit a try.

Generate and Use WiFi passwords via QR code on Linux

Monday, November 17th, 2025

If you’re running a WiFi network for a guest house / AirBNB, a small hotel or an office / home network and you’re tired of telling / dictating guests your long, complicated Wi-Fi password every time they visit, there’s a simple and secure way to share the WiFi name and password by putting the info in a WiFi authentication QR code. With a simple scan from their phone via a QR reader (which iPhones and all modern smartphones have), they can join your network instantly with zero typing.

In short — Why use a QR Code for Wi-Fi?

  • Convenience for guests: No more reading or spelling out your SSID and password.
  • Better security practice: Keep a strong password while still making access easy.
  • Works on most devices: Android and iOS both support Wi-Fi QR codes.

The Wi-Fi QR Code Standard Format

Smartphones understand Wi-Fi QR codes using this format:

WIFI:S:;T:;P:;;

  • S: your Wi-Fi network name (SSID)
  • T: encryption type (WPA, WEP, or nopass)
  • P: your Wi-Fi password
  • Everything ends with ;;

If your SSID or password contains special characters such as ; or \, they must be escaped using a backslash \.

Example:

SSID = WifiNetworkName
Password = @ss;word45123P4?#$!
Type = WPA

The final string becomes:

WIFI:S:WifiNetworkName;T:WPA;P:@ss\;word45123P4?#$!;;

How to Generate the QR Code Locally on Linux

You can generate the QR code locally using qrencode instead of uploading credentials online.

  1. Install qrencode (Debian/Ubuntu):

    # apt update # apt install qrencode

  2. Generate the QR code:

    # qrencode -o wifi-qr.png 'WIFI:S:WifiNetwork;T:WPA;P:P@ss\;word!;;'

    Example with colors and SVG output:

    # qrencode -t svg –foreground=FFFFFF –background=000000 \ -o qr-code.svg –inline –rle -s 10 \ "WIFI:S:MyWiFI;T:WPA;P:<Secret_Pass>;;"

    Use -s to increase size, e.g. -s 10.

  3. Print or share the generated wifi-qr.png.

Alternative: GUI / Desktop Approach

On GNOME-based systems (Ubuntu, Fedora), install the WiFi QR Code GNOME extension.

  • Open quick settings → Wi-Fi → “Show QR Code”
  • Right-click to copy or save for printing

Advanced: Using wifi-qr Tool

The wifi-qr tool provides CLI and GUI Wi-Fi QR generation.

# terminal interface to generate QR
# wifi-qr -t

wifi-qr screenshot

This command prints your current Wi-Fi SSID, encryption type, and password in clear text.

Security Tips

  • Limit where you display the QR
  • Rotate the password when needed
  • Use a guest network instead of your main one
  • Prefer WPA2/WPA3
  • Store QR images safely

How Guests Use the QR Code

  1. Open the phone camera (iOS/Android)
  2. Point it at the QR
  3. Tap “Join” when the Wi-Fi prompt appears

Final Thoughts

Generating a Wi-Fi QR code blends security with usability. Whether using qrencode, a GUI extension, or a website, guests connect instantly with a quick scan – no typing required.

How to Set Up SSH Two-Factor Authentication (2FA) on Linux Without Google Authenticator with OATH Toolkit

Wednesday, November 5th, 2025

install-2-factor-free-authentication-google-authentication-alternative-with-oath-toolkit-linux-logo

Most tutorials online on how to secure your SSH server with a 2 Factor Authentication 2FA will tell you to use Google Authenticator to secure SSH logins.

But what if you don’t want to depend on Google software – maybe for privacy, security, or ideological reasons ?

Luckily, you have a choice thanks to free oath toolkit.
The free and self-hosted alternative: OATH Toolkit has its own PAM module  libpam-oath to make the 2FA work  the openssh server.

OATH-Toolkit is a free software toolkit for (OTP) One-Time Password authentication using HOTP/TOTP algorithms. The software ships a small set of command line utilities covering most OTP operation related tasks.

In this guide, I’ll show you how to implement 2-Factor Authentication (TOTP) for SSH on any Linux system using OATH Toolkit, compatible with privacy-friendly authenticator apps like FreeOTP, Aegis, or and OTP.

It is worthy to check out OATH Toolkit author original post here, that will give you a bit of more insight on the tool.

1. Install the Required Packages

For Debian / Ubuntu systems:

# apt update
# apt install libpam-oath oathtool qrencode
...

For RHEL / CentOS / AlmaLinux:
 

# dnf install pam_oath oathtool

The oathtool command lets you test or generate one-time passwords (OTPs) directly from the command line.

2. Create a User Secret File

libpam-oath uses a file to store each user’s secret key (shared between your server and your phone app).

By default, it reads from:

/etc/users.oath

Let’s create it securely and set proper permissions to secure it:
 

# touch /etc/users.oath
# chmod 600 /etc/users.oath

Now, generate a new secret key for your user (replace hipo with your actual username):
 

# head -10 /dev/urandom | sha1sum | cut -c1-32

This generates a random 32-character key.
Example:

9b0e4e9fdf33cce9c76431dc8e7369fe

Add this to /etc/users.oath in the following format:

HOTP/T30 hipo - 9b0e4e9fdf33cce9c76431dc8e7369fe

HOTP/T30 means Time-based OTP with 30-second validity (standard TOTP).

Replace hipo with the Linux username you want to protect.

3. Add the Key to Your Authenticator App

Now we need to add that secret to your preferred authenticator app.

You can create a TOTP URI manually (to generate a QR code):

$ echo "otpauth://totp/hipo@jericho?secret=\
$(echo 9b0e4e9fdf33cce9c76431dc8e7369fe \
| xxd -r -p | base32)"

You can paste this URI into a QR code generator (e.g., https://qr-code-generator.com) and scan it using FreeOTP , Aegis, or any open TOTP app.
The FreeOTP Free Ap is my preferred App to use, you can install it via Apple AppStore or Google Play Store.

Alternatively, enter the Base32-encoded secret manually into your app:

# echo 9b0e4e9fdf33cce9c76431dc8e7369fe | xxd -r -p | base32

You can also use qrencode nice nifty tool to generate out of your TOTP code in ASCII mode and scan it with your Phone FreeOTP / Aegis App and add make it ready for use:

# qrencode –type=ANSIUTF8 otpauth://totp/hipo@jericho?secret=$( oathtool –verbose –totp 9b0e4e9fdf33cce9c76431dc8e7369fe –digits=6 -w 1 | grep Base32 | cut -d ' ' -f 3 )\&digits=6\&issuer=pc-freak.net\&period=30

qrencode-generation-of-scannable-QR-code-for-freeotp-or-other-TOTP-auth

qrencode will generate the code. We set the type to ANSI-UTF8 terminal graphics so you can generate this in an ssh login. It can also generate other formats if you were to incorporate this into a web interface. See the man page for qrencode for more options.
The rest of the line is the being encoded into the QR code, and is a URL of the type otpauth, with time based one-time passwords (totp). The user is “hipo@jericho“, though PAM will ignore the @jericho if you are not joined to a domain (I have not tested this with domains yet).

The parameters follow the ‘?‘, and are separated by ‘&‘.

otpauth uses a base32 hash of the secret password you created earlier. oathtool will generate the appropriate hash inside the block:

 $( oathtool –verbose –totp 9b0e4e9fdf33cce9c76431dc8e7369fe | grep Base32 | cut -d ' ' -f 3 )

We put the secret from earlier, and search for “Base32”. This line will contain the Base32 hash that we need from the output:

Hex secret: 9b0e4e9fdf33cce9c76431dc8e7369fe
Base32 secret: E24ABZ2CTW3CH3YIN5HZ2RXP
Digits: 6
Window size: 0
Step size (seconds): 30
Start time: 1970-01-01 00:00:00 UTC (0)
Current time: 2022-03-03 00:09:08 UTC (1646266148)
Counter: 0x3455592 (54875538)

368784 
From there we cut out the third field, “E24ABZ2CTW3CH3YIN5HZ2RXP“, and place it in the line.

Next, we set the number of digits for the codes to be 6 digits (valid values are 6, 7, and 8). 6 is sufficient for most people, and easier to remember.

The issuer is optional, but useful to differentiate where the code came from.

We set the time period (in seconds) for how long a code is valid to 30 seconds.

Note that: Google authenticator ignores this and uses 30 seconds whether you like it or not.

4. Configure PAM to Use libpam-oath

Edit the PAM configuration for SSH:

# vim /etc/pam.d/sshd

At the top of the file, add:

auth required pam_oath.so usersfile=/etc/users.oath window=30 digits=6

This tells PAM to check OTP codes against /etc/users.oath.

5. Configure SSH Daemon to Ask for OTP

Edit the SSH daemon configuration file:
 

# vim /etc/ssh/sshd_config

Ensure these lines are set:
 

UsePAM yes
challengeresponseauthentication yes
ChallengeResponseAuthentication yes
AuthenticationMethods publickey keyboard-interactive
##KbdInteractiveAuthentication no
KbdInteractiveAuthentication yes

N.B.! The KbdInteractiveAuthentication yes variable is necessery on OpenSSH servers with version > of version 8.2_ .

In short This setup means:
1. The user must first authenticate with their SSH key (or local / LDAP password),
2. Then enter a valid one-time code generated from TOTP App from their phone.

You can also use  Match  directives to enforce 2FA under certain conditions, but not under others.
For example, if you didn’t want to be bothered with it while you are logging in on your LAN,
but do from any other network, you could add something like:

Match Address 127.0.0.1,10.10.10.0/8,192.168.5.0/24
Authenticationmethods publickey

6. Restart SSH and Test It

Apply your configuration:
 

# systemctl restart ssh

Now, open a new terminal window and try logging in (don’t close your existing one yet, in case you get locked out):

$ ssh hipo@your-server-ip

You should see something like:

Verification code:

Enter the 6-digit code displayed in your FreeOTP (or similar) app.
If it’s correct, you’re logged in! Hooray ! 🙂

7. Test Locally and Secure the Secrets

If you want to test OTPs manually with a base32 encrypted output of hex string:

# oathtool --totp -b \
9b0e4e9fdf33cce9c76431dc8e7369fe

As above might be a bit confusing for starters, i recommend to use below few lines instead:

$ secret_hex="9b0e4e9fdf33cce9c76431dc8e7369fe"
$ secret_base32=$(echo $secret_hex | xxd -r -p | base32)
$ oathtool –totp -b "$secret_base32"
156874

You’ll get the same 6-digit code your authenticator shows – useful for debugging.

If you rerun the oathtool again you will get a difffefrent TOTP code, e.g. :

$ oathtool –totp -b "$secret_base32"
258158


Use this code as a 2FA TOTP auth code together with local user password (2FA + pass pair),  when prompted for a TOTP code, once you entered your user password first.

To not let anyone who has a local account on the system to be able to breach the 2FA additional password protection,
Ensure the secrets file is protected well, i.e.:

# chown root:root /etc/users.oath
# chmod 600 /etc/users.oath

How to Enable 2FA Only for Certain Users

If you want to force OTP only for admins, create a group ssh2fa:

# groupadd ssh2fa
# usermod -aG ssh2fa hipo

Then modify /etc/pam.d/sshd:

auth [success=1 default=ignore] pam_succeed_if.so \
user notingroup ssh2fa
auth required pam_oath.so usersfile=/etc/users.oath \
window=30 digits=6

Only users in ssh2fa will be asked for a one-time code.

Troubleshooting

Problem: SSH rejects OTP
Check /var/log/auth.log or /var/log/secure for more details.
Make sure your phone’s time is in sync (TOTP depends on accurate time).

Problem: Locked out after restart
Always keep one root session open until you confirm login works.

Problem: Everything seems configured fine but still the TOTP is not accepted by remote OpenSSHD.
– Check out the time on the Phone / Device where the TOTP code is generated is properly synched to an Internet Time Server
– Check the computer system clock is properly synchornized to the Internet Time server (via ntpd / chronyd etc.), below is sample:

  • hipo@jeremiah:~$ timedatectl status
                   Local time: Wed 2025-11-05 00:39:17 EET
               Universal time: Tue 2025-11-04 22:39:17 UTC
                     RTC time: Tue 2025-11-04 22:39:17
                    Time zone: Europe/Sofia (EET, +0200)
    System clock synchronized: yes
                  NTP service: n/a
              RTC in local TZ: no

Why Choose libpam-oath?

  • 100% Free Software (GPL)
  • Works completely offline / self-hosted
  • Compatible with any standard TOTP app (FreeOTP, Aegis, andOTP, etc.)
  • Doesn’t depend on Google APIs or cloud services
  • Lightweight (just one PAM module and a text file)

Conclusion

Two-Factor Authentication doesn’t have to rely on Google’s ecosystem.
With OATH Toolkit and libpam-oath, you get a simple, private, and completely open-source way to harden your SSH server against brute-force and stolen-key attacks.

Once configured, even if an attacker somehow steals your SSH key or password, they can’t log in without your phone’s one-time code – making your system dramatically safer.

How to Install and Use Netdata on Debian / Ubuntu Linux for Real-Time Server Monitoring

Wednesday, October 29th, 2025

netdata-server-monitoring-simple-tool-for-linux-bsd-windows

Monitoring system performance is one of the most overlooked aspects of server administration – until something breaks. That is absolutely true for beginners and home brew labs for learnings on how to manage servers and do basic system administration. For novice monitoring servers and infrastructure is not a big deal as usually testing machines are OK to break things. But still if you happen to host yourself some own brew websites a blog or Video streaming servers a torrent server, a tor server, some kind of public proxy or whatever of community advantageous solution for free at home, then monitoring will become important topic at some time when your small thing becomes big.

 While many sysadmins reach for Prometheus or Zabbix, using those comes with much of a complexity and effort to put in installing + setting up the overall server and agent clients as well as configure different monitoring checks.

Anyways sometimes you just need a lightweight, zero-configuration server monitoring tool that gives you instant visibility and you don’t want to learn much to have the basic and a bit of heuristic monitoring in the house.

That’s where Netdata shines.

What is Netdata?

Netdata is an open-source, real-time performance monitoring tool that visualizes CPU, memory, disk, network, and process metrics directly in your browser. It’s written in C and optimized for minimal overhead, making it perfect for both old hardware and modern VPS setups.

Netdata is built to primarly monitor different Linux OS distributions such as CentOS / RHEL / AlmaLinux / Rocky Linux / OpenSuse / Arch Linux / Amazon Linux and Oracle Linux it also has support for Windows OS as well as partially supports Mac OS and FreeBSD / OpenBSD / Dragonfly BSD and some other BSDs but some of its Linux features are not available on those.

1. Install Netdata real time performance monitoring tool


root@pcfreak:~# apt-cache show netdata|grep -i description -A3

Description-en: real-time performance monitoring (metapackage)

 Netdata is distributed, real-time, performance and health monitoring for

 systems and applications. It provides insights of everything happening on the

 systems it runs using interactive web dashboards.

Description-md5: 6843dd310958e94a27dd618821504b8e

Homepage: https://github.com/netdata/netdata

Section: net

Priority: optional

Netdata runs on most Linux distributions. On Debian or Ubuntu, installation is dead simple:

# apt update

# apt install curl -y


To be with the latest version since the default repositories provide usually older release you can use for install directly the kickstart installer from netdata.

# bash <(curl -Ss https://my-netdata.io/kickstart.sh)

This script automatically installs dependencies, sets up the Netdata daemon, and enables it as a systemd service.

Once installed, Netdata starts immediately. You can verify with:

# systemctl status netdata

2. Access the Web Dashboard


Open your browser and navigate to:

http://your-server-ip:19999/

You’ll be greeted by an intuitive dashboard showing real-time graphs of every aspect of your system — CPU load, memory usage, disk I/O, network bandwidth, and more.

If you’re running this on a public server, make sure to secure access with a firewall or reverse proxy, since by default Netdata is open to all IPs.

Example (UFW):

# ufw allow from YOUR.IP.ADDRESS.HERE to any port 19999

# ufw enable

3. Enable Persistent Storage

By default, Netdata stores only live data in memory. To retain historical data:
 

# vim /etc/netdata/netdata.conf

Find the [global] section and modify:

[global]

  history = 86400

  update every = 1

This keeps 24 hours of data at one-second resolution. You can also connect Netdata to a database backend for long-term archiving.

4. Secure with Basic Auth (Optional)

If you want simple password protection:

# apt install apache2-utils

# htpasswd -c /etc/netdata/.htpasswd admin

Then edit /etc/netdata/netdata.conf to include:

[web]

  mode = static-threaded

  default port = 19999

  allow connections from = localhost 192.168.1.*

  basic auth users file = /etc/netdata/.htpasswd

Restart Netdata:

# systemctl restart netdata

Why Netdata is Awesome 

Unlike Prometheus or Grafana, Netdata gives you instant insights without heavy setup. It’s ideal for:

  • Debugging high load or memory leaks in real time
  • Monitoring multiple VPS or embedded devices
  • Visualizing system resource usage with minimal CPU cost

And because it’s written in C, it’s insanely fast — often using less than 1% CPU on idle systems.

Final Thoughts

If you’re running any Linux server – whether for personal projects, web hosting, or experiments – Netdata is one of the easiest ways to visualize what’s happening under the hood.

You can even integrate it into your homelab or connect multiple nodes to the Netdata Cloud for centralized monitoring. And of course the full featured use and all the features of the tool are available just in the cloud version but that is absolutely normal. As the developers of netdata seems to have adopted the usual business model of providing things for free and same time selling another great things to make cash.

Netdata is really cool solution without cloud for people who needs to be able to quickly monitor like 20 or 50 servers without putting too much effort. You can simply install it across the machines and you will get a plenty of monitoring, just open each of the machines inside a separate browser tabs and take a look at what is going on once or 2 times a day. It is very old fashioned way to do monitoring but still can make sense if you don't want to bother too much with developing the monitoring or put any effort in it but still have a kind of obeservability on your mid size computer infrastructure.

So, next time your VPS feels sluggish or your load average spikes, fire up Netdata — your CPU will tell you exactly what’s wrong.

How to boost Linux Server Speed with tmpfs and few smart Optimization tweaks

Monday, October 20th, 2025

speed-up-accelerate-wordpress-joomla-drupal-cms-and-mysql-server-with-tmpfs_ramfs_decrease-pageload-times-with-ram-caching.png

If you’ve ever managed a busy Linux server, you’ve probably noticed how I/O bottlenecks can make your system feel sluggish – even when CPU and memory usage look fine. I recently faced this problem on a Debian box running Nginx, PHP-FPM, and MySQL / MariaDB. The fix turned out to be surprisingly simple: using tmpfs for temporary directories and tweaking a few kernel parameters.

1. Identify the resource issue Bottleneck

Running iostat -x 1 showed my /var/lib/mysql drive constantly pegged at 100% utilization, while CPU load stayed low. Classic disk-bound performance issue.

I checked swap usage:

# swapon –show

# free -h

The system was swapping occasionally — not good for performance-critical workloads.

2. Use tmpfs for Cache and Temporary Files

Linux allows you to use part of your RAM as a fast, volatile filesystem. Perfect for things like cache and sessions.

I edited /etc/fstab and added:

tmpfs   /tmp            tmpfs   defaults,noatime,mode=1777,size=1G  0  0

tmpfs   /var/cache/nginx tmpfs  defaults,noatime,mode=0755,size=512M 0 0

Then:

# mount -a

Immediately, I noticed fewer disk I/O spikes. Nginx’s cache hits were lightning-fast, and PHP temporary files were written in memory instead of SSD.

3. Tune Kernel Parameters

Adding these lines to /etc/sysctl.conf helped reduce swapping and improve responsiveness:

vm.swappiness=10

vm.vfs_cache_pressure=50

Then apply:

# sysctl -p

4. Use tmpfs for MySQL / MariaDB tmpdir (Optional)

If you have enough RAM, move MySQL’s temporary directory to tmpfs:

# mkdir -p /mnt/mysqltmp

# mount -t tmpfs -o size=512M tmpfs /mnt/mysqltmp

# chown mysql:mysql /mnt/mysqltmp

Then set in /etc/mysql/my.cnf: / /etc/mysql/mariadb.cnf

tmpdir = /mnt/mysqltmp

This dramatically speeds up large sorts and temporary table creation.

5. Monitor the Effects and tune up if necessery

After applying these changes, iostat showed disk utilization dropping from 95% to under 20% under the same workload.
Average response times from Nginx dropped by around 30–40%, and the server felt much more responsive.
However other cases might be different so it is a good idea to play around with tmpfs side according to your CPU / Memory system parameters etc. and find out the best values that would fit your Linux setup best.

Short rephrasal

tmpfs is one of those underused Linux features that can make a real-world difference for sysadmins and self-hosters. Just remember that data in tmpfs disappears after reboot, so only use it for volatile data (cache, temp files, etc.).

If you’re running a VPS or small dedicated box and looking for a quick, low-cost performance boost — give tmpfs a try. You might be surprised how much smoother your system feels.

 

Optimizing Linux Server Performance Through Digital Minimalism and Running Services and System Cleanup

Friday, October 3rd, 2025

linux-logo-optimizing-linux-server-performance-digital-minimalism-software-cleanup

In today’s landscape of bloated software stacks, automated dependency chains, and background services that consume memory and CPU without notice, Linux system administrators and enthusiasts alike benefit greatly from embracing digital minimalism of what is setup on the server and to reduce it to the absolute minimum.

Digital minimalism in the context of Linux servers means removing what you don't need, disabling what you don't use, and optimizing what remains — all with the goal of increasing performance, improving security, and simplifying further maintenance.
In this article, we’ll walk through practical steps to declutter your Linux server, optimize resources, and regain control over what’s running and why.

1. Identify and Remove Unnecessary Packages

Over time, many systems accumulate unused packages — either from experiments, dependency installations, or unnecessary defaults.

On Debian/Ubuntu

Find orphaned packages:
 

# apt autoremove --dry-run


Remove unnecessary packages:
 

# apt autoremove
# apt purge <package-name>


List large installed packages:

# dpkg-query -Wf '${Installed-Size}\t${Package}\n' | sort -n | tail -n 20


On RHEL/CentOS/AlmaLinux:

Find orphaned packages:

# dnf autoremove

List packages sorted by size:

# rpm -qia --qf '%{SIZE}\t%{NAME}\n' | sort -n | tail -n 20


2. Audit and Disable Unused Services
 

Every running service consumes memory, CPU cycles, and opens potential attack surfaces.

List enabled services:
 

# systemctl list-unit-files --type=service --state=enabled

See currently running services:

# systemctl --type=service –state=running

Put some good effort to review and disable all unnecesssery

 

Disable unneeded services :

# systemctl disable --now bluetooth.service
# systemctl disable --now cups.service
# systemctl disable --now ModemManager.service

And so on

Useful services to disable (if unused):
 

Service

Purpose

When to Disable

cups.service

Printer daemon

On headless servers

bluetooth.service

Bluetooth stack

On servers without Bluetooth

avahi-daemon

mDNS/Zeroconf

Not needed on most servers

ModemManager

Modem management

If not using 3G/4G cards

NetworkManager

Dynamic net config

Prefer systemd-networkd for static setups


Simple Shell Script to List & Review Services
 

#!/bin/bash
echo "Enabled services:"
systemctl list-unit-files --state=enabled | grep service
echo ""
echo "Running services:"
systemctl --type=service --state=running

3. Optimize Startup and Boot Time

Analyze system boot performance:

# systemd-analyze

View which services take the longest:

# systemd-analyze blame
min 25.852s certbot.service
5min 20.466s logrotate.service
1min 29.748s plocate-updatedb.service
54.595s php5.6-fpm.service
43.445s systemd-logind.service
42.837s e2scrub_reap.service
37.915s apt-daily.service
35.604s mariadb.service
31.509s man-db.service
27.405s systemd-journal-flush.service
18.357s ifupdown-pre.service
14.672s dev-xvda2.device
13.523s rc-local.service
11.024s dpkg-db-backup.service
9.871s systemd-sysusers.service
...

 

Disable or mask long-running services that are not essential.


Why services masking is important?


Simply because after some of consequential updates, some unwanted service daemon might start up with the system boot.

Example:
 

# systemctl mask lvm2-monitor.service


4. Reduce Memory Usage (Especially on Low-RAM VPS)
 

Monitor memory usage:

# free -h
# top
# htop

Use lightweight alternatives:

Service

Heavy

Lightweight Alternative

Web server

Apache

Nginx / Caddy / Lighttpd

Database

MySQL

MariaDB / SQLite (if local)

Syslog

rsyslog

busybox syslog / systemd journal

Shell

bash

dash / ash

File manager

GNOME Files

mc / ranger (CLI)


5. Configure Swap (Only If Needed)
 

Having too much or too little swap can affect performance.


Check if swap is active:

# swapon --show


Create swap file (if needed):

# fallocate -l 1G /swapfile
# chmod 600 /swapfile
# mkswap /swapfile
# swapon /swapfile

Add to /etc/fstab for persistence:

/swapfile none swap sw 0 0

6. Clean Up Cron Jobs and Timers

Old scheduled tasks can silently run in the background and consume resources.

List user cron jobs:

crontab -l

Check system-wide cron jobs:

# ls /etc/cron.*
# ls -al /var/spool/cron/*


List systemd timers:

# systemctl list-timers


Disable any unneeded timers or outdated cron entries.

7. Optimize Logging and Log Rotation

Logs are essential but can grow large and fill up disk space quickly.

Check log size:

# du -sh /var/log/*

Force logrotate:
 

# logrotate -f /etc/logrotate.conf

Edit /etc/logrotate.conf or specific files in /etc/logrotate.d/* to reduce retention if needed.

8. Check for Zombie Processes and Old Users

Old users and zombie processes can indicate neglected cleanup or the server is (cracked) hacked.

List users:
 

cat /etc/passwd | cut -d: -f1

Remove unused accounts:
 

# userdel -r username


Check for zombie processes:
 

# ps aux | awk '{ if ($8 == "Z") print $0; }'

9. Disable IPv6 (if not used)

IPv6 can add unnecessary complexity and attack surface if you’re not using it.

To disable IPv6 temporarily:

# sysctl -w net.ipv6.conf.all.disable_ipv6=1
# sysctl -w net.ipv6.conf.default.disable_ipv6=1

To disable permanently, add to /etc/sysctl.conf:

net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1


10. Final Thoughts: Less Is More

Digital minimalism is not just a personal tech trend — it's a philosophy of clarity, performance, and security. Every running process is a potential vulnerability. Every megabyte of RAM consumed by a useless service is wasted capacity. Every package installed increases the system’s complexity.

By regularly auditing, pruning, and simplifying your Linux server, you not only improve its performance and reliability, but you also reduce future maintenance headaches.

Minimalism = Maintainability.

Implementing and using gssproxy, example guide on how to use it to authenticate ssh, samba, nfs with no password via kerberos protocol

Friday, September 26th, 2025

Implementing and using gssproxy, example guide on how to use it to authenticate ssh, samba, nfs with no password via kerberos protocol

GSS-Proxy is a daemon that safely performs GSSAPI (Kerberos) operations on behalf of other processes. It’s useful when services running as unprivileged users need to accept or initiate Kerberos GSSAPI authentication but shouldn’t hold or access long‑lived keys (keytabs) or raw credentials themselves. Typical users: OpenSSH, SSSD, Samba, NFS idmap, and custom daemons.

This article walks through what gssproxy does, how it works, how to install and configure it, example integrations (sshd and an unprivileged service), testing, debugging and common pitfalls.
 

1. What gssproxy does (quick conceptual summary)
 

  • Runs as a privileged system daemon (typically root) and holds access to keytabs or system credentials.
  • Exposes a local IPC (Unix socket) and controlled API so allowed clients can ask it to perform GSSAPI accept/init operations on their behalf.
  • Enforces access controls by client PID/user and by named service configuration (you map a client identity to the allowed service name and keytab).
  • Minimizes the need to distribute keytabs or give services direct access to Kerberos credentials.
     

2. Installation

On many modern Linux distributions (Fedora, RHEL/CentOS, Debian/Ubuntu) gssproxy is packaged.

Example (RHEL/Fedora/CentOS):

# RHEL/CentOS 7/8/9 (dnf or yum)

 

sudo dnf install gssproxy

 

# or

 

sudo yum install gssproxy

Example (Debian/Ubuntu):

sudo apt update

sudo apt install gssproxy

If you must build from source:

# get source, then typical autotools or meson/ninja workflow per upstream README

./configure

make

sudo make install

 

After install, systemd unit gssproxy.service should be available.
 

3. Main configuration concepts

The main config file is usually /etc/gssproxy/gssproxy.conf. It consists of mechs (mechanisms), services, clients, and possibly mappings. Key elements:

  • mech: declares a GSSAPI mechanism (e.g., krb5) and default keytab(s) for acceptor credentials.
  • service: logical service names (e.g., ssh, nfs, httpd) with attributes: user (the Unix user running the service), keytab, cred_store, mechs, and whether the service is allowed to be client (initiate) and/or server (accept).
  • client: rules mapping local client sockets / users / pids to allowed services.

A minimal working example that allows sshd to use gssproxy:

mechs = {

    krb5_mech = {

        mech = krb5;

        default_keytab = /etc/krb5.keytab;

    };

};

 

services = {

    ssh = {

        mech = krb5_mech;

        user = "sshd";

        keytab = /etc/krb5.keytab;

        # allow both acceptor (server) and initiator (client) ops if needed

        client = yes;

        server = yes;

    };

};

Client rules are often implicit: gssproxy can enforce that calls on a given service socket originate from the configured Unix user. For more complex setups you add policy and client blocks. Example to allow a specific PID or user to use the ssh service:

clients = {

    ssh_clients = {

        clients = [

            { match = "uid:0" },      # root can ask for ssh service

            { match = "user:sshd" },  # or the sshd user

        ];

        service = "ssh";

    };

};

Paths and sockets: gssproxy listens on a socket (e.g. /var/run/gssproxy/socket) and possibly per-user sockets (e.g. /run/gssproxy/uid_1000). The systemd unit usually creates the runtime directory with correct permissions.
 

4. Example: Integrate with OpenSSH server (sshd)

Goal: allow sshd and session processes to accept delegated GSS credentials and let unprivileged child processes use those credentials via gssproxy.

Server side config

  1. Ensure sshd is built/installed with GSSAPI support. On SSH server:

    • In /etc/ssh/sshd_config:
    • GSSAPIAuthentication yes
    • GSSAPICleanupCredentials yes
    • GSSAPIKeyExchange yes        # optional: if you want GSS key exchange
  2. Configure gssproxy with an ssh service entry pointing to the host keytab (so gssproxy can accept SPNEGO/kerberos accept_sec_context calls):

mechs = {

    krb5 = {

        mech = krb5;

        default_keytab = /etc/krb5.keytab;

    };

};

 

services = {

    ssh = {

        mech = krb5;

        user = "sshd";

        keytab = /etc/krb5.keytab;

        server = yes;

        client = yes;

    };

};

  1. Ensure /etc/krb5.keytab contains the host principal host/fqdn@REALM (or host/short@REALM depending on SPN strategy). Use ktutil or kadmin to create/populate.
  2. Restart gssproxy and sshd:

sudo systemctl restart gssproxy

sudo systemctl restart sshd

Client side

  • ssh client configuration (usually ~/.ssh/config or /etc/ssh/ssh_config):

Host myhost.example.com

    GSSAPIAuthentication yes

    GSSAPIDelegateCredentials yes

Client must have a TGT in the credential cache (kinit user), or use a client that acquires one.

Result

When the client initiates GSSAPI authentication and delegates credentials (GSSAPIDelegateCredentials yes or -K for older OpenSSH), gssproxy on the server handles acceptor functions. If a session process needs to use the delegated credentials (e.g., to access network resources as that user), gssproxy arranges a per-session credential store that unprivileged processes can use via the kernel keyring or other mechanisms gssproxy supports.
 

5. Example: Allow an unprivileged service to acquire initiator creds via gssproxy

Suppose a service mydaemon runs as myuser and needs to initiate Kerberos-authenticated connections using a specific service principal stored in /etc/mydaemon.keytab but you don’t want to expose that keytab to myuser.

Add a mech and service:

mechs = {

    krb5 = {

        mech = krb5;

        default_keytab = /etc/krb5.keytab;

    };

    mydaemon_mech = {

        mech = krb5;

        default_keytab = /etc/mydaemon.keytab;

    };

};

 

services = {

    mydaemon = {

        mech = mydaemon_mech;

        user = "myuser";

        keytab = /etc/mydaemon.keytab;

        client = yes;    # allow initiator operations

        server = no;

    };

};

Configure a client mapping so the mydaemon process (uid myuser) is allowed to use the mydaemon service. Once gssproxy runs, mydaemon uses the gssapi libraries (GSSAPI libs detect gssproxy via environment or library probe) and calls the GSSAPI functions; gssproxy will perform gss_acquire_cred using /etc/mydaemon.keytab and return a handle to the calling process. The service itself never directly reads the keytab.
 

6. Testing and tools

  • kinit / klist: manage and list Kerberos TGTs on clients.
  • journalctl -u gssproxy -f (or systemctl status gssproxy) to watch logs.
  • ss -l or ls -l /run/gssproxy to inspect sockets.
  • If you have gssproxy command-line utilities installed (may vary by distro), some installations include gssproxy CLI helpers. Otherwise use the service that relies on gssproxy and watch logs.

Example basic tests:

  1. Ensure gssproxy is running:

sudo systemctl status gssproxy

  1. On server, check socket and permissions:

sudo ls -l /run/gssproxy

# or

sudo ss -x -a | grep gssproxy

  1. Attempt SSH from a client with a TGT:

kinit alice

ssh -o GSSAPIDelegateCredentials=yes alice@server.example.com

# then on server, check journalctl logs for gssproxy/sshd messages
 

7. Debugging tips

  • Journal logs: journalctl -u gssproxy -xe will be your first stop.
  • Permissions: Ensure that gssproxy can read the keytab(s) (typically root-owned with restrictive perms). In config you may point to a keytab readable only by gssproxy.
  • Clients blocked: If a client is denied, check the clients block and match rules (uid/pid/user).
  • Keytab issues: Use klist -k /etc/krb5.keytab to list principals in a keytab. Ensure correct SPN and realm.
  • Clock skew: Kerberos is time-sensitive. Ensure NTP/chrony is working.
  • DNS / SPNs: Ensure hostnames and reverse DNS match the principal names expected for the service.
  • SSHD integration: If sshd still complains it can’t accept GSSAPI creds, enable debug logging (LogLevel DEBUG), and check gssproxy logs.
  • SELinux: On SELinux-enabled systems, you may need to ensure file contexts and SELinux policies allow gssproxy to access keytabs and sockets. Check audit.log for AVC denials and use semanage fcontext/restorecon or local policy modules when needed.
     

8. Common pitfalls & best practices

  • Don’t expose keytabs to unprivileged users. Let gssproxy hold them.
  • Principals & SPNs must match service hostnames used by clients. Consistent DNS is essential.
  • Minimal privileges: configure services and clients narrowly: allow only the minimum users/PIDs and only the required mech ops.
  • Rotation: when rotating keytabs, reload/restart gssproxy or send a signal if supported. Plan for keytab updates.
  • Logging: enable adequate logging during deployment and revert to normal verbosity in production.
  • Testing in staging: GSSAPI behavior across SSH clients and other daemons can be subtle — test across your client set (Linux, macOS, Windows via native Kerberos clients, etc.).
     

9. Security considerations

  • gssproxy centralizes credential access: secure the host and the gssproxy process.
  • Protect keytab files using strict filesystem permissions and (if needed) SELinux policy.
  • Restrict which local processes may request operations for a service — map by UID/PID carefully.
  • Monitor logs for unexpected use of gssproxy.
     

10. Example full config (simple)

Save as /etc/gssproxy/gssproxy.conf:

mechs = {

    krb5 = {

        mech = krb5;

        default_keytab = /etc/krb5.keytab;

    };

};

 

services = {

    ssh = {

        mech = krb5;

        user = "sshd";

        keytab = /etc/krb5.keytab;

        server = yes;

        client = yes;

    };

 

    mydaemon = {

        mech = krb5;

        user = "myuser";

        keytab = /etc/mydaemon.keytab;

        client = yes;

        server = no;

    };

};

 

clients = {

    allow_root_for_ssh = {

        clients = [

            { match = "uid:0" },

        ];

        service = "ssh";

    };

 

    mydaemon_client = {

        clients = [

            { match = "user:myuser" },

        ];

        service = "mydaemon";

    };

};

Restart: sudo systemctl restart gssproxy and then restart dependent services (sshd, mydaemon, etc.) if needed.

 

Useful resources for gssproxy and further integrations

  • Read your distribution’s /usr/share/doc/gssproxy/ or man pages (man gssproxy, man gssproxy.conf) — they contain distribution-specific details.
  • Check integrations: Samba/Winbind, SSSD, NFS idmap — many modern stacks support gssproxy as an option to avoid exposing keytabs to many daemons.
  • For production: automate keytab distribution, rotation and monitor gssproxy usage.