How to Set Up Automatic Security Updates on Debian and Ubuntu

Keeping your Ubuntu server secure and up-to-date is crucial to minimizing the risk of vulnerabilities. One effective way to ensure timely patching of critical security issues is to enable automatic updates using unattended-upgrades. Here’s how to configure it step by step.

TLDR;

sudo apt install unattended-upgrades
sudo dpkg-reconfigure unattended-upgrades
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
sudo nano /etc/apt/apt.conf.d/20auto-upgrades

Step 1: Install unattended-upgrades

First, you need to install the package that handles automatic updates. You can do this by running the following command:

sudo apt install unattended-upgrades

This will install the necessary package to automate the upgrade process.

Step 2: Configure unattended-upgrades

Once the package is installed, you need to configure it. Run the following command to launch the configuration process:

sudo dpkg-reconfigure unattended-upgrades

During this process, you’ll be asked whether you want to enable automatic updates. Make sure to select “Yes” to enable it.

Step 3: Adjust Configuration Files

To further customize the behavior of automatic updates, you can modify some configuration files.

  1. Open the main configuration file to specify which packages to automatically update:
   sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

In this file, you can select specific origins or repositories from which packages should be updated, such as security updates.

  1. Open another configuration file to control the frequency of updates:
   sudo nano /etc/apt/apt.conf.d/20auto-upgrades

In this file, you can specify the interval for how often the system should check for updates. It typically looks something like this:

   APT::Periodic::Update-Package-Lists "1";
   APT::Periodic::Unattended-Upgrade "1";

These settings indicate that the package list is updated daily, and the system performs unattended upgrades once a day as well.

Conclusion

With these steps, you’ve successfully set up automatic security updates on your Ubuntu server. This will help keep your system secure without needing constant manual intervention. While this is a good practice for keeping your server updated, it’s always important to regularly check logs and ensure everything runs smoothly.

Monitoring Event Logs in Windows with PowerShell: A Script for Recent Events

When managing a Windows environment, analyzing event logs is an essential part of troubleshooting. Windows logs a wide range of system, security, and application events, but sometimes specific problems can arise without easily accessible evidence. For example, when tracking down recent events, it can be cumbersome to manually check each log for relevant entries.

In this post, I’ll share a simple PowerShell script that extracts recent log entries across all event logs—not just the default System, Application, and Security logs. This script is particularly useful when you need to quickly review what’s been happening on your machine over the last 5 minutes.

The Challenge

By default, most users only check System, Application, and Security logs. However, Windows maintains many other event logs that can provide critical information about drivers, devices, or even specific services. Accessing these logs manually via Event Viewer can be tedious and time-consuming. The goal here is to automate this process with PowerShell and make it easier to analyze logs from a specific timeframe—such as the last 5 minutes.

The Solution: PowerShell Script

Below is the PowerShell script that retrieves recent events from all event logs and displays them in an easy-to-read format.

# Determine the time from 5 minutes ago
$TimeSpan = (Get-Date).AddMinutes(-5)

# Fetch all event log names
$logNames = Get-WinEvent -ListLog *

# Loop through each log and look for recent events
foreach ($logName in $logNames.LogName) {
# Fetch the last 100 events, suppress errors if no events exist
$events = Get-WinEvent -LogName $logName -MaxEvents 100 -ErrorAction SilentlyContinue

# If there are events, filter by time
if ($events) {
$recentEvents = $events | Where-Object { $_.TimeCreated -gt $TimeSpan }

# If recent events exist, display them
if ($recentEvents) {
Write-Host "Log: $logName" -ForegroundColor Cyan
$recentEvents | Select-Object TimeCreated, Id, LevelDisplayName, Message | Format-Table -AutoSize
}
}
}

How It Works

  1. Fetching Log Names: The script starts by retrieving the names of all available event logs on your system using the following command:powershellCopy code$logNames = Get-WinEvent -ListLog * This command lists every log, including ones that are not typically visible in the default Event Viewer console.
  2. Setting a Time Filter: The script calculates the timestamp from 5 minutes ago by using Get-Date combined with the AddMinutes() method:powershellCopy code$TimeSpan = (Get-Date).AddMinutes(-5) This value will be used to filter out any events that occurred before this time.
  3. Looping Through Logs: The script then loops through each log fetched earlier:powershellCopy codeforeach ($logName in $logNames.LogName) { For each log, it pulls the last 100 events using Get-WinEvent. The -ErrorAction SilentlyContinue parameter is important here—it suppresses any errors if no events are found in a particular log, ensuring the script doesn’t stop unexpectedly.
  4. Filtering by Time: Once the events are retrieved, they are filtered by the timestamp:powershellCopy code$recentEvents = $events | Where-Object { $_.TimeCreated -gt $TimeSpan } This ensures that only events created in the last 5 minutes are shown.
  5. Displaying the Results: If any events match the filter, they are displayed in a neat table using Format-Table:powershellCopy code$recentEvents | Select-Object TimeCreated, Id, LevelDisplayName, Message | Format-Table -AutoSize The table includes the time the event was created, its event ID, the level (such as Error, Warning, or Information), and the message content.

Why This Matters

By gathering events from all logs, this script ensures that no critical logs are overlooked. Whether you’re troubleshooting a hardware issue, investigating network activity, or monitoring driver problems, reviewing all logs within a specific timeframe can give you a broader perspective on system behavior.

Example Output

Here’s an example of what the output looks like when recent events are found:

Log: Application
TimeCreated Id LevelDisplayName Message
----------- -- ---------------- -------
9/10/2024 11:45 AM 1001 Error Application error occurred...
9/10/2024 11:47 AM 2002 Warning Warning: High CPU usage...

This provides a quick snapshot of recent system activity across various logs.

Happy scripting!

Extend Linux ext4 disk with cfdisk

There are times when you need to extend a disk to accommodate more data or improve performance. While using UI tools to extend disks can make the process easier and more intuitive, there are situations where these tools aren’t available. In such cases, knowing how to extend a disk using command-line tools can be invaluable. This post will guide you through the process of extending a disk without the need for graphical interfaces like gparted.

TLDR;

swapoff /dev/sda5
cfdisk
resize2fs /dev/sda1
mkswap /dev/sda5

swapon /dev/sda5
blkid /dev/sda5
nano /etc/fstab

Full procedure

First check the current partition structure with lsblk

As you can see you have 65G total but only 15GB on /

Start cfdisk


As you can see I cannot extend the disk because of the swap partition. So disable the swap first:

sudo swapoff /dev/sda5

Then start cfdisk to remove the extended and the swap partitions and extend the /dev/sda1

In my case I reseverd 1GB for the new swap.

Then create a new extended /dev/sda2 (max size) partition and within the extended partition a new swap partition /dev/sda5

Change the type of the swap partition to 82 Linux Swap / Solaris

So the partition structure looks like:

Give a write and exit the cfdisk tool

Now you can extend the /dev/sda1 partition with: resize2fs /dev/sda1

As you can see the partition is extended. Now can can reactivate your swap partition

First check the current status

Enter the commands:

  • mkswap /dev/sda5
  • swapon /dev/sda5

And as you can see the swap is actived

last thing you need to do is change the fsab to when the system reboots everything still works 😉

Get the UUID with blkid /dev/sda5

Edit the fstab file: nano /etc/fstab and change the UID to the new ID

That’s all. Happy resizing 🙂

Optimizing RDP Performance on Linux: My Best Settings with xfreerdp

XfreeRDP3

If you’re like me and rely heavily on Remote Desktop Protocol (RDP) to connect to Windows servers from a Linux environment, you know how crucial performance can be. After experimenting with numerous settings, I’ve found a configuration that delivers the best performance using xfreerdp. Here’s a breakdown of the settings that worked wonders for me.

Why xfreerdp?

xfreerdp is an open-source RDP client that offers a plethora of customization options, making it a powerful tool for Linux users needing to connect to Windows servers. Its flexibility allows for fine-tuning, which is essential for optimizing performance.

My Go-To Command

Here is the xfreerdp command that gave me the best results:

xfreerdp3 /u:[email protected] /p:"P@ASSWRRRDDD" /v:10.10.10.10 /dynamic-resolution /compression /network:auto /gfx:AVC420:on +clipboard -themes

Let’s break down what each part of this command does:

  • /u:[email protected]: Specifies the username to use for the connection.
  • /p:”P@ASSWRRRDDD”: Specifies the password. Ensure this is securely stored and managed.
  • /v:10.10.10.10: The IP address of the Windows server.
  • /dynamic-resolution: Adjusts the screen resolution dynamically to match the size of the xfreerdp window.
  • /compression: Enables compression to reduce the amount of data transferred, improving performance over slower connections.
  • /network:auto: Automatically adjusts settings based on network conditions for optimal performance.
  • /gfx:AVC420:on: Uses the AVC420 codec for efficient video compression, providing a good balance between quality and performance.
  • +clipboard: Enables clipboard sharing between the local and remote systems.
  • -themes: Disables desktop themes on the remote server to reduce the amount of graphical processing required.

Additional Tips for Improved Performance

To enhance your Remote Desktop (RDP) experience from Linux, adjusting the performance settings on the Windows server can make a big difference. Here’s a quick guide:

  1. Open System Properties:
  • Right-click on “This PC” or “Computer” and select “Properties”.
  • Click on “Advanced system settings”.
  1. Adjust Performance Options:
  • In the System Properties window, under the “Advanced” tab, click “Settings” in the Performance section.
  • In the Performance Options window, select “Custom” and adjust the settings as shown in the screenshot below.
  1. Recommended Settings:
  • Uncheck unnecessary visual effects like animations, shadows, and Peek.
  • Check only essential items for a smoother experience.

Refer to the screenshot for detailed settings adjustments.

By tweaking these settings, you can significantly improve the responsiveness of your RDP sessions.

Performance Options

Conclusion

Finding the right settings for xfreerdp can be a game-changer for your remote desktop experience on Linux. The command and tips I’ve shared should help you achieve a smoother and more responsive connection to your Windows servers. Don’t hesitate to tweak these settings further based on your specific network conditions and requirements.

Happy remoting!


NixOS and Sway

Currently, I am experimenting with NixOS and Sway. NixOS is a Linux operating system that allows you to build and manage your system using a single configuration file. Sway is a tiling window manager designed for Wayland, offering a dynamic and efficient workspace.

This article is a work in progress. I plan to share my setup and configuration details, but for now, this article serves as a draft to document my journey.

I am aware of tools like flakes and Home Manager, but my current goal is to explore and understand NixOS without using these mechanisms.

Sway

Config displays

Use wdisplays. This is a nice graphical tool for wayland to configure and outline your displays

Use swaymsg -t get_outputs to get all the display settings

Example config for 3 displays

# Config eDP-1
output eDP-1 {
    mode [email protected]
    pos 5247 0
    scale 1.375
    scale_filter linear
    transform normal
    max_render_time off
    adaptive_sync disabled
}

# Config DP-3
output DP-3 {
    mode [email protected]
    pos 8808 0
    scale 1.0
    scale_filter nearest
    transform normal
    max_render_time off
    adaptive_sync disabled
}

# Config DP-4
output DP-4 {
    mode [email protected]
    pos 6888 0
    scale 1.0
    scale_filter nearest
    transform normal
    max_render_time off
    adaptive_sync disabled
}

# Workspace assign
workspace 1 output eDP-1
workspace 2 output DP-4
workspace 3 output DP-3

Terminal (foot)

Configure the font

$ touch ~/.config/foot/foot.ini
$ nano ~/.config/foot/foot.ini

[main]
font = monospace:size=14

Sway shortcuts (cheatsheet)

  • Mod + w = Tabbed view
  • Mod + e = Normal view
  • Mod + w = Tabbed view
  • Mod + d = Application menu
  • Mod+Shift+e = Restart Sway

NixOS

Packages

environment.systemPackages = with pkgs; [
vim
wget
firefox-wayland
spotify
steam
todoist-electron
gimp
pinta
gedit
keepassxc
synology-drive-client
vscode
dolphin
libsForQt5.kdeconnect-kde
killall
networkmanager
git
kitty
powershell
networkmanagerapplet
gnome.gnome-keyring
blueman
gnome.gnome-bluetooth
bluez
bluez-tools
pkgs.libsForQt5.bismuth # KDE Tiling
upower # nodig voor power management (firefox)
];

PRTG articles to build custom sensors

In recent times, I’ve dedicated a significant portion of my efforts to developing custom PRTG sensors. To assist others who might be interested in this area, I’ve decided to create this blog post where I will compile a collection of useful links. These links lead to various articles and resources that I’ve found invaluable in my journey of crafting personalized sensors for the PRTG network monitoring tool. This curated list is intended to serve as a helpful guide for anyone looking to explore the possibilities of custom sensor creation in PRTG.

Advanced Sensors

https://www.paessler.com/manuals/prtg/custom_sensors#advanced_sensors

PRTG Sensor Hub

https://www.paessler.com/sensor-hub/all/all/all#sw_origin_9

iptraf-ng: A Lightweight Yet Powerful Alternative to TCPDump and Wireshark

Iptraf-ng stands out as an excellent alternative to Wireshark and tcpdump, offering a robust set of features for comprehensive network traffic analysis. This versatile tool gathers a wide range of information, including TCP connection details, interface statistics, and TCP/UDP traffic breakdowns.

Its key features make it a compelling choice:

  1. IP Traffic Monitoring:
    • Provides real-time insights into IP traffic across your network.
  2. Detailed Interface Statistics:
    • Displays comprehensive statistics on IP, TCP, UDP, ICMP, non-IP packets, and more.
  3. TCP and UDP Service Monitoring:
    • Monitors incoming and outgoing packets for commonly used TCP and UDP application ports.
  4. LAN Statistics Module:
    • Identifies active hosts on the LAN, offering data activity statistics.
  5. Protocol Display Filters:
    • Enables users to customize displays for specific protocols like TCP, UDP, and others.
  6. Logging Capabilities:
    • Allows for the logging of network activity, facilitating detailed analysis.

As a user-friendly and efficient network monitoring tool, iptraf-ng presents itself as a valuable alternative to Wireshark and tcpdump. Its capabilities make it particularly well-suited for those seeking a reliable solution for network analysis and troubleshooting. The example screenshot of the IP traffic monitor underscores its user-friendly interface and robust functionality, positioning iptraf-ng as a commendable choice in the realm of network monitoring tools.

vlookup with powershell

I want to use the vlookup excel function within powershell and without data manipulation of the CSV itself. So I wrote a script to import a CSV, find some data and compare these data

$CSV = Import-Csv -Path C:\Users\user\some.csv

$trigger = $CSV| Where-Object {$_."Primary Description"  -like "some string with a computername"}
$result = $CSV| Where-Object {$_."Primary Description"  -like "another string with a computername"}

$triggerComputer = foreach ($i in $trigger) {($i."Primary Description" -split " ")[5]}
$resultComputer = foreach ($i in $result) {($i."Primary Description" -split " ")[5]}

Compare-Object $triggerComputer $resultComputer

Have fun!

Install winget without the Microsoft App Store

If you are unable to access the Windows Store app and wish to install winget, you can easily do so by following these steps:

  • First download the latest version of winget: https://aka.ms/getwinget
  • Then use this Powershell command to install winget
Add-AppxPackage -Path Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle

Probably you will get this error:

Windows cannot install package Microsoft.DesktopAppInstaller_1.19.10173.0_x64__8wekyb3d8bbwe because this package depends on a framework that could not be found. Provide the framework “Microsoft.UI.Xaml.2.7” published by “CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US”, with neutral or x64 processor architecture and minimum version 7.2109.13004.0, along with this package to install. The frameworks with name “Microsoft.UI.Xaml.2.7” currently installed are: {}

The reason is that you miss the dependency Microsoft.UI.Xaml.2.7

Now you have to go to the nuget website and download the nuget package: https://www.nuget.org/packages/Microsoft.UI.Xaml/2.7.3

Then you have to rename the file extension of the downloaded file to .zip

Open the zip file and go to tools > AppX > X64 > Release and extract the Microsoft.UI.Xaml.2.7.appx file

Install the extracted appx file

Add-AppxPackage -Path .\Microsoft.UI.Xaml.2.7.appx

You may also get this error when you try to install winget

Windows cannot install package Microsoft.DesktopAppInstaller_1.19.10173.0_x64__8wekyb3d8bbwe because this package depen
ds on a framework that could not be found. Provide the framework “Microsoft.VCLibs.140.00.UWPDesktop” published by “CN=
Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US”, with neutral or x64 processor architect
ure and minimum version 14.0.30704.0, along with this package to install. The frameworks with name “Microsoft.VCLibs.14
0.00.UWPDesktop” currently installed

You can download Microsoft.VCLibs.140.00.UWPDesktop here: https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx

Install Microsoft.VCLibs.x64.14.00.Desktop with this command:

Add-AppxPackage -Path .\Microsoft.VCLibs.x64.14.00.Desktop.appx

And now you should install the winget application without errors:

Add-AppxPackage -Path .\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle

Happy installing 🙂

Install and Configure OpenSSH Windows Server 2019 and 2022 and configure key-based authentication

OpenSSH is a free and open-source software that allows secure communication between computers over an unsecured network. It is widely used on Linux and Unix systems, but it is also available for Windows systems. In this article, we will show you how to install and configure OpenSSH on a Windows 2022 server.

Step 1: Install OpenSSH

The first step is to install OpenSSH on your Windows server. To do this, follow these steps:

# Install the OpenSSH Server
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
# Start the sshd service
Start-Service sshd

# OPTIONAL but recommended:
Set-Service -Name sshd -StartupType 'Automatic'

# Confirm the Firewall rule is configured. It should be created automatically by setup. Run the following to verify
if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) {
    Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..."
    New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
} else {
    Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists."
}

