NetBSD was founded in March 1993 by Chris Demetriou, Theo de Raadt, Adam Glass, and Charles Hannum.
The developers were contributing to the 386BSD branch, but grew frustrated with the slow pace of integration, lack of code audits, and lack of support for multi-platform CPU architectures.
They merged the 386BSD codebase with Berkeley’s Net/2 tape to create NetBSD 0.8, which was released in April 1993.
The project adopted a core mission: portability. The goal was to write clean, machine-independent code that could easily compile and run on any hardware platform, from high-performance servers to legacy and embedded hardware.
This design philosophy led to the famous slogan: “Of course it runs NetBSD.”
Early ports were rapidly written for the Motorola 68k (Amiga and Atari), PC-9801, DEC Alpha, and SPARC architectures.
The 4.4BSD-Lite Integration and Lawsuit Settlement (1994–1995)
Like FreeBSD and OpenBSD, NetBSD was impacted by the Unix System Laboratories (USL) vs. BSDI/UC Berkeley lawsuit.
Following the settlement in 1994, the NetBSD project replaced the encumbered Net/2 files with clean code from Berkeley’s 4.4BSD-Lite.
In October 1994, NetBSD released NetBSD 1.0, which was completely free of proprietary AT&T code and established the project’s multi-platform capabilities.
This clean codebase allowed developers to focus on the unification of compiler structures and machine-independent driver layers.
Divergence of OpenBSD (1995)
In 1995, due to personal and philosophical differences regarding development processes, Theo de Raadt was asked to resign from the NetBSD core team.
This split led Theo de Raadt to fork the NetBSD source tree and create the OpenBSD project, focusing heavily on security audits and proactive cryptography.
This divergence split the development community but also allowed NetBSD to focus single-mindedly on its portability optimizations and clean modular kernel designs.
Pioneer of Shared USB and Audio Stacks
During the late 1990s and early 2000s, NetBSD developers pioneered some of the industry’s most flexible and portable driver stacks.
The USB Stack (NetBSD USB) was designed from the ground up to be architecture-neutral, allowing it to be compiled on big-endian and little-endian architectures alike.
This stack was subsequently imported by FreeBSD, OpenBSD, and several commercial real-time operating systems (RTOS) due to its stability.
Similarly, NetBSD’s Audio Subsystem separated the hardware driver logic from the audio mixer logic, establishing standard userspace interfaces that are still in use today.
Architectural Expansion and Hardware Portability
NetBSD is renowned for running on an extremely wide variety of CPU architectures:
NetBSD 1.3 (1998): Added support for DEC Alpha, Motorola 68k, and early SPARC, demonstrating that the kernel could run on both 32-bit and 64-bit platforms.
NetBSD 1.6 (2002): Expanded architectures to include SuperH, MIPS, and ARM, making NetBSD a favorite for embedded hardware and network routers.
Toaster and Obscure Ports: A famous demonstration involved installing NetBSD on an internet-enabled toaster (Technologic Systems TS-5300 board running NetBSD), validating its modularity. Other obscure ports include the Sega Dreamcast, Amiga, NeXTSTEP hardware, VAX mainframes, and HP 9000 workstations.
NetBSD 5.0 (2009): Introduced major performance improvements for multi-core processors (SMP), transitioned to the thread-safe WAPBL journaling filesystem, and expanded modular driver loading.
NetBSD 8.0 (2018): Integrated NPF (NetBSD Packet Filter) as the default firewall, added built-in support for PaX security enforcements (ASLR, MPROTECT), and updated graphics layers.
NetBSD 9.0 (2020): Improved ARM64 hardware support (Tier-1 status), added support for Virtualization.framework inside guest systems, and optimized the RUMP Kernels framework.
NetBSD 10.0 (2024): Improved CPU scheduling performance on multi-core systems, updated graphics drivers (DRM/KMS), and added support for WireGuard VPN connections natively.
The Development and Build System Innovation
To achieve hardware portability, NetBSD developers wrote the build.sh cross-compilation infrastructure.
build.sh allows a developer to compile the entire NetBSD operating system, including the kernel, userland, and installer sets, for any target architecture (such as ARM64 or SPARC) on a host system running Linux, macos, or Windows, without requiring root privileges.
NetBSD Release Timeline and Architecture Mapping
The table outlines major NetBSD releases, including their hardware support and life status:
Marketing Release
Kernel Version
Release Year
Main CPU Architectures
Status
NetBSD 1.0
1.0-RELEASE
1994
i386, SPARC, Amiga, Atari
End of Life (EOL)
NetBSD 2.0
2.0-RELEASE
2004
i386, amd64, alpha, sparc64, macppc
End of Life (EOL)
NetBSD 3.0
3.0-RELEASE
2005
amd64, i386, alpha, sparc64, m68k
End of Life (EOL)
NetBSD 4.0
4.0-RELEASE
2007
amd64, i386, sparc64, alpha, mips
End of Life (EOL)
NetBSD 5.0
5.0-RELEASE
2009
amd64, i386, sparc64, powerpc, sh3
End of Life (EOL)
NetBSD 6.0
6.0-RELEASE
2012
amd64, i386, arm, mips, sparc64
End of Life (EOL)
NetBSD 7.0
7.0-RELEASE
2015
amd64, arm64, i386, sparc64, mips
End of Life (EOL)
NetBSD 8.0
8.0-RELEASE
2018
amd64, arm64, i386, powerpc, vax
End of Life (EOL)
NetBSD 9.0
9.0-RELEASE
2020
amd64, arm64, i386, sparc64, vax
Active Support
NetBSD 10.0
10.0-RELEASE
2024
amd64, arm64, i386, sparc64, vax, m68k
Active Support
NetBSD 11.0
11.0-CURRENT
2025
amd64, arm64, riscv64
Development
Introduction
What is NetBSD?
NetBSD is a free and open-source operating system descended from Berkeley Software Distribution (BSD) Unix, focusing on portability, clean code design, and standards compliance.
Like FreeBSD and OpenBSD, NetBSD compiles its kernel and userland tools together from a single source tree, maintaining a cohesive base system.
NetBSD is widely recognized for its hardware portability and its Rump Kernels framework, which allows developers to run kernel-space drivers inside user-space containers.
POSIX Compliance and Standards
NetBSD adheres strictly to POSIX standards, ensuring that systems APIs, compilers, and utilities behave consistently across all supported CPU architectures.
The project uses the LLVM/Clang and GCC compiler chains, adapting them to compile clean, standards-compliant binaries for diverse targets.
BSD License vs GPL
Released under the permissive BSD License, NetBSD allows modifications and commercial packaging without copyleft source-sharing rules.
This has allowed companies to use NetBSD in embedded devices, network appliances, and real-time systems (such as printers, routers, and space satellites).
Portability Philosophy: Machine-Independent (MI) vs Machine-Dependent (MD)
A core component of NetBSD’s design is the strict separation of code into Machine-Independent (MI) and Machine-Dependent (MD) layers.
The MI layer contains code that is identical across all architectures (e.g., virtual memory policies, scheduling algorithms, and network packet routing logic).
The MD layer contains only the code that must directly interface with the hardware CPU and registers (e.g., context switching, page table manipulation, and assembly bootstrap code).
By isolating MD code to a minimal set of files, porting NetBSD to a new architecture usually requires rewriting only a few thousand lines of MD code, leaving the rest of the OS untouched.
Core Advantages of NetBSD
Hardware Portability: Runs on over 50 hardware architectures (from servers and desktop workstations to VAX mainframes and ARM64 IoT boards).
Rump Kernels (Anykernel): Allows running NetBSD drivers in userspace or micro-VM containers, preventing driver crashes from crashing the host kernel.
Cross-Platform Package Manager (pkgsrc): NetBSD’s package manager runs on other operating systems, including Linux, macos, and other BSDs, providing a consistent package building pipeline.
Unified build.sh Toolchain: The build system cross-compiles the entire OS for any target from a single command, making it easy to manage embedded builds.
Core Disadvantages of NetBSD
Smaller Desktop Community: Lacks the user base of Ubuntu or FreeBSD, resulting in fewer desktop-centric customization guides.
Slower Driver Adoption: Graphics acceleration drivers (DRM/KMS) and wireless card drivers are ported from Linux, which can lead to support delays for the newest PC hardware.
Lack of systemd: System administration uses the traditional rc.d system, requiring developers to adapt Linux-centric systemd setup scripts.
Real-World Applications
Embedded IoT: NetBSD is a popular choice for embedded devices due to its tiny footprint, modularity, and quick boot times on ARM/MIPS.
NASA Projects: NetBSD has been used in NASA research projects and computational tasks that require rock-solid execution environments.
Network Appliances: Companies construct secure hardware firewalls and routers based on NetBSD’s low-overhead TCP/IP stack and NPF.
Retrocomputing: Preservation of historical server and mainframe systems is heavily reliant on NetBSD, as it remains the only actively maintained operating system that supports architectures like VAX, m68k, and Alpha.
Comparison: NetBSD vs OpenBSD vs FreeBSD vs Linux
The table outlines key differences across the operating system platforms:
# Download the official NetBSD install ISO image# Fetch the SHA512 checksum file to verify download integrityfetch https://cdn.netbsd.org/pub/NetBSD/NetBSD-10.0/images/NetBSD-10.0-amd64.isofetch https://cdn.netbsd.org/pub/NetBSD/NetBSD-10.0/images/SHA512# Validate the checksum matches on a Unix-like systemsha512sum -c SHA512 --ignore-missing# Burn image to a USB flash drivesudo dd if=NetBSD-10.0-amd64.iso of=/dev/sdX bs=1M status=progresssync
The sysinst Installer Walkthrough
NetBSD boots into a lightweight menu-driven installer called sysinst:
Select language interface (e.g., English).
Select keyboard layout (e.g., us).
Choose Install NetBSD to hard disk.
Select installation target disk (e.g., wd0 or sd0).
Configure disk partitioning using disklabel or GPT layouts.
Configure network interfaces to fetch installation packages.
Extract the core package sets: base, compiler, game, system diagnostic tools.
Set root password and configure the default timezone.
Partitioning Guide: disklabel Layout
NetBSD partitions are divided into sub-partitions using the disklabel system:
Partition Index --> Mount Point --> File System Type --> Size Allocation
/dev/wd0a --> / --> ffs --> Remaining Disk space
/dev/wd0b --> None --> swap --> 2 GB (Swap Space)
/dev/wd0e --> /boot/efi --> msdos --> 200 MB (EFI System Partition)
Headless Installation: Setting up a Serial Console Server
In headless server environments, physical screens and keyboards are unavailable. NetBSD can be configured to use a serial port as the primary console.
To boot the installer or system directly over a serial port, edit the configuration files on the boot partition:
# /boot.cfg configuration parameters
# Force console redirection to the first serial port com0
consdev=com0
speed=115200
After installation, the system must spawn a login shell on the serial interface. Edit /etc/ttys to enable getty on the serial port:
# /etc/ttys entries for serial terminal daemon
# Interface --> Daemon path & options --> Terminal Type --> Status
tty00 "/usr/libexec/getty std.115200" vt100 on secure
Desktop Environment & Sound System Setup
Although NetBSD is popular for server and embedded environments, it can be configured as a lightweight workstation.
Setting up X11 and Default Window Manager:
Since NetBSD 10, CTWM is configured as the default window manager in the base system.
Enable the virtual terminal mouse daemon (wsmoused) and D-Bus in /etc/rc.conf:
echo "wsmoused=YES" | sudo tee -a /etc/rc.confecho "dbus=YES" | sudo tee -a /etc/rc.confsudo service wsmoused startsudo service dbus start
To use a full desktop environment like XFCE instead of CTWM, install it using pkgin:
sudo pkgin install xfce4 xfce4-extras slimecho "slim=YES" | sudo tee -a /etc/rc.conf
Sound System Configuration:
NetBSD uses the open-source audio framework interface /dev/audio.
Hardware status and audio channels can be inspected using audioctl and configured using mixerctl:
# Query active audio device driveraudioctl -a# Set master volume to 80% (range is usually 0-255)mixerctl -w outputs.master=204# Play a standard wav file using base utilityaudioplay /usr/share/sounds/startup.wav
First Boot Configuration
Upon booting into a fresh NetBSD install:
rc.conf: Enable default services like DHCP client configuration and SSH daemon.
pkgin: Install binary packages from official pkgsrc mirrors.
# Configure /etc/rc.conf to enable networking and sshd on bootecho "dhcpcd=YES" | sudo tee -a /etc/rc.confecho "sshd=YES" | sudo tee -a /etc/rc.conf# Start networking daemon manuallysudo service dhcpcd start# Configure pkgin binary mirror source paths# Edit the file /usr/pkg/etc/pkgin/repositories.conf# Add: https://cdn.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/10.0/All# Update package database and upgrade packagessudo pkgin updatesudo pkgin upgrade
Kernel & Architecture
Monolithic Design with Userspace Modularity (Rump Kernels)
NetBSD uses a monolithic kernel design, but features a modular architecture called Rump Kernels (Runnable Userspace Meta Programs) or the Anykernel.
Rump Kernels allow running unmodified NetBSD kernel drivers (such as filesystems, device drivers, or TCP/IP stacks) in user space or inside micro-VM containers.
Because the drivers are isolated from the main kernel address space, a driver crash does not crash the host kernel, improving system reliability.
The Three Layers of RUMP Architecture
The Rump kernel architecture partitions kernel components into distinct layers to separate logic from execution contexts:
rumpuser (Hypercalls): The platform-dependent layer. It maps userspace execution calls (allocations, threads, file locks) to the host environment operations.
rumpkern (Subsystem Core): The machine-independent kernel core, providing thread schedulers, lock synchronization pools, and memory managers.
rumpdev / rumpnet (Isolated Drivers): Virtualized wrappers hosting actual device drivers (network interfaces, disk volumes, usb controllers) and networking protocols.
This structure allows the system to cross-compile device drivers for completely separate targets and run them in virtualization pipelines.
Detailed Comparison: Rump Kernels vs Microkernels vs Monolithic Kernels
To understand the unique “Anykernel” design of NetBSD, we must contrast it with traditional kernel styles:
Monolithic Kernels (e.g., Linux, standard FreeBSD): Run the entire OS services (filesystems, network stack, device drivers) inside a single large address space in supervisor mode. While highly efficient, any driver bug or memory leak can trigger a fatal kernel panic and halt the host.
Microkernels (e.g., Mach, Hurd, L4): Place only the absolute minimum primitives (IPC, basic scheduling, page table mapping) in kernel space. All other services (drivers, filesystems) run as separate userland servers. While highly secure and isolated, this architecture suffers from significant IPC context-switch performance overhead.
Anykernel (NetBSD Rump): Maintains a monolithic structure for normal bare-metal operations to ensure maximum performance. However, because the kernel code is strictly partitioned, the exact same driver binaries can be detached and compiled to execute inside userspace processes. This provides microkernel-style fault isolation on demand without the performance penalty of traditional microkernels.
Rump Hypercalls API: The rumpuser Interface
The interface between the rump kernel and the host system is defined by a thin abstraction layer called the rumpuser hypercall API.
This API exposes simple primitives for memory allocation, thread creation, synchronization locks, and I/O access.
Because the rump kernel only depends on this minimal API, it can be run on top of diverse environments:
POSIX Userspace: Running as standard processes on NetBSD, Linux, macOS, or Windows.
Bare Metal: Running directly on physical hardware or hypervisors as a specialized Unikernel.
Xen / KVM Hypervisors: Serving as lightweight, isolated network firewalls or storage proxies.
The build.sh Cross-Compilation Infrastructure
NetBSD features build.sh, a script in /usr/src that automates cross-compilation of the entire operating system.
Developers can compile the kernel, libraries, and utilities for a target architecture (e.g., SPARC or ARM) on a host system running Linux or macOS, without requiring root privileges.
# Navigate to the source tree directorycd /usr/src# Compile the cross-compiler toolchain for ARM64 target./build.sh -m evbarm -a aarch64 tools# Build the complete NetBSD distribution sets for ARM64 target./build.sh -m evbarm -a aarch64 distribution# Compile the kernel specifically./build.sh -m evbarm -a aarch64 kernel=GENERIC
System Startup Boot Flow
UEFI/BIOS Boot: Loads the boot loader program (boot.cfg).
boot (2nd Stage Bootloader): Parses config options, loads kernel drivers, and boots the kernel (/netbsd).
Kernel Initialization (main): Initializes CPU features, memory allocators, and mounts root filesystem.
init (PID 1): Runs the /etc/rc startup scripts.
rc.d Scripts: Starts system daemons in dependency order.
Like OpenBSD, NetBSD configures the Korn Shell (ksh) as the default shell for standard user accounts.
The system profiles are located in /etc/profile and the user’s home .profile directory.
Shell Customization
# ~/.profile configuration parametersexport HISTFILE=$HOME/.ksh_historyexport HISTSIZE=500# Set terminal prompt showing host, username, and path infoPS1='[NetBSD] $USER:$PWD $ '# Enable vi-style terminal command line editingset -o vi
Zsh Customization in NetBSD
To install and customize Zsh as the primary shell on NetBSD, install it from packages:
sudo pkgin install zshchsh -s /usr/pkg/bin/zsh
Save this template as ~/.zshrc for an optimized terminal experience:
# ~/.zshrc configuration on NetBSDexport PATH=/usr/pkg/bin:/usr/pkg/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R7/bin:/usr/local/binexport HISTFILE=~/.zsh_historyexport HISTSIZE=10000export SAVEHIST=10000# Configure prompt layout with exit code verificationPROMPT='%F{green}[%n@%m]%f %F{blue}%~%f %# '# Keybindings for vi mode compatibilitybindkey -v
wscons Console Driver Configuration
NetBSD uses the wscons (workstation console) driver to manage physical displays, virtual consoles, and keyboards.
Configurations are stored in /etc/wscons.conf. It allows defining screen resolutions, enabling screen savers, mapping virtual console terminals, and configuring keyboard layouts.
Example production configurations:
# /etc/wscons.conf configurations template
# Define virtual screens (up to 8 consoles)
screen 0 - vt100
screen 1 - vt100
screen 2 - vt100
screen 3 - vt100
screen 4 - -
# Map keyboard layout (e.g., German, French, or Us)
encoding de
# Load custom VGA screen font for sharper displays
font ibm 8 16 pcvt /usr/share/pcvt/fonts/vt220l.816
Unix Permissions and File Flags
NetBSD supports standard permissions and advanced file flags via the chflags command:
schg: System Immutable flag. Can only be altered when the system is in single-user mode.
sappnd: System Append-only flag. Permits appending data to log files, but blocks modifications and deletions.
# Lock a system configuration file using the system immutable flagsudo chflags schg /etc/rc.conf# Lock log files to prevent log deletionsudo chflags sappnd /var/log/authlog
User & Group Management
The Account Database Structures
NetBSD stores user credentials in /etc/master.passwd, which is readable only by the root account.
Passwords are hashed using cryptographic algorithms like bcrypt or SHA512, configured in /etc/passwd.conf.
User Administration Commands
Users are managed using standard POSIX utility commands:
# Add a new group 'staff'sudo groupadd -g 1020 staff# Create a new user with home directory and Korn shellsudo useradd -u 1020 -g staff -m -s /bin/ksh -c "System Operator" operator1# Set the user's passwordsudo passwd operator1# Add 'operator1' to the wheel group (required to switch to root shell)sudo usermod -G wheel operator1# Delete a user account and purge their filessudo userdel -r operator1
Sudo Privilege Configuration
NetBSD uses sudo for privilege escalation (install via pkgin):
Configure permissions using the visudo editor command:
# Run visudo to safely edit /etc/sudoers# Allow wheel group members to execute commands as root:# %wheel ALL=(ALL:ALL) ALLsudo visudo
Login Classes & Resource Limits: /etc/login.conf
Login classes allow administrators to set resource limits (CPU usage, memory limits, maximum open files, process limits) for users globally or by category.
Edit /etc/login.conf to set custom resource constraints:
# /etc/login.conf configuration definitions
# Define limits for database servers or large compiler processes
heavyusers:\
:datasize-max=2048M:\
:stacksize-max=128M:\
:memoryuse-max=4096M:\
:openfiles-max=4096:\
:maxproc-max=512:\
:tc=default:
Assign a user to this login class in the account database:
# Change login class for database admin usersudo usermod -L heavyusers dbadmin
System Configuration & Services (rc.d)
The rc.d Startup Daemon Framework
NetBSD uses the traditional rc.d initialization framework to run system scripts in dependency order.
System services are enabled and configured in /etc/rc.conf.
# Enable a service (e.g., httpd) to start on bootecho "httpd=YES" | sudo tee -a /etc/rc.conf# Start the service immediatelysudo service httpd start# Check service statussudo service httpd status# Restart the servicesudo service httpd restart# Stop the servicesudo service httpd stop
Core Configuration Files Map
/etc/rc.conf: The primary configurations file for system services and network interfaces.
/etc/mygate: Configures the default network gateway.
The rcorder Dependency Ordering Utility
NetBSD starts services using the rcorder utility.
Instead of executing files based on numerical order (such as /etc/rc3.d/S99app in Linux SysVinit), rcorder parses metadata block comments located at the top of every startup script.
Key metadata blocks include:
PROVIDE: Specifies the service name this script initiates.
REQUIRE: Lists services that must be running before this script starts (e.g., NETWORKING or mountcritlocal).
BEFORE: Lists services that should only start after this script finishes.
The system executes rcorder /etc/rc.d/* to compute a topological sort, determining the optimal execution schedule on boot.
Writing a Custom rc.d Script (Template 1: Custom Daemon)
Save this template as /etc/rc.d/customapp to manage a custom daemon on boot:
# Make executablesudo chmod +x /etc/rc.d/customapp# Enable and start the serviceecho "customapp=YES" | sudo tee -a /etc/rc.confsudo service customapp start
Writing a Second Custom rc.d Script (Template 2: Load Monitor Service)
Save this template as /etc/rc.d/sysmonitor to run a background diagnostic script that runs after the networking interface configuration is online:
sudo chmod +x /etc/rc.d/sysmonitorecho "sysmonitor=YES" | sudo tee -a /etc/rc.confsudo service sysmonitor start
Package Management (pkgsrc)
The pkgsrc Cross-Platform Package Manager
NetBSD uses pkgsrc as its package management system.
pkgsrc is highly portable and runs on many Unix-like systems, including Linux, macos, and other BSDs.
It supports installing pre-compiled binary packages via pkgin or building packages from source using the pkgsrc makefile tree.
Using the pkgin Binary Package Tool
pkgin is the CLI tool for managing binary packages on NetBSD:
# Update package repository index catalogsudo pkgin update# Install a package (e.g., tmux)sudo pkgin install tmux# Upgrade all installed binary packages to their latest versionssudo pkgin upgrade# Search for a package matching a keywordpkgin search nmap# Uninstall a packagesudo pkgin remove tmux# Remove unused dependencies and clean packages cachesudo pkgin autoremovesudo pkgin clean
Compiling Packages from Source (pkgsrc tree)
To build packages from source:
# Fetch and extract the pkgsrc tree using cvscd /usrsudo cvs -q -z3 -d anoncvs@anoncvs.NetBSD.org:/cvsroot checkout -P pkgsrc# Navigate to the target package directory (e.g., net/nmap)cd /usr/pkgsrc/net/nmap# Compile from source and installsudo make install clean
Production mk.conf Compilation Configurations
When building applications from source inside the pkgsrc directory tree, compilation flags and local dependencies are controlled via /etc/mk.conf.
Saving an optimized /etc/mk.conf file allows administrators to apply custom compilation arguments across all packages globally.
Example production configuration file:
# /etc/mk.conf pkgsrc compilation parameters
# Define compiler optimizations for the host CPU
CFLAGS+= -O2 -march=native
CXXFLAGS+= -O2 -march=native
# Enable Stack-Smashing Protection (SSP) hardening on all builds
PKGSRC_USE_SSP= yes
# Accept licenses for proprietary packages (e.g., non-free codecs)
ACCEPTABLE_LICENSES+= no-profit non-commercial-use
# Global package-specific options
PKG_DEFAULT_OPTIONS= -ipv6 ssl dbus
# Custom option overrides for specific packages
PKG_OPTIONS.nmap= -zenity ssl
PKG_OPTIONS.nginx= nginx-dav nginx-push-stream
Storage & Filesystems (FFS, LFS, CGD & ZFS)
FFS (Fast File System) and WAPBL Logging
NetBSD uses the Fast File System (FFS) as its default filesystem.
To optimize metadata write speeds and ensure filesystem safety during sudden power losses, NetBSD implements WAPBL (Write Ahead Physical Block Logging).
WAPBL writes metadata updates to a dedicated transaction log before committing them to the filesystem, enabling fast mounts without requiring a full fsck pass after unexpected shutdowns.
# Check filesystem mount configurations in /etc/fstab# Example line:# /dev/wd0a / ffs rw,log 1 1# (log option indicates WAPBL metadata logging is active)
LFS (Log-Structured Filesystem)
NetBSD is one of the few operating systems that supports LFS (Log-Structured Filesystem) natively.
LFS writes all new data and metadata sequentially in a continuous log, maximizing write speeds on write-intensive workloads.
CGD (Cryptographic Disk Device) Partition Encryption
CGD encrypts partitions at the sector level, protecting sensitive data:
# 1. Generate a configuration file for partition cgd0sudo cgdconfig -g -o /etc/cgd/wd0e aes-xts-256# 2. Attach and decrypt partition wd0e, mapping it to /dev/cgd0csudo cgdconfig cgd0 /dev/wd0e# (Enter passphrase to decrypt the volume)# 3. Format the decrypted cgd0c volume with FFSsudo newfs /dev/cgd0c# 4. Mount the volumesudo mount /dev/cgd0c /mnt/secure
ZFS on NetBSD Setup
NetBSD includes native support for the ZFS (Zettabyte File System), ported from the OpenZFS project.
To use ZFS, enable the kernel modules and service daemons:
# Enable ZFS support in /etc/rc.confecho "zfs=YES" | sudo tee -a /etc/rc.confsudo service zfs start# Create a ZFS storage pool named 'datapool' on partition wd1dsudo zpool create datapool /dev/wd1d# Create a filesystem dataset within the poolsudo zfs create datapool/appdata# Enable compression on the datasetsudo zfs set compression=lz4 datapool/appdata# Verify active ZFS status and propertieszpool statuszfs list
RAIDframe (Software RAID Configuration)
NetBSD uses the RAIDframe driver to create software RAID arrays.
To configure a RAID 1 mirror using RAIDframe, define the disk layouts in a configuration file:
# Initialize the RAID array configurationsudo raidctl -C /etc/raid0.conf raid0# Reconstruct the parity channelssudo raidctl -I raid0# Formats RAID device with FFS filesystemsudo newfs /dev/rraid0c
Security Hardening (PaX & Veriexec)
PaX Security Protections
NetBSD includes built-in security features from the PaX project to protect against memory exploitation:
ASLR (Address Space Layout Randomization): Randomizes memory layouts (stack, heap, and library locations) on every execution, making it difficult for exploit code to jump to specific target functions.
MPROTECT: Enforces strict memory permission rules (preventing memory pages from being both writeable and executable at the same time), blocking code execution in writeable buffers.
Segvguard: Detects rapid, repetitive process crashes (indicative of brute-force buffer overflow attempts) and blocks the application from starting for a cool-down period.
# Query state of PaX MPROTECT enforcementssysctl security.pax.mprotect.enabled# Query state of PaX ASLR enforcementssysctl security.pax.aslr.enabled
paxctl: Per-Binary Exceptions
Certain applications, especially compilers and JIT-compilers (like Node Js, Java VMs, or modern web browsers), require generating code dynamically in writeable memory pages and subsequently executing it.
These programs will crash when PaX MPROTECT is globally enabled. To resolve this, use paxctl to disable specific protections on a per-binary basis:
# Disable MPROTECT on a target application binarysudo paxctl +m /usr/pkg/bin/node# Disable ASLR on a target application binarysudo paxctl +a /usr/pkg/bin/legacy_app# Verify the active PaX flags of a binarypaxctl /usr/pkg/bin/node
Veriexec File Integrity Subsystem
Veriexec is NetBSD’s in-kernel file integrity verification subsystem.
It monitors system files by matching their SHA256/SHA512 hashes against a secure signature database (/etc/signatures).
If a system binary (such as sshd or login) is modified by an attacker, the kernel detects the hash mismatch and blocks the binary from executing.
Production Veriexec Configuration (/etc/signatures)
Veriexec runs under specific access enforcement modes, configured using keys in /etc/signatures:
direct: Allows execution of the binary directly from a shell shell.
indirect: Allows execution only via an interpreter or wrapper library (prevents direct user execution).
untrusted: Hash checks are performed on execution, but the file is not protected against runtime modifications (useful for temporary user scripts).
file: Marks the file as a read-only configuration asset, blocking modifications.
# /etc/signatures database file example
# Maps binaries to their hashes and sets strict validation flags
/sbin/init SHA256 3a4918e7c10b2dfc221a63df8bb394c8b26e0e64c129a00832049d5203bbca7b direct,indirect
/usr/sbin/sshd SHA256 a193cf830c23945a8e102f9c8bb2542a1bc3ef401826aa02bc2818aaef38341a direct
/bin/sh SHA256 f3e2d83a48e7129c9c824a73e6f9219aa28bbef503cf92a9128ca8725838efcf untrusted
/etc/rc.conf SHA256 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 file
# Load signatures database into kernelsudo veriexecctl load /etc/signatures
Step-by-Step Veriexec Enforcement Setup
To permanently enable and enforce Veriexec at boot, configure the boot options:
Create /etc/veriexec.conf pointing to your signatures databases:
Set the kernel security level to 1 or 2 in /etc/sysctl.conf to prevent users from altering signatures:
# /etc/sysctl.conf parameters
kern.securelevel=1
Networking & Firewalls
Network Interface Configuration
NetBSD manages network interfaces using static configuration files in /etc/:
Files follow the format /etc/ifconfig.interface_name.
# Configure static IP on interface card 'wm0'# Edit the file /etc/ifconfig.wm0inet 192.168.1.100 netmask 255.255.255.0# Configure interface to use DHCP# Edit the file /etc/ifconfig.wm0updhcp# Apply configurations manuallysudo service network restart
The NPF (NetBSD Packet Filter) Firewall
NPF is NetBSD’s default firewall, designed for high-performance multi-core CPU architectures.
Production NPF Configuration (/etc/npf.conf)
This configuration includes standard packet filtering, table-based dynamic blacklisting, network address translation (NAT), port forwarding mapping, and TCP MSS clamping:
# Define network interfaces
$ext_if = inet4(wm0)
$local_net = { 192.168.1.0/24 }
# Define IP Tables
# Table containing dynamically banned client IP addresses
table <blacklist> type iphash
# Address translation (NAT)
map wm0 dynamic $local_net -> $ext_if
# Port forwarding configuration
# Forward incoming web traffic on port 8080 to internal server 192.168.1.50:80
map wm0 static 192.168.1.50 port 80 <- $ext_if port 8080
# Groups of rules mapping interfaces
group "external" on $ext_if {
# Instantly drop all traffic originating from blacklisted table
block in final from <blacklist>
# Default block incoming traffic
block in all
# TCP MSS Clamping to prevent MTU packet fragmentation
pass stateful out proto tcp flags S/SA mssclamp 1460 all
# Allow SSH and Web traffic
pass stateful in proto tcp to any port { 22, 80, 443 }
# Allow outbound traffic
pass stateful out all
}
group default {
pass out all
pass in all
}
Managing NPF
# Enable and start the NPF firewall servicesudo rcctl enable npfsudo rcctl start npf# Validate configuration file configurationssudo npfctl reload# Query active NPF configurations and tablessudo npfctl show
Virtualization & Unikernels
Rump Kernels as Unikernels
Because NetBSD’s architecture allows drivers and filesystems to run as standalone userspace components, NetBSD is highly popular in the development of unikernels.
Unikernels bundle an application with only the specific operating system drivers it needs to run, compiling them into a lightweight image that boots directly on a hypervisor (such as Xen) in milliseconds.
Xen Hypervisor Support
NetBSD includes native support for the Xen Hypervisor, running as both the management domain (Dom0) and guest domain (DomU):
NetBSD features nvmm (NetBSD Virtual Machine Monitor), a native hypervisor API that provides hardware-accelerated CPU virtualization (Intel VMX and AMD SVM).
To run virtual machines accelerated by nvmm, install QEMU and configure user privileges:
# 1. Load the nvmm kernel modulesudo modload nvmm# 2. Configure permanent loading on boot in /etc/modules.confecho "nvmm" | sudo tee -a /etc/modules.conf# 3. Configure file permissions to allow users in the 'nvmm' group accesssudo chown root:nvmm /dev/nvmmsudo chmod 0660 /dev/nvmmsudo usermod -G nvmm mainuser# 4. Launch QEMU virtual machine using nvmm hardware accelerationqemu-system-x86_64 -accel nvmm \ -m 2048 \ -smp 2 \ -drive file=guest_os.qcow2,if=virtio \ -net nic,model=virtio -net user \ -display curses
Diagnostics, Tuning & Troubleshooting
Runtime Tuning via sysctl
Adjust kernel settings at runtime:
# Enable IP forwardingsudo sysctl -w net.inet.ip.forwarding=1# Adjust maximum socket queue sizesudo sysctl -w kern.somaxconn=512
System Monitoring and Diagnostics
Monitor system resources using these utilities:
top: Monitor CPU usage and running processes.
vmstat: Display virtual memory allocations and page stats.
iostat: Monitor disk I/O metrics.
netstat: Monitor network connections and interfaces.
crash: Analyzes memory crash dumps when the kernel encounters fatal traps:
# Run lockstat to capture kernel lock statistics for 5 secondssudo lockstat sleep 5# Analyze active kernel structures using crashsudo crash -M /dev/mem -N /netbsd
Below is a complete C program simulating NetBSD’s RUMP Kernel architecture.
It runs virtual hardware drivers (such as disk or network adapters) isolated in userspace, mapping systems calls through virtualized rump system calls, and verifying that driver crashes do not crash the host kernel:
Configures virtual interfaces and launches a userspace driver:
#!/bin/sh# ==============================================================================# Script: rump_net_provisioner.sh# Description: Provisions tap interface and starts a userspace network driver.# Author: VR-Rathod# ==============================================================================TAP_IF="tap0"RUMP_IP="192.168.2.10"echo "[INFO] Creating virtual tap network interface..."ifconfig "$TAP_IF" createifconfig "$TAP_IF" inet 192.168.2.1 netmask 255.255.255.0 upecho "[INFO] Launching userspace network driver container..."# Execute rump tcp/ip server mapping tap0 interfacerump_server -d linkstr=tap0,netmodel=tap -p 12345 unix:///tmp/rump_sock# Configure IP on the userspace driver socketrump.ifconfig -socket unix:///tmp/rump_sock shmif0 inet "$RUMP_IP" netmask 255.255.255.0 upecho "[SUCCESS] Userspace driver online. IP: ${RUMP_IP} on shmif0"exit 0
Script 3: Automating pkgsrc CVS trees updates and binary checks
Updates local source repositories and binary packages database:
#!/bin/sh# ==============================================================================# Script: pkgsrc_cron.sh# Description: Automates pkgsrc CVS trees updates and binary audits.# Author: VR-Rathod# ==============================================================================LOG_FILE="/var/log/pkgsrc_updates.log"echo "=== pkgsrc Update cron [$(date)] ===" >> "$LOG_FILE"# 1. Update binary package catalogecho "[INFO] Updating binary package catalogs..." >> "$LOG_FILE"pkgin -y update >> "$LOG_FILE" 2>&1pkgin -y upgrade >> "$LOG_FILE" 2>&1# 2. Update source tree if directory is presentif [ -d "/usr/pkgsrc/.cvs" ]; then echo "[INFO] Updating pkgsrc source tree via CVS..." >> "$LOG_FILE" cd /usr/pkgsrc && cvs update -dP >> "$LOG_FILE" 2>&1fiecho "[SUCCESS] Maintenance updates completed." >> "$LOG_FILE"exit 0
Script 4: Veriexec signature file generator and loader
Automatically updates hash signatures of critical binaries inside the Veriexec database:
#!/bin/sh# ==============================================================================# Script: veriexec_updater.sh# Description: Generates and loads Veriexec signatures for base binaries.# Author: VR-Rathod# ==============================================================================SIG_FILE="/etc/signatures"BIN_PATHS="/bin /sbin /usr/bin /usr/sbin"echo "# Veriexec signatures file - Generated $(date)" > "$SIG_FILE"for path in $BIN_PATHS; do if [ -d "$path" ]; then echo "[INFO] Generating signatures for folder: ${path}" for file in "${path}"/*; do if [ -f "$file" ] && [ -x "$file" ]; then # Calculate SHA256 hash for execution file HASH=$(sha256 -q "$file") echo "${file} SHA256 ${HASH} epath" >> "$SIG_FILE" fi done fidone# Load database into kernel memoryecho "[INFO] Loading signature database..."veriexecctl load "$SIG_FILE"echo "[SUCCESS] Veriexec database is now active."exit 0
Script 5: Cryptographic CGD volume auto-mounter
Automates password decryption and formatting of encrypted storage partitions:
#!/bin/sh# ==============================================================================# Script: cgd_mount.sh# Description: Attaches and decrypts CGD virtual partitions.# Author: VR-Rathod# ==============================================================================CGD_DEV="cgd0"RAW_PART="/dev/wd0e"MOUNT_POINT="/mnt/encrypted_store"echo "[INFO] Attaching encrypted disk partition ${RAW_PART} to ${CGD_DEV}..."cgdconfig "$CGD_DEV" "$RAW_PART"if [ $? -eq 0 ]; then echo "[INFO] Mounting filesystem..." mkdir -p "$MOUNT_POINT" mount "/dev/${CGD_DEV}a" "$MOUNT_POINT" echo "[SUCCESS] CGD partition mounted successfully on ${MOUNT_POINT}"else echo "[ERROR] Decryption password failed." exit 1fiexit 0
NetBSD Command Reference
Complete Command Reference (160+ Commands)
System Administration & Information
sysctl -a # Query all active kernel variablessysctl -w net.inet.ip.forwarding=1 # Enable IP routing immediatelysysctl -w kern.somaxconn=1024 # Query or write maximum socket listen connection queuessysctl kern.version # Read kernel version detailssysctl kern.maxfiles # Query maximum open file descriptors limitsysctl kern.securelevel # Read active kernel security level (0, 1, 2)sysctl hw.ncpu # Query count of active hardware CPU coressysctl hw.physmem64 # Display physical RAM installed in system in bytesuname -a # Display system details, architecture, and kernel versionuname -p # Display the physical processor architecture typedmesg # Read the system boot and kernel message buffersdate # Display or adjust system calendar time settingsuptime # Show system uptime, load averages, and user countshutdown -p now # Power down the system immediatelyreboot # Reboot the system immediatelyservice -l # List all active rc.d scriptsservice httpd status # Query run status of httpd daemon serviceservice httpd start # Start httpd daemon serviceservice httpd restart # Restart httpd daemon serviceservice httpd stop # Stop httpd daemon servicedrvctl -l # List active system device tree linksdrvctl -a # Scan and configure device buses dynamicallylocale # Print active language configurationspciconf -l # List PCI bus hardware devices (compat check)sysinst # Launch interactive system installer utilitypostinstall # Post-upgrade configuration checking toolbuild.sh -m evbarm tools # Compile cross-compiler toolchain for ARM targetsbuild.sh -m evbarm distribution # Compile full distribution files for targetrcorder /etc/rc.d/* # Analyze rc.d dependency start order sequenceconfig -x /netbsd # Extract configuration options used to build running kernelmodload nvmm # Dynamically load the nvmm virtualization kernel modulemodunload nvmm # Dynamically unload the nvmm virtualization kernel modulemodstat # List status of all loaded kernel modulessyspatch # Retrieve and apply official binary patches
Storage, Partitioning & Filesystem Administration
fdisk wd0 # View partition layout on disk wd0fdisk -i wd0 # Initialize partition table on disk wd0fdisk -u wd0 # Update sector mappings in fdisk partition tabledisklabel wd0 # View partitions within drive label wd0disklabel -E wd0 # Edit partitions within drive label wd0disklabel -w wd0 auto # Write a default initial disklabel structure to diskgpt show wd0 # Display GPT partition table layouts on devicegpt create wd0 # Initialize device wd0 with GPT partitions tablegpt add -t ffs -size 10G wd0 # Add a 10GB FFS partition to GPT disknewfs /dev/rwd0a # Format partition with FFS filesystemnewfs_lfs /dev/rwd0a # Format partition with LFS log-structured filesystemfsck -y /dev/rwd0a # Scan and repair FFS partition, auto-fixing issuesfsck_lfs /dev/rwd0a # Scan and repair Log-Structured Filesystem partitionmount /dev/wd0a /mnt # Mount partition to target directory pathmount -o log /dev/wd0a /mnt # Mount partition enabling WAPBL logging metadata writesmount_msdos /dev/wd0e /boot/efi # Mount FAT/EFI system partitionmount_nfs server:/path /mnt # Mount remote Network File System pathmount_tmpfs tmpfs /tmp # Mount dynamic volatile tmpfs storage to /tmpumount /mnt # Unmount target device mount pointdf -h # Display mounted filesystem space usagedu -sh /var/log/ # Calculate directory space usagecgdconfig -g -o aes-xts-256 # Generate CGD encryption configuration profilecgdconfig cgd0 /dev/wd0e # Attach and decrypt CGD encrypted partitioncgdconfig -u cgd0 # Detach/lock encrypted CGD partitiontunefs -p / # Print UFS filesystem config flags statustunefs -l enable / # Enable WAPBL logging permanently on UFS partitionzpool status # Query status of all active ZFS storage poolszpool create zstore /dev/wd1d # Initialize ZFS storage pool named zstorezfs create zstore/data # Create ZFS dataset within zstore poolzfs set compression=lz4 zstore # Enable lz4 compression globally on ZFS poolraidctl -s raid0 # Query mirror status of software RAID device raid0raidctl -R /dev/wd2a raid0 # Reconstruct hot-swap drive replacement on raid0
Process Management, Resource Limits & Diagnostics
ps aux # Display running processesps -axm # List processes displaying thread allocationspgrep -u root sshd # Find process IDs matching criteriapkill -9 -u testuser # Kill processes matching criteria immediatelykill -15 1024 # Terminate process gracefully using SIGTERMkill -9 1024 # Terminate process immediately using SIGKILLtop -o cpu # Monitor system processes, sorted by CPU usagetop -o res # Monitor processes sorted by resident memory sizevmstat -s # Display page allocation statisticsvmstat -i # Display hardware interrupt allocation tableiostat -w 2 # Print disk I/O metrics every two secondssystat -ifstat # Full-screen network interface statisticssystat -vmstat # Full-screen virtual memory and scheduling statisticssystat -iostat # Full-screen disk I/O diagnostics displayfstat -p 1024 # List open files held by specific process IDfstat -u testuser # List open files held by a specific user accountsockstat -4 -l # List processes listening on open TCP/UDP portslimit # Display shell session resource limitsulimit -n 2048 # Adjust open file descriptors limit in shellulimit -c 0 # Disable generation of core dump files in shellnice -n 10 backup.sh # Run process with low priority levelrenice +15 -p 1024 # Lower priority level of active process IDlockstat sleep 2 # Capture kernel lock statistics for two secondsktrace -p 1024 # Enable kernel process execution trace monitoringkdump # Decode and print trace results from ktrace.outgprof /usr/bin/app # Print execution profiling graphs of compiler outputpaxctl /usr/pkg/bin/node # Query PaX protection flags on node binarypaxctl +m /usr/pkg/bin/node # Disable PaX MPROTECT on node execution pathpaxctl +a /usr/pkg/bin/app # Disable PaX ASLR on application binarycrash -M /dev/mem # Launch kernel interactive memory dump analyzer
Networking, Routing & Port Diagnostics
ifconfig # List active network interfaces and configurationsifconfig wm0 up # Enable network interface card wm0ifconfig wm0 down # Disable network interface card wm0ifconfig wm0 inet 192.168.1.5 # Configure IP address on interface wm0ifconfig wm0 alias 10.0.0.5 # Add secondary IP address alias to interfaceifconfig tap0 create # Create virtual tap interface nodeifconfig tap0 destroy # Destroy virtual tap interface noderoute add default 192.168.1.1 # Add default gateway path to routing tableroute change default 10.0.0.1 # Modify active default gateway pathroute show # Display active network routing tablesroute flush # Flush all entries from routing tablesping -c 5 1.1.1.1 # Send ICMP echo requests to verify remote hosttraceroute 8.8.8.8 # Display hop path to remote destinationnetstat -rn # Display active routing tables in numeric formatnetstat -i # Display network interface statisticsnetstat -an | grep LISTEN # List open sockets listening for incoming connectionsnetstat -s # Print protocol packet statistics (TCP/IP/UDP)arp -a # Display ARP IP-to-MAC address mapping tablesarp -d 192.168.1.50 # Delete host entry from local ARP cache tabledig @8.8.8.8 google.com # Perform DNS lookup queries using Google DNShost google.com # Perform quick DNS host resolution querync -zv 192.168.1.100 22 # Test connection to remote port (Netcat)curl -I https://netbsd.org # Fetch HTTP headers of target web serverfetch https://site.com/file.zip # Download file over HTTP/FTPtcpdump -i wm0 # Capture network packets passing through interface wm0tcpdump -vv proto \icmp # Capture packet details matching ICMP protocolndp -an # Display IPv6 neighbor cache mapping detailsaudioctl -a # Print audio hardware device configurationsmixerctl -w outputs.master=200 # Adjust audio mixer volume levels
Package Management (pkgsrc)
pkgin update # Update package repository index catalogpkgin install tmux # Install a binary packagepkgin upgrade # Upgrade installed binary packages to latest versionspkgin remove tmux # Uninstall an installed binary packagepkgin search nmap # Search repositories for matching packagespkgin show tmux # Display metadata details of an installed packagepkgin clean # Clean download package cachespkgin autoremove # Delete orphaned dependenciespkgin list # List all installed binary packages in systempkgin provides tmux # Search which package provides tmux binary pathspkg_info # Display package information metadata detailspkg_add tmux.tgz # Install package manually from tarball filespkg_delete tmux # Delete package bypassing pkgin layerspkg_admin audit # Audit installed packages for known vulnerabilitiespkg_admin fetch-db # Update local package vulnerabilities databasescvs update -dP # Perform updates inside /usr/pkgsrc directory treesmake install clean # Build and clean package within pkgsrc folder pathsmake show-options # Query compile configurations flags inside pkgsrc folder
chflags schg critical_file # Set system immutable flag on a filechflags noschg critical_file # Clear system immutable flag on a filechflags sappnd log_file # Set system append-only flag on a log filels -lao # List directory files displaying system flagsuseradd -m -g =wheel test # Create system user accountuserdel -r test # Delete user account and home directoriesvipw # Safely edit system master password fileveriexecctl load /etc/signatures # Load signatures database into kernel memoryveriexecctl query /bin/ls # Query verification status of a binarynpfctl start # Start the NPF firewall enginenpfctl stop # Stop the NPF firewall enginenpfctl reload # Validate and reload /etc/npf.conf configurationsnpfctl show # Display active NPF rules statusnpfctl validate # Check syntax formatting in /etc/npf.confnpfctl table blacklist add 1.2.3.4 # Dynamically add bad IP to NPF blacklist tablenpfctl table blacklist list # List all IPs currently trapped in NPF tablexl list # List Xen guest domains (install via pkgsrc)xl create -c /etc/xen/domain # Start Xen guest domain consoleqemu-system-x86_64 -accel nvmm # Boot QEMU VM accelerated by nvmm hypervisorrump_server unix:///tmp/sock # Start virtual userspace RUMP kernel serverrump.ifconfig shmif0 inet 10.0.0.1 # Configure IP on virtual RUMP kernel interfacerump.halt # Stop execution of userspace RUMP kernel server