Samba: Difference between revisions

imported>Quentinsf
Update samba systemd service names
Zeal (talk | contribs)
m sudo is needed for this
 
(18 intermediate revisions by 12 users not shown)
Line 1: Line 1:
This guide will help you on how to use samba on nixos.
This guide will help you on how to use samba on nixos.


== Samba Client ==
== Server setup ==
=== cifs mount ===
 
The following snippets shows how to mount a CIFS (Windows) share in NixOS.
Replace all <code><FIELDS></code> with concrete values:
 
<syntaxhighlight lang="nix">
{
  # For mount.cifs, required unless domain name resolution is not needed.
  environment.systemPackages = [ pkgs.cifs-utils ];
  fileSystems."/mnt/share" = {
      device = "//<IP_OR_HOST>/path/to/share";
      fsType = "cifs";
      options = let
        # this line prevents hanging on network split
        automount_opts = "x-systemd.automount,noauto,x-systemd.idle-timeout=60,x-systemd.device-timeout=5s,x-systemd.mount-timeout=5s";
 
      in ["${automount_opts},credentials=/etc/nixos/smb-secrets"];
  };
}
</syntaxhighlight>
 
Also create /etc/nixos/smb-secrets with the following content (<code>domain=</code> can be optional)
 
<syntaxhighlight lang="nix">
username=<USERNAME>
domain=<DOMAIN>
password=<PASSWORD>
</syntaxhighlight>
 
=== mount as user ===
By default, CIFS shares are mounted as root. If mounting as user is desirable, `uid` and `gid` arguments can be provided as part of the filesystem options:
<syntaxhighlight lang="nix">
{
  fileSystems."/mnt/share" = {
    # ... rest of the filesystem config omitted
    options = ["credentials=/etc/nixos/smb-secrets,uid=1000,gid=100"];
    # or if you have specified `uid` and `gid` explicitly through NixOS configuration,
    # you can refer to them rather than hard-coding the values:
    # options = ["credentials=/etc/nixos/smb-secrets,uid=${config.users.users.<username>.uid},gid=${config.users.groups.<group>.gid}"];
  };
}
</syntaxhighlight>


Example setup for creating a public guest share called <code>public</code> and a private share called <code>private</code>.


== Firewall ==
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
Samba discovery of machines and shares may need the firewall to be tuned ([https://wiki.archlinux.org/index.php/Samba#.22Browsing.22_network_fails_with_.22Failed_to_retrieve_share_list_from_server.22 source]):
in <code>/etc/nixos/configuration.nix</code>, add:
<syntaxhighlight lang="nix">
networking.firewall.extraCommands = ''iptables -t raw -A OUTPUT -p udp -m udp --dport 137 -j CT --helper netbios-ns'';
</syntaxhighlight>
 
== Browsing samba shares with GVFS ==
Many GTK-based file managers like Nautilus, Thunar, and PCManFM can browse samba shares thanks to GVFS.
GVFS is a dbus daemon which must be running for this to work.
If you use Gnome, you have nothing to do as the module already enables it for you, but in less full-featured desktop environments, some further configuration options are needed.
 
The generic way of enabling GVFS is to add this in <code>/etc/nixos/configuration.nix</code>:
<syntaxhighlight lang="nix">
services.gvfs.enable = true;
</syntaxhighlight>
 
There are however some special cases.
===== XFCE =====
[[Xfce]] comes with a slimmed-down version of GVFS by default which comes with samba support compiled out. To have smb:// support in Thunar, we will use GNOME's full-featured version of GVFS:
<syntaxhighlight lang="nix">
  services.gvfs = {
    enable = true;
    package = lib.mkForce pkgs.gnome3.gvfs;
  };
</syntaxhighlight>
===== No desktop environment =====
GVFS relies on polkit to gain privileges for some operations. Polkit needs an authentication agent to ask for credentials.
Desktop environments usually provide one but if you have no desktop environment, you may have to install one yourself:
 
Excerpt of <code>/etc/nixos/configuration.nix</code>:
<syntaxhighlight lang="nix">
environment.systemPackages = with pkgs; [ lxqt.lxqt-policykit ]; # provides a default authentification client for policykit
</syntaxhighlight>
 
 
===== DBUS =====
Furthermore, if you happen to start your Window Manager directly, via <code>.xinitrc</code>, or directly invoke a Wayland compositor such as Sway, you should ensure that you launch dbus at startup in your session and export its environment. If you do not have a dbus session in your environment, you will see errors such as "Operation not supported" when attempting to browse the network.
 
For example, if you are using <code>.xinitrc</code>, you could invoke <code>dbus-launch</code>:
<syntaxhighlight lang="bash">
export `dbus-launch` # starts dbus and exports its address
exec xterm # your prefered Window Manager
</syntaxhighlight>
(You need to restart your Window Manager to have the changes in <code>.xinitrc</code> to take place.)
 
If you are using a Wayland compositor like Sway, you can run it under <code>dbus-run-session</code> for the same effect:
<syntaxhighlight lang="bash">
dbus-run-session sway
</syntaxhighlight>
 
(Because <code>dbus-run-session</code> exits when the child process exits, it is only appropriate to use <code>dbus-run-session</code> with a process that will be running during the entire session. This is the case for Wayland compositors, but is not necessarily true for all configurations of X11 window managers.)
 
== Samba Server ==
=== excerpt of /etc/nixos/configuration.nix ===
 
<syntaxhighlight lang="nix">
services.samba-wsdd.enable = true; # make shares visible for windows 10 clients
networking.firewall.allowedTCPPorts = [
  5357 # wsdd
];
networking.firewall.allowedUDPPorts = [
  3702 # wsdd
];
services.samba = {
services.samba = {
   enable = true;
   enable = true;
   securityType = "user";
   openFirewall = true;
   extraConfig = ''
   settings = {
     workgroup = WORKGROUP
     global = {
    server string = smbnix
      "workgroup" = "WORKGROUP";
    netbios name = smbnix
      "server string" = "smbnix";
    security = user  
      "netbios name" = "smbnix";
    #use sendfile = yes
      "security" = "user";
    #max protocol = smb2
      #"use sendfile" = "yes";
    # note: localhost is the ipv6 localhost ::1
      #"max protocol" = "smb2";
    hosts allow = 192.168.0. 127.0.0.1 localhost
      # note: localhost is the ipv6 localhost ::1
    hosts deny = 0.0.0.0/0
      "hosts allow" = "192.168.0. 127.0.0.1 localhost";
    guest account = nobody
      "hosts deny" = "0.0.0.0/0";
    map to guest = bad user
      "guest account" = "nobody";
  '';
      "map to guest" = "bad user";
  shares = {
    };
     public = {
     "public" = {
       path = "/mnt/Shares/Public";
       "path" = "/mnt/Shares/Public";
       browseable = "yes";
       "browseable" = "yes";
       "read only" = "no";
       "read only" = "no";
       "guest ok" = "yes";
       "guest ok" = "yes";
Line 137: Line 33:
       "force group" = "groupname";
       "force group" = "groupname";
     };
     };
     private = {
     "private" = {
       path = "/mnt/Shares/Private";
       "path" = "/mnt/Shares/Private";
       browseable = "yes";
       "browseable" = "yes";
       "read only" = "no";
       "read only" = "no";
       "guest ok" = "no";
       "guest ok" = "no";
Line 149: Line 45:
   };
   };
};
};
</syntaxhighlight>


If your firewall is enabled, or if you consider enabling it:
services.samba-wsdd = {
<syntaxhighlight lang="nix">
  enable = true;
  openFirewall = true;
};
 
services.avahi = {
  publish.enable = true;
  publish.userServices = true;
  # ^^ Needed to allow samba to automatically register mDNS records (without the need for an `extraServiceFile`
  nssmdns4 = true;
  # ^^ Not one hundred percent sure if this is needed- if it aint broke, don't fix it
  enable = true;
  openFirewall = true;
};
 
networking.firewall.enable = true;
networking.firewall.enable = true;
networking.firewall.allowPing = true;
networking.firewall.allowPing = true;
services.samba.openFirewall = true;
</nowiki>}}
</syntaxhighlight>
 
{{Evaluate}}


Samba should startup afterwards.
The <code>samba-wsdd</code> service and avahi is used to advertise the shares to Windows hosts.


=== User Authentication ===
=== User Authentication ===


For a user to be authenticated on the samba server, you must add their password using <code>smbpasswd -a <user></code> as root.
For a user called <code>my_user</code>to be authenticated on the samba server, you must add their password using


=== stopping/restarting the services ===
<syntaxhighlight lang="bash">
<syntaxhighlight lang="console">
sudo smbpasswd -a my_user
# systemctl stop samba-smbd.service
# systemctl start samba-smbd.service
# systemctl restart samba-smbd.service
</syntaxhighlight>
</syntaxhighlight>


=== Use Cases ===
=== Configuration ===
 
==== Apple Time Machine ====
==== Apple Time Machine ====
Example configuration:
 
In addition to the example above, add this to your configuration:
 
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
services.samba = {
services.samba = {
   shares = {
   settings = {
     tm_share = {
     "tm_share" = {
         path = "/mnt/Shares/tm_share";
         "path" = "/mnt/Shares/tm_share";
         "valid users" = "username";
         "valid users" = "username";
         public = "no";
         "public" = "no";
         writeable = "yes";
         "writeable" = "yes";
         "force user" = "username";
         "force user" = "username";
        # Below are the most imporant for macOS compatibility
        # Change the above to suit your needs
         "fruit:aapl" = "yes";
         "fruit:aapl" = "yes";
         "fruit:time machine" = "yes";
         "fruit:time machine" = "yes";
Line 190: Line 97:
     };
     };
   };
   };
}
};
 
# Ensure Time Machine can discover the share without `tmutil`
services.avahi = {
  extraServiceFiles = {
    timemachine = ''
      <?xml version="1.0" standalone='no'?>
      <!DOCTYPE service-group SYSTEM "avahi-service.dtd">
      <service-group>
        <name replace-wildcards="yes">%h</name>
        <service>
          <type>_smb._tcp</type>
          <port>445</port>
        </service>
          <service>
          <type>_device-info._tcp</type>
          <port>0</port>
          <txt-record>model=TimeCapsule8,119</txt-record>
        </service>
        <service>
          <type>_adisk._tcp</type>
          <!--
            change tm_share to share name, if you changed it.
          -->
          <txt-record>dk0=adVN=tm_share,adVF=0x82</txt-record>
          <txt-record>sys=waMa=0,adVF=0x100</txt-record>
        </service>
      </service-group>
    '';
  };
};
</syntaxhighlight>
</syntaxhighlight>


==== Printer sharing ====
==== Printer sharing ====
The `samba` packages comes without cups support compiled in, however `sambaFull` features printer sharing support.
To use it set the `services.samba.package` option:


<syntaxhighlight lang=nix>
<syntaxhighlight lang=nix>
Line 202: Line 136:
</syntaxhighlight>
</syntaxhighlight>


A printer share that allows all members in the local network printing could look like this:
A printer share that allows printing to all members in the local network


<syntaxhighlight lang=nix>
{{file|/etc/nixos/configuration.nix|nix|<nowiki>
{ pkgs, ... }: {
services.samba = {
  services.samba = {
  enable = true;
    enable = true;
  package = pkgs.sambaFull;
    package = pkgs.sambaFull;
  openFirewall = true;
    openFirewall = true; # Automatically open firewall ports
  settings = {
     extraConfig = ''
     "global" = {
       load printers = yes
       "load printers" = "yes";
       printing = cups
       "printing" = "cups";
       printcap name = cups
       "printcap name" = "cups";
     '';
     };
     shares = {
     "printers" = {
       printers = {
       "comment" = "All Printers";
        comment = "All Printers";
      "path" = "/var/spool/samba";
        path = "/var/spool/samba";
      "public" = "yes";
        public = "yes";
      "browseable" = "yes";
        browseable = "yes";
      # to allow user 'guest account' to print.
        # to allow user 'guest account' to print.
      "guest ok" = "yes";
        "guest ok" = "yes";
      "writable" = "no";
        writable = "no";
      "printable" = "yes";
        printable = "yes";
      "create mode" = 0700;
        "create mode" = 0700;
      };
     };
     };
   };
   };
  systemd.tmpfiles.rules = [
};
    "d /var/spool/samba 1777 root root -"
systemd.tmpfiles.rules = [
  ];
  "d /var/spool/samba 1777 root root -"
}
];
</syntaxhighlight>
</nowiki>}}
 
The `samba` packages comes without [[Printing|CUPS printing]] support compiled in, however `sambaFull` features printer sharing support.


==== Active Directory Domain Controller ====
==== Active Directory Domain Controller ====
Line 273: Line 207:
       # Set pythonpath manually (bellow with overrideAttrs) as it is not set on 22.11 due to bug
       # Set pythonpath manually (bellow with overrideAttrs) as it is not set on 22.11 due to bug
     }).overrideAttrs (finalAttrs: previousAttrs: {
     }).overrideAttrs (finalAttrs: previousAttrs: {
         pythonPath = with super; [ python3Packages.dnspython tdb ldb talloc ];
         pythonPath = with super; [ python3Packages.dnspython python3Packages.markdown tdb ldb talloc ];
       });
       });
   })];
   })];
Line 333: Line 267:
Then restart the samba service with <code>sudo systemctl restart samba</code>, and you're ready to go!
Then restart the samba service with <code>sudo systemctl restart samba</code>, and you're ready to go!


==Troubleshooting==
== Samba Client ==
=== Server log ===
 
<pre>
=== CIFS mount configuration ===
sudo journalctl -u samba-smbd.service -f
 
</pre>
The following snippets shows how to mount a CIFS (Windows) share in NixOS.
Replace all <code><FIELDS></code> with concrete values:
 
<syntaxhighlight lang="nix">
{
  # For mount.cifs, required unless domain name resolution is not needed.
  environment.systemPackages = [ pkgs.cifs-utils ];
  fileSystems."/mnt/share" = {
    device = "//<IP_OR_HOST>/path/to/share";
    fsType = "cifs";
    options = let
      # this line prevents hanging on network split
      automount_opts = "x-systemd.automount,noauto,x-systemd.idle-timeout=60,x-systemd.device-timeout=5s,x-systemd.mount-timeout=5s";
 
    in ["${automount_opts},credentials=/etc/nixos/smb-secrets"];
  };
}
</syntaxhighlight>
 
Also create /etc/nixos/smb-secrets with the following content (<code>domain=</code> can be optional)
 
<syntaxhighlight lang="nix">
username=<USERNAME>
domain=<DOMAIN>
password=<PASSWORD>
</syntaxhighlight>
 
By default, CIFS shares are mounted as root. If mounting as user is desirable, `uid`, `gid` and usergroup arguments can be provided as part of the filesystem options:
<syntaxhighlight lang="nix">
{
  fileSystems."/mnt/share" = {
    # ... rest of the filesystem config omitted
    options = let
      automount_opts = "x-systemd.automount,noauto,x-systemd.idle-timeout=60,x-systemd.device-timeout=5s,x-systemd.mount-timeout=5s,user,users";
 
      in ["${automount_opts},credentials=/etc/nixos/smb-secrets,uid=1000,gid=100"];
    # or if you have specified `uid` and `gid` explicitly through NixOS configuration,
    # you can refer to them rather than hard-coding the values:
    # in ["${automount_opts},credentials=/etc/nixos/smb-secrets,uid=${toString config.users.users.<username>.uid},gid=${toString config.users.groups.<group>.gid}"];
  };
}
</syntaxhighlight>
 
=== Firewall configuration ===
 
Samba discovery of machines and shares may need the firewall to be tuned ([https://wiki.archlinux.org/index.php/Samba#.22Browsing.22_network_fails_with_.22Failed_to_retrieve_share_list_from_server.22 source]):
in <code>/etc/nixos/configuration.nix</code>, add:
<syntaxhighlight lang="nix">
networking.firewall.extraCommands = ''iptables -t raw -A OUTPUT -p udp -m udp --dport 137 -j CT --helper netbios-ns'';
</syntaxhighlight>
 
=== Command line ===


=== Stale file handle ===
List shares
Trying to read the contents of a remote file leads to the following error message: "Stale file handle". If you have mounted a share via the method described in "cfis mount", adding the option <code>noserverino</code> might fix this problem. [https://askubuntu.com/questions/1265164/stale-file-handler-when-mounting-cifs-smb-network-drive-from-fritz-router]


=== List shares ===
<pre>
<pre>
smbclient --list localhost
smbclient --list localhost
Line 360: Line 343:
</pre>
</pre>


=== NT_STATUS_INVALID_NETWORK_RESPONSE ===
Mount as guest. <code>public</code> is your share name
 
The error
<code>protocol negotiation failed: NT_STATUS_INVALID_NETWORK_RESPONSE</code>
means "access denied".
Probably you must fix your server's <code>hosts allow</code> section.
Note that <code>localhost</code> is the ipv6 localhost <code>::1</code>,
and <code>127.0.0.1</code> is the ipv4 localhost
 
=== Mount shares ===
mount as guest. <code>public</code> is your share name


<pre>
<pre>
Line 386: Line 359:
<code>sec=ntlmssp</code> should work.
<code>sec=ntlmssp</code> should work.
for more values, see `man mount.cifs` (search for `sec=arg`)
for more values, see `man mount.cifs` (search for `sec=arg`)
=== Browsing samba shares with GVFS ===
Many GTK-based file managers like Nautilus, Thunar, and PCManFM can browse samba shares thanks to GVFS.
GVFS is a dbus daemon which must be running for this to work.
If you use Gnome, you have nothing to do as the module already enables it for you, but in less full-featured desktop environments, some further configuration options are needed.
The generic way of enabling GVFS is to add this in <code>/etc/nixos/configuration.nix</code>:
<syntaxhighlight lang="nix">
services.gvfs.enable = true;
</syntaxhighlight>
There are however some special cases.
===== XFCE =====
[[Xfce]] comes with a slimmed-down version of GVFS by default which comes with samba support compiled out. To have smb:// support in Thunar, we will use GNOME's full-featured version of GVFS:
<syntaxhighlight lang="nix">
  services.gvfs = {
    enable = true;
    package = lib.mkForce pkgs.gnome.gvfs;
  };
</syntaxhighlight>
===== No desktop environment =====
GVFS relies on polkit to gain privileges for some operations. Polkit needs an authentication agent to ask for credentials.
Desktop environments usually provide one but if you have no desktop environment, you may have to install one yourself:
Excerpt of <code>/etc/nixos/configuration.nix</code>:
<syntaxhighlight lang="nix">
environment.systemPackages = with pkgs; [ lxqt.lxqt-policykit ]; # provides a default authentification client for policykit
</syntaxhighlight>
===== DBUS =====
Furthermore, if you happen to start your Window Manager directly, via <code>.xinitrc</code>, or directly invoke a Wayland compositor such as Sway, you should ensure that you launch dbus at startup in your session and export its environment. If you do not have a dbus session in your environment, you will see errors such as "Operation not supported" when attempting to browse the network.
For example, if you are using <code>.xinitrc</code>, you could invoke <code>dbus-launch</code>:
<syntaxhighlight lang="bash">
export `dbus-launch` # starts dbus and exports its address
exec xterm # your prefered Window Manager
</syntaxhighlight>
(You need to restart your Window Manager to have the changes in <code>.xinitrc</code> to take place.)
If you are using a Wayland compositor like Sway, you can run it under <code>dbus-run-session</code> for the same effect:
<syntaxhighlight lang="bash">
dbus-run-session sway
</syntaxhighlight>
(Because <code>dbus-run-session</code> exits when the child process exits, it is only appropriate to use <code>dbus-run-session</code> with a process that will be running during the entire session. This is the case for Wayland compositors, but is not necessarily true for all configurations of X11 window managers.)
== Troubleshooting ==
=== Server log ===
<pre>
sudo journalctl -u samba-smbd.service -f
</pre>
=== Stale file handle ===
Trying to read the contents of a remote file leads to the following error message: "Stale file handle". If you have mounted a share via the method described in "cfis mount", adding the option <code>noserverino</code> might fix this problem. [https://askubuntu.com/questions/1265164/stale-file-handler-when-mounting-cifs-smb-network-drive-from-fritz-router]
=== NT_STATUS_INVALID_NETWORK_RESPONSE ===
The error
<code>protocol negotiation failed: NT_STATUS_INVALID_NETWORK_RESPONSE</code>
means "access denied".
Probably you must fix your server's <code>hosts allow</code> section.
Note that <code>localhost</code> is the ipv6 localhost <code>::1</code>,
and <code>127.0.0.1</code> is the ipv4 localhost


=== Permission denied ===
=== Permission denied ===
Maybe check the <code>guest account</code> setting in your server config.
Maybe check the <code>guest account</code> setting in your server config.
The default value is <code>nobody</code>,
The default value is <code>nobody</code>,
Line 402: Line 448:


== See also ==
== See also ==
* [https://search.nixos.org/options?channel=unstable&from=0&size=50&sort=relevance&type=packages&query=services.samba Samba Options in NixOS on unstable]
* [https://search.nixos.org/options?channel=unstable&from=0&size=50&sort=relevance&type=packages&query=services.samba Samba Options in NixOS on unstable]
* [https://wiki.archlinux.org/title/Samba Samba in the Arch Linux Wiki]
* [https://wiki.archlinux.org/title/Samba Samba in the Arch Linux Wiki]


[[Category:Services]]
[[Category:Server]]
[[Category:Applications]]