Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions nixos/doc/manual/release-notes/rl-2505.section.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@

- [µStreamer](https://github.com/pikvm/ustreamer), a lightweight MJPEG-HTTP streamer. Available as [services.ustreamer](options.html#opt-services.ustreamer).

- [ynetd](https://yx7.cc/code/), a small server for binding programs to TCP ports. Available as [services.ynetd](options.html#opt-services.ynetd).

- [Whoogle Search](https://github.com/benbusby/whoogle-search), a self-hosted, ad-free, privacy-respecting metasearch engine. Available as [services.whoogle-search](options.html#opt-services.whoogle-search.enable).

- [autobrr](https://autobrr.com), a modern download automation tool for torrents and usenets. Available as [services.autobrr](#opt-services.autobrr.enable).
Expand Down
1 change: 1 addition & 0 deletions nixos/modules/module-list.nix
Original file line number Diff line number Diff line change
Expand Up @@ -917,6 +917,7 @@
./services/misc/weechat.nix
./services/misc/workout-tracker.nix
./services/misc/xmrig.nix
./services/misc/ynetd.nix
./services/misc/ytdl-sub.nix
./services/misc/zoneminder.nix
./services/misc/zookeeper.nix
Expand Down
23 changes: 23 additions & 0 deletions nixos/modules/programs/ynetd.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
config,
lib,
pkgs,
...
}:

with lib;

let
cfg = config.programs.ynetd;
in
{
options = {
programs.ynetd = {
enable = mkEnableOption "Small server for binding programs to TCP ports";
};
};

config = mkIf cfg.enable {
environment.systemPackages = pkgs.ynetd;
};
}
103 changes: 103 additions & 0 deletions nixos/modules/services/misc/ynetd.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
{
config,
lib,
pkgs,
...
}:

with lib;

let
cfg = config.services.ynetd;

instanceOpts =
{ name, config, ... }:
{
options = {
enable = mkEnableOption "ynetd instance ${name}";

bindAddress = mkOption {
type = types.nonEmptyStr;
default = "::";
description = "IP address to bind to";
};

port = mkOption {
type = types.port;
description = "TCP port to bind to";
};

user = mkOption {
type = types.nonEmptyStr;
default = "nobody";
description = "Username to run the service as";
};

workingDir = mkOption {
type = types.nullOr types.path;
default = "";
description = "Working directory for the command";
};

command = mkOption {
type = types.nonEmptyStr;
description = "Command to execute for each connection";
};

extraFlags = mkOption {
type = types.str;
default = "";
description = "Additional flags to pass to ynetd";
};
};
};

# Generate systemd service for an instance
mkService = name: instanceCfg: {
description = "ynetd service for ${name}";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];

serviceConfig = {
ExecStart = ''
${cfg.package}/bin/ynetd \
-a ${instanceCfg.bindAddress} \
-p ${toString instanceCfg.port} \
-u ${instanceCfg.user} \
${optionalString (instanceCfg.workingDir != "") "-d ${instanceCfg.workingDir}"} \
${instanceCfg.extraFlags} \
"${instanceCfg.command}"
'';
User = "root";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this need to be root? Can a systemd user or whatever not be used?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the bit I feel a little uneasy regarding, I have a little explanation in the second paragraph of my PR, like we could set it to a less powerful user, but then for cgroups I believe it would need CAP_SYS_ADMIN at which point it's basically root just under another name.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if I go through and model more of the flags I can dynamically apply some of the CAP for the unhardened ynetd. I'll go through and see how this looks

Restart = "always";
RestartSec = "5s";
};
};
in
{
options.services.ynetd = {
enable = mkEnableOption "ynetd service";

package = mkOption {
type = types.package;
default = pkgs.ynetd;
defaultText = literalExpression "pkgs.ynetd";
description = "The ynetd package to use (can be overridden with pkgs.ynetd.hardened for hardened version)";
};

instances = mkOption {
type = types.attrsOf (types.submodule instanceOpts);
default = { };
description = "Attribute set of ynetd instances";
};
};

config = mkIf cfg.enable {
# Create systemd services for each enabled instance
systemd.services = mapAttrs' (
name: instanceCfg: nameValuePair "ynetd-${name}" (mkService name instanceCfg)
) (filterAttrs (_: instanceCfg: instanceCfg.enable) cfg.instances);

environment.systemPackages = [ cfg.package ];
};
}
2 changes: 2 additions & 0 deletions nixos/tests/all-tests.nix
Original file line number Diff line number Diff line change
Expand Up @@ -1320,6 +1320,8 @@ in {
yabar = runTest ./yabar.nix;
ydotool = handleTest ./ydotool.nix {};
yggdrasil = runTest ./yggdrasil.nix;
ynetd = runTest ./ynetd.nix;
ynetd-hardened = runTest ./ynetd-hardened.nix;
your_spotify = runTest ./your_spotify.nix;
zammad = runTest ./zammad.nix;
zenohd = runTest ./zenohd.nix;
Expand Down
113 changes: 113 additions & 0 deletions nixos/tests/ynetd-hardened.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import ./make-test-python.nix (
{ lib, pkgs, ... }:
let
powSolverScript = pkgs.writeTextFile {
name = "pow-solver-script.py";
text = ''
import socket
import re
import subprocess
import sys
import time

def main():
# Connect to the service
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 7000))

# Get the challenge
challenge = s.recv(1024).decode('utf-8')
print(f"Received challenge: {challenge}")

# Extract the hex string from the challenge
hex_match = re.search(r'unhex\("([0-9a-f]+)"', challenge)
if not hex_match:
print("Could not extract hex string from challenge")
return 1

hex_string = hex_match.group(1)

# Extract the number of zero bits
bits_match = re.search(r'(\d+) zero bits', challenge)
if not bits_match:
print("Could not extract zero bits from challenge")
return 1

zero_bits = bits_match.group(1)

# Solve the PoW challenge
solver_cmd = ["${pkgs.ynetd.hardened}/bin/pow-solver", zero_bits, hex_string]
solution = subprocess.check_output(solver_cmd).decode('utf-8').strip()
print(f"Solution: {solution}")

# Send the solution
s.sendall((solution + '\n').encode('utf-8'))

# Wait a bit for the service to process the solution
time.sleep(0.5)

# Send our test message
test_message = "Hello from hardened!\n"
s.sendall(test_message.encode('utf-8'))

# Get the response
response = s.recv(1024).decode('utf-8')
print(f"Response: {response}")

# Check if our message was echoed back
if "Hello from hardened!" in response:
print("Test passed!")
return 0
else:
print("Test failed!")
return 1

if __name__ == "__main__":
sys.exit(main())
'';
executable = true;
destination = "/bin/pow-solver-script.py";
};
in
{
name = "ynetd-hardened";

nodes.machine = {
services.ynetd = {
enable = true;
package = pkgs.ynetd.hardened;

instances = {
echo = {
enable = true;
port = 7000;
command = "${pkgs.coreutils}/bin/cat";
extraFlags = "-pow 5";
};
};
};

# Include our solver script
environment.systemPackages = [ powSolverScript ];
};

testScript = ''
start_all()

machine.wait_for_unit("ynetd-echo.service")
machine.wait_for_open_port(7000)

# Run the test script
test_result = machine.succeed("${pkgs.python3}/bin/python3 ${powSolverScript}/bin/pow-solver-script.py")
print(f"Hardened test result: {test_result}")

# Verify the test passed
assert "Test passed!" in test_result, "Hardened echo service test failed"

# Verify service is active
machine.succeed("systemctl is-active ynetd-echo.service")
'';

meta.maintainers = [ lib.maintainers.haylin ];
}
)
66 changes: 66 additions & 0 deletions nixos/tests/ynetd.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import ./make-test-python.nix (
{ lib, pkgs, ... }:
{
name = "ynetd";

nodes.machine = {
services.ynetd = {
enable = true;

instances = {
echo = {
enable = true;
port = 7000;
command = "${pkgs.coreutils}/bin/cat";
};

shell = {
enable = true;
port = 7001;
command = "${pkgs.bash}/bin/bash -i";
extraFlags = "-se y";
};
};
};
};

testScript = ''
start_all()

machine.wait_for_unit("ynetd-echo.service")
machine.wait_for_unit("ynetd-shell.service")

machine.wait_for_open_port(7000)
machine.wait_for_open_port(7001)

# Test echo service
echo_output = machine.succeed("echo 'Hello, world!' | nc -w 1 localhost 7000")
assert "Hello, world!" in echo_output, f"Echo service failed: {echo_output}"

# Test security
machine.succeed("""
cat > /tmp/shell_commands.txt << 'EOF'
id -u -n
cat /etc/shadow
exit
EOF
""")

# Send commands to the shell service and capture output
security_output = machine.succeed("cat /tmp/shell_commands.txt | nc -w 2 localhost 7001")
print(f"Security check output: {security_output}")

# Verify running as nobody
assert "nobody" in security_output, "Service not running as nobody user"

# Verify cannot read /etc/shadow
assert "Permission denied" in security_output, "Expected permission denied when trying to read /etc/shadow"

# Verify services are active
machine.succeed("systemctl is-active ynetd-echo.service")
machine.succeed("systemctl is-active ynetd-shell.service")
'';

meta.maintainers = [ lib.maintainers.haylin ];
}
)
5 changes: 5 additions & 0 deletions pkgs/by-name/yn/ynetd/package.nix
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
stdenv,
fetchurl,
callPackage,
nixosTests,
}:
stdenv.mkDerivation (finalAttrs: {
pname = "ynetd";
Expand All @@ -27,6 +28,10 @@ stdenv.mkDerivation (finalAttrs: {
# these should be kept in sync when possible
passthru.hardened = callPackage ./hardened.nix { };

passthru.tests = {
test = nixosTests.ynetd;
};

meta = {
description = "Small server for binding programs to TCP ports";
homepage = "https://yx7.cc/code/";
Expand Down