Step 2: Configure OpenSSH

Once OpenSSH is installed on your server, you need to configure it to allow secure communication. Follow these steps to configure OpenSSH:

  • Open notepad
  • Open the configuration file C:\ProgramData\ssh\sshd_config
  • Remove the “#” at the beginning of the line #PubkeyAuthentication yes to uncomment it:PubkeyAuthentication yes
  • Locate the line that starts with #PasswordAuthentication yes and remove the “#” at the beginning of the line to uncomment it and change it to NO: PasswordAuthentication no
  • Add the “#” at the beginning of the line AuthorizedKeysFile PROGRAMDATA/ssh/administrators_authorized_keys to comment it out:#AuthorizedKeysFile PROGRAMDATA/ssh/administrators_authorized_keys
  • Save the changes and close the configuration file.
  • Restart the service
# Restart the sshd service
Restart-Service sshd

Step 3: Configure the Administrator for key-based authentication

After the configuration is complete, you need to configure the public key.

Optional: If you don’t have a public/private keypair use this command to create the files on your client:

ssh-keygen -t rsa -b 4096
  • Open the Explorer and go to C:\Users\<Username>\
  • Create a folder .ssh
  • Create a text file (without extension!) authorized_keys
  • Open the file in notepad
  • Paste your ssh-rsa public key in this authorized_keys file (this is the content of id_rsa.pub)
  • Save the file
  • Remove the inheritance so that only the user and system has full permission

Step 4: Test OpenSSH

To test if OpenSSH is installed and configured correctly, follow these steps:

  • Open a Command Prompt window.
  • Type “ssh username@<server>” and press Enter.
  • If the connection is successful, you should see a welcome message.

Congratulations! You have successfully installed and configured OpenSSH on your Windows 2022 server and configure it securely with key-based authentication.

Optional: change CMD to Powershell

If you want to connect directly in PowerShell instead of the default command use this PowerShell command

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force

Happy connecting 🙂