-
-
Save betaboon/c434934c217b3f1a4f86b8047c489240 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ pkgs, config | |
, secrets ? {} | |
, directory ? "/var/lib/sftp-server" | |
, listenAddress ? "0.0.0.0" | |
, sftpListenPort ? 2121 | |
, ... | |
}: | |
with pkgs.lib; | |
let | |
sftpGroup = "sftpusers"; | |
mkUserFromSecret = { secret, name, homeDirectory }: | |
assert | |
(builtins.hasAttr "keys" secret) | |
|| (builtins.hasAttr "password" secret) | |
|| (builtins.hasAttr "hashedPassword" secret); | |
assert !( | |
(builtins.hasAttr "keys" secret) | |
&& (builtins.hasAttr "password" secret) | |
&& (builtins.hasAttr "hashedPassword" secret) | |
); | |
{ | |
extraGroups = [ | |
sftpGroup | |
]; | |
home = homeDirectory; | |
createHome = true; | |
openssh.authorizedKeys.keys = mkIf (builtins.hasAttr "keys" secret) secret.keys; | |
password = mkIf (builtins.hasAttr "password" secret) secret.password; | |
hashedPassword = mkIf (builtins.hasAttr "hashedPassword" secret) secret.hashedPassword; | |
}; | |
mkUsersFromSecrets = { secrets, homeDirectoryBase }: | |
mapAttrs' (name: secret: nameValuePair name (mkUserFromSecret { | |
inherit name secret; | |
homeDirectory = "${homeDirectoryBase}/${name}"; | |
})) secrets; | |
in { | |
networking.firewall.allowedTCPPorts = [ | |
sftpListenPort | |
]; | |
system.activationScripts.data = '' | |
mkdir -p ${directory} | |
chmod 111 ${directory} | |
''; | |
# this is done in order to prevent creation of .nix-profile-symlink in $HOME | |
environment.shellInit = ""; | |
users.groups."${sftpGroup}" = {}; | |
users.users = mkUsersFromSecrets { | |
inherit secrets; | |
homeDirectoryBase = directory; | |
}; | |
services.openssh = { | |
enable = true; | |
listenAddresses = [ | |
{ addr = listenAddress; port = sftpListenPort; } | |
# the following rule takes all ports from config.services.openssh.ports | |
# this is done in order to stay reachable on eg port 22 for nixops | |
{ addr = "0.0.0.0"; } | |
]; | |
kexAlgorithms = [ | |
"curve25519-sha256@libssh.org" | |
"diffie-hellman-group-exchange-sha256" | |
"diffie-hellman-group14-sha1" | |
]; | |
extraConfig = '' | |
Match Group ${sftpGroup} | |
ChrootDirectory ${directory} | |
ForceCommand internal-sftp -d %u | |
PasswordAuthentication no | |
AllowAgentForwarding no | |
AllowTcpForwarding no | |
AllowStreamLocalForwarding no | |
X11Forwarding no | |
PermitTunnel no | |
''; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment