完美的 Standalone Samba Server

 最後更新: 2021-09-13

介紹

 


介紹

 

Samba 是以 CIFS(Common Internet File System) 協定來實現檔案傳輸的 File Server 來

這裡的 Standalone 是指 Samba 獨立地在 Network 上存在, 它既不是 domain controller 又沒有 join domain.

 


Samba 的 3 個 Service

 

nmbd

This daemon handles all name registration and resolution requests.
(It is the primary vehicle involved in network browsing.)

If Samba is not running as a WINS server, then there will be one single instance of nmbd running on your system.

If it is running as a WINS server, then there will be two instances one to handle the WINS requests.

smbd

local authentication
* should be started immediately following the startup of nmbd.
* smbd is the server message daemon
* spawns a new process for each client connection made.

winbindd

* This daemon should be started when Samba is a member of a
   Windows NT4 or ADS domain. idmap uid and idmap gid
* daemon that handles communication with domain controllers.
* winbindd will run as one or two daemons

 


Samba Backports

 

# U16

add-apt-repository ppa:mumblepins/samba-backports

apt-get update

apt-get install samba

 


Samba 的最基本設定

 

位置:

/etc/samba/smb.conf

smb.conf 是由一個個不同的 sections 所構成的設定檔, 每個 section 都是以 [] 開頭

而設定項目則是由 key/value pairs 所組成

最少設定如下:

# mini configure
; also is comment

[global]
    workgroup = WORKGROUP
    netbios name = FileServer

[homes]
    comment = Home Directories
    # %S = Server share name ([tim] => %S=tim)
    valid users = %S
    read only = No
    browseable = No

[Public_Share]
    path = /home/Public_Folder
    comment = Some Public Share files
    # 多行過一行的設定
    invalid users = root bin daemon adm sync shutdown \
                halt mail news ftp

Default 設設定值:

  • guest ok = no                      # 沒有帳戶的人可否用此資源 (guest ok = yes 相當於 public = yes)
  • read-only = yes                   # 可否寫東西入去
  • browseable = yes                 # 當 \\fileserver 時是否可見
  • valid users = NULL               # 什麼用戶可用此服務, 當是 'NULL' 時, 即任何人都可以
  • available = yes                    # 是否啟用此服務

[homes]

# 所有系統 User A/C 都有自己名義的 Shared Folder

valid users = %S

# 指定 User 才有 home shared folder

valid users = user1 user2

 


Network

 

只在某介面卡啟用 samba 服務:

interfaces = eth* lo 192.168.123.0/24
bind interfaces only = yes

Default: bind interfaces only = no

Firewall 要開的 port:

舊 Server 內的:

Port 137/UDP - used by nmbd (NetBIOS name service (WINS))
Port 138/UDP - used by nmbd (NetBIOS datagram)
Port 139/TCP - used by smbd (TCP NetBIOS Session, Windows File and Printer Sharing)

新 Server 用的:

Port 445/TCP - used by smbd  (Microsoft-DS Active Directory, Windows shares)
Port 445/UDP - used by smbd (Microsoft-DS SMB file sharing)

Protocol:

SMB 2.1

  • Windows 7
  • Server 2008 R2

SMB 3.0

  • Windows 8
  • Windows Server 2012

新功能:

SMB Multichannel
(multiple connections per SMB session)

hosts allow 的 list

# 只有 hosts allow 設定時, 只有 list 上的人可用
# 只有 hosts deny 設定時, list 以外的人可用
# 當兩者都存在時, 在 allow 而不在 deny list 的人可用

hosts allow = 192.168.0. 192.168.123.
hosts deny =  192.168.123.1

 


Unicode/Charsets

 

dos charset = UTF8
unix charset = UTF8
display charset = UTF8

 


Master Browser

 

由選舉產生, 負責整理一份本地資源表

browse list = yes (default)

smbd(8) will serve a browse list to a client

local master = yes
# 是否要參加 local master browser 的選舉

os level = 255
# local master browser 選舉時用的值, 愈大愈易成為  local master
# 它存在卡一個 broadcast-isolated subnets

domain master = yes
# wide area 的 browser master
# 所有 local master browser 都會比自己的 list 它
# 這些資訊最後會成為 "domain-wide browse list"

preferred master = yes

#  nmbd 啟動時會發起選舉

P.S. 找出 master

nmblookup -M <Workgroup>

-M   Searches for a master browser by looking up the NetBIOS

querying Workgroup on 192.168.123.255
192.168.123.21 Workgroup<1d>

 


建立用戶及管理(smbpasswd, pdbedit)

 

# 建立系統用戶 (linux 用戶)

useradd user_name

# 建立 samba 用戶 (samba 用戶必須要是 Linux 系統用戶, 但 Shell 可以是 /bin/false !!)

smbpasswd -a user_name

                  OR

pdbedit -au user_name

# 列出所有帳戶

pdbedit -L [user_name]

ie.

test:2005:

# 停用及啟用帳戶

# 停用

    smbpasswd -d user_name

# 啟用

    smbpasswd -e user_name

# 刪除帳戶

smbpasswd -x user_name

OR

pdbedit -xu username

 


pdbedit

 

-f fullname

Example: -f "tester"

-h homedir

Example: -h "\\\\BERSERKER\\sorce"

-i|--import

Example: pdbedit -i smbpasswd:/etc/smbpasswd.old

-e|--export

Example: pdbedit -e smbpasswd:/root/samba-users.backup

backend: passdb(default) smbpasswd xml

 


WINS 及 Time Server

 

wins 是遠古的 window 功能來, 它的目的與 DNS 差不多 ~

連接本地的 wins server

    wins server = 192.168.1.1

自己成為 wins server

wins support = yes
dns proxy = no
name resolve order = host wins bcast

# 當找不同相應的名稱的主機時, 就不再去問 DNS Server

自已成為 Window 上的 time server

time server =yes

測試:

C:\>net time \\fileserver
\\fileserver 現在的時間是 2011/12/25 下午 07:23

命令執行成功。

 

time 及 wins 這兩個 Service 同時是由 nmbd 負責

 


查視設定值

 

Compile Samba 時的設定:

smbd -b | less

Build environment:
...

Paths:
...
CONFIGFILE: /etc/samba/smb.conf
...

smb.conf 的設定值(-v: 連預設值):

testparm -v

精簡化設定檔:

root#  testparm -s smb.conf.master > smb.conf

 


Samba 上的 "admin users"

 

admin users = datahunter

被指定的用戶能無視 Linux 的檔案系統權限, 可任意 read/write !!

它會用 root 的身份 access file, 所以他建立的檔案的 owner 是 root

 * "valid users" 係控制權限, "admin users" 係 fs permission

 


Samba 的資料庫 (*.tdb)

 

DB Path

Centos: /var/cache/samba/*.tdb

Debian: /var/lib/samba/*.tdb

tdb = Trivial Database

ls *.tdb

account_policy.tdb
group_mapping.tdb
passdb.tdb                # smbpasswd 建立的 user
registry.tdb
secrets.tdb
share_info.tdb

tdbdump

我們可以用 tdbdump 查看它的內容

tdbtool

tdbtool TDBFILE [COMMANDS...]

COMMANDS

create TDBFILE   # Create a new database named TDBFILE.

open TDBFILE     # Open an existing database named TDBFILE.

keys                   # Dump the current database keys as strings

info                    # Print summary information about the current database.
                             i.e. 5 records totalling 422 bytes

insert KEY DATA          # Insert a record into the current database.

move KEY TDBFILE      # Move a record from the current database into TDBFILE.

store KEY DATA           # Store (replace) a record in the current database.

show KEY                   # Show a record by key.

delete KEY                  # Delete a record by key.

list               # Print the current database hash table and free list.

free             # Print the current database and free list.

 


Samba 上的 Group list

 

  • @
  • +
  • &

 


矛盾的存在

 

在 samba 上很多 configure 的選項都是矛盾地存在的, 在字面上真是很難明白它們想做什麼 ~

以下一一為大家解說

 

read only 與 writeable

read only 及 writeable 就是其中一組, 它們好明顯是相反的一對, 不過它們是"同義"的

即是說, 它們兩者只可存在一個, 不能兩個同時存在

 

read only = no   即是     writable = yes , 它們是沒有分別的 !!

 

write list 與 read list

此外, smb.conf 上又有另一對矛盾的朋友 "write list" 及 "read list"

它們兩個都個無視 "read only" 的存在, 亦即是說

當 "read only = yes" 時, 在 "write list" 上的朋友依然有 write,

相反, 當 "read only = no" 時, 在 "read list" 上的朋友只有 read !!!

 * 當帳戶同時存在於 write list 及 read list 時, 最終用戶是有 write 的 !!

 

hosts allow 與  hosts deny

當一同時存在卡 hosts allow 及  hosts deny 時, 最終是 allow 的 !!

Example:

hosts allow = 127.0.0.1 192.168.123.0/24
hosts deny = 0.0.0.0/0

 


force group 與 force user

 

強制所有用此"分享"的用戶所獲得的"身份",

所有人都會用此"身份"去續寫檔案/目錄.

'+' character

force group = +smbgrp

only users who are already members of [group] will have their primary group changed to [group]

Ohter user not affected by this directive

Example: 配會 "force create mode" 及 "force directory mode" 使用

force group = smbgrp
force create mode = 0660
force directory mode = 0770

 


隱藏檔案

 

[data]
    # Samba reports files beginning with a period "." as having their hidden attribute set
    hide dot files = yes

    # hide pipes, sockets, devices ...
    hide special files = yes

    # hide selected files
    # '*' and '?' can be used to specify multiple files or directories
    # Each entry must begin, end, or be separated from another with a slash (/) character
    hide files = /.snapshot/

If you want to prevent users from seeing files completely (完全 access 唔到)

[data]
    # list must be separated by a '/'
    veto files = /.snapshot/

 


follow symlinks 與  wide links

 

follow symlinks

If the option is set to yes, the target of the link will be interpreted as the file

wide links option

if set to no, prevents the client user from following symbolic links that point outside the current shared directory tree

 


檔案的屬性(Archive  System  Archive)

 

Default:

map archive = yes
map system = no
map hidden = no

 


[force]create / directory mask

 

create / directory mask:

  • create mask                 建立 File 時會的 permission
  • directory mask             建立 Folder 時會的 permission

 

force create mode:

´OR´ 此 mask (bits that are specified will always be set)

  • force create mode           # Default: 000
  • force directory mode       # Default: 000

e.g.

[Public]
        path = /home/samba_root/Public_Folder
        comment = "Public Folder"
        browseable = yes
        writable = yes
        valid users = @smb_public,@smb_admin
        admin users = @smb_admin
        force group = smb_public
        create mask = 660
        directory mask = 770

 

inherit:

Default: inherit permissions = no

When the inherit permissions option is set to yes, the create mask, directory mask, force create mode, and force directory mode are ignored. (setuid bit is never set via inheritance)

Default: inherit acls = no

Note that using the VFS modules acl_xattr or acl_tdb which store native Windows as meta-data will automatically turn this option on for any share for which they are loaded

 

Security Mask (Samba 4 取消了這設定)

  • security mask (AND)
  • force security mode (OR)
    ----
  • directory security mask (AND)
  • force directory security mode (OR)

每次設定 permission 後, 最後最後都要與 security mask AND 一次

不能同時設定 "OR" 及 "AND"

Default:

  • directory security mask = 0777
  • security mask = 0777
  • force security mode = 0
  • force directory security mode = 0

P.S.

此功能用來克服 inheritance installed 的限制

nt acl support (Default: yes)

Controls whether smbd(8) will attempt to map UNIX permissions into Windows NT access control lists.

 


Opportunistic Locking (oplocks)

 

Default:

# byte-range locks
locking = yes

# local caching of files
oplocks = yes

If a second client requests access to that file before the first client has finished working on it,

Samba sends an oplock break request to the first client.

This tells the client to stop caching its changes and return the current state of the file to the server so that the interrupting client can use it as it sees fit.

A more concrete example of oplock failure occurs when database files are very large.

If a client is allowed to oplock this kind of file, there can be a huge delay while the client copies the entire file from the server to cache it,

even though it might need to update only one record.

The situation goes from bad to worse when another client tries to open the oplocked file.

The first client might need to write the entire file back to the server before the second client's file open request can succeed.

This results in another huge delay (for both clients), which in practice often results in a failed open due to a timeout on the second client,

perhaps along with a message warning of possible database corruption!

If you are having problems of this variety, you can turn off oplocks for the affected files by using the veto oplock files parameter:

[dbdata]
    veto oplock files = /*.dbm/

strict locking(Default: no)

If yes, denies access to an entire file if a byte-range lock exists in it.

A Level 2 (or shared) oplock

indicates that there are multiple readers of a stream and no writers.
This supports client read caching.

A Level 1 (or exclusive) oplock

allows a client to open a stream for exclusive access and
allows the client to perform arbitrary buffering.
This supports client read caching and write caching.

OS:

  • Windows NT 3.1       # Level 1, Level 2, and Batch oplocks
  • Windows 2000         # The Filter oplock
  • Windows 7              # R, RH, RW, and RWH oplocks have been added in

 


DFS(Distributed File System)

 

Client OS >= Windows 2000

當 DFS Client 訪問 DFS 目錄內的目錄時, DFS Server 將那目錄的 Server 的 UNC 給 Client.

* Universal Naming Convention(\\?????)

Load Balancing

Dfs also can help improve performance for read-only shares because it provides load balancing.

It is possible to set up a Dfs reference to point to identical shares on two or more servers.

The Dfs server then divides requests between the servers, dividing the client load among them.

"msdfs:"

it sees the leading msdfs: and interprets the rest as the name of a remote share. The client is then redirected to the remote share.

 * dfs 可以用來做 mount point

應用 Case

/data                      <-- disk 0

/data/mountpoint1  <-- disk 1

/data/mountpoint2  <-- disk 2

[data]
path = /data
...

[Disk1]
path = /Disk1
...

[Disk2]
path = /Disk2
...

當寫 data 入 mountpoint1 時, 當 /data 沒有空位,

即使 mountpoint1 仍有位, 那仍是會出 Over Quota 情況

Config Example:

[FolderA]
        comment = "Folder A"
        path = /home/smb_root/folderA
        public = no
        writable = yes
        valid users = @groupA
        force group = groupA
        create mask = 660
        directory mask = 770

[FolderB]
        comment = "Folder B"
        path = /home/smb_root/folderB
        public = no
        writable = yes
        valid users = @groupB
        force group = groupB
        create mask = 660
        directory mask = 770

[DFS]
        comment = DFS
        path = /home/smb_root/dfs
        public = yes
        msdfs root = yes
        writable = no

建立在 DFS 內的 Link

mkdir /home/smb_root/dfs

ln -s msdfs:192.168.123.103\\FolderA FolderA  
ln -s msdfs:192.168.123.103\\FolderB FolderB

Load balancing

!! make sure the shares is read-only to users

To set up a load-balancing Dfs share, create the symbolic link like this:

ln -s 'msdfs:serverA\\shareA,serverB\\shareB' lb-data

To enable support for Dfs in the server, we need to add one line to the [global] section:

[global]
    # default: yes
    host msdfs = yes

[dfs]
    path = /usr/local/samba/dfs
    msdfs root = yes

 


Security Mode

 

到最後, 不能不談 samba 的 security mode 了,

它掌管著 samba 的登入方式.

它一共分為 4 種, 分別是 share, user, server, domain

而 default 是 user 的.

<security = user>

在這模式下, linux 帳戶及 samba 帳戶必須存在,

client 須要提供用戶名及密碼登入

而且只可以用一個帳戶去登入

valid users 與 invalid users

當某一"服務"沒有 "valid users" 時, 那服務適同於任何同戶

當它有設定 "valid users" 時, 只有此 list 上的帳戶才可用此 "服務"

如果一個帳戶同時存在於 "valid users" 及 "invalid users" 時, 

則此帳戶不能用此 "服務"

<security = share >

guest ok 與 guest only

guest ok 是指所有人都可以用此服務, 而且不須要密碼. 至於用戶的權限由 "guest account" 來指定

Default:

    guest account = nobody

"guest only = yes" 是一很特別的功能來, 它會把現在的服務變成 share-level security
(如同 "security = share")

只有 guest ok = yes 時, guest only 才生效

only user 與 users

only user = yes 使服務變成 share-level security

users 則是自動配對的 user name

 


ACL

 

It is a file system features

Where an extra set of file attributes stored in addition to the normal Linux file owner/group/other permissions.

Enable

mount -o remount,acl /path/to/share

Set

setfacl -R -d -m u::rwx,g:smbgrp:rwx,o::r-x /path/to/share

Get

getfacl /path/to/share

詳見: fs_acl

 


VFS

 

可用的 vfs 放在

/usr/lib/samba/vfs/

e.g.

  • fake_perms.so 
  • readonly.so      
  • syncops.so
  • cap.so           
  • fileid.so     
  • recycle.so       
  • xattr_tdb.so
  • default_quota.so
  • shadow_copy2.so
  • expand_msdfs.so
  • netatalk.so

audit:

  • audit.so
  • extd_audit.so
  • full_audit.so

other:

  • readahead.so  
  • streams_xattr.so

 


Recycle Bin

 

# 原理

It intercepts file deletion requests and moves the affected files to a temporary repository.

# U14 / U16 Install

apt-get install samba-vfs-modules

# Setting

[global]
..................................
# 載入 recycle.so
vfs objects = .... recycle ....
include  = /etc/samba/recycle.conf
..................................

OR

[public]
        vfs objects = recycle
        recycle:keeptree = yes
        recycle:versions = yes
        recycle:repository = /home/samba/recycle

recycle.conf 的內容:

# 被刪除了的檔案將會放在那裡

recycle:repository = /home/recycle_bin

# 保持目錄結構

recycle:keeptree = yes

# 被刪除過的檔案會以 "Copy #x of filename" 形式另外保存

recycle:versions = yes

# 沒有 version 的檔案

recycle:noversions = *.mp3

# repository 目錄的權限
# 檔案寫入後, 檔案權限 Default 是 700

recycle:directory_mode = 700
recycle:subdir_mode = 700

# 是否更新 mtime 到刪除的時間

recycle:touch_mtime = no

# 檔案小於或大於此時不放入 recycle_bin 單位是 BYTES

recycle:minsize =  0
recycle:maxsize = 0

# 那些檔案不放入回收筒, 支援 "*, ?"
# 另有設定 recycle:exclude_dir = LIST

recycle:exclude = *.~, *.bak, *.tmp, *.TMP

tmp file list:

  • *.WBK
  • *.wbk
  • *.ASD
  • *.asd
  • *.TMP
[Recycle_Bin]
    comment ="資源回收箱"
    path = /home/recycle_bin                        # 這個 Folder 要以被 Delete File 的 User 讀入 !!
    browseable = yes
    writeable = yes
    public = yes
    directory mask = 775
    create mask = 775
    recycle:versions = no
    recycle:exclude= *

P.S.

在檔案在移入 recycle:repository 目錄的過程中, 若無法寫入那目錄,
Samba 會寫入一筆錯誤資訊至 Log 檔中, 並把檔案刪除!!

所以, recycle_bin 的權限用 777 較為安全 !!
(注意不同目錄的相同結構)

 

# 定時清除 7 天前的垃圾

0 10 * * * root    find /home/recycle_bin -type f -mtime +7 -delete > /dev/null

# 學習

man vfs_recycle


audit

 

audit 的 modules 一共有 3 個:

audit.so

# syslog facility

Example:

[audit]
    comment = Audited /data directory
    path = /data
    vfs objects = audit
    writeable = yes
    browseable = yes

extd_audit.so

# sends audit logs to both syslog as well as the smbd log files.

Log Level

0    Make Directory, Remove Directory, Unlink
1    Open Directory, Rename File, Change Permissions/ACLs
2    Open & Close File
10    Maximum Debug Level

full_audit.so

client operations to the system log using syslog

常見的 operations:

  • mkdir, rmdir
  • rename                           <-- move file 都是這個 log
  • link, unlink
  • write, read (pread, pwrite)
  • chown, chmod

Global section

# Audit settings
full_audit:prefix = %u|%I|%S
full_audit:failure = connect
full_audit:success = mkdir rmdir read pread write pwrite sendfile rename unlink link 
full_audit:facility = local5
full_audit:priority = notice

* full_audit:success: on busy server it will generate a lots of junk.
* full_audit:prefix = %u|%I|%S - adds additional useful information to audit log file

%u - User
%I - User IP address
%S - Server share name

Example1:

[public]
  comment = Public Stuff
  path = /home/samba/public
  public = yes
  writable = no
  write list = @staff
  vfs object = full_audit

Example2:

[records]
    path = /data/records
    vfs objects = full_audit
    full_audit:prefix = %u|%I
    full_audit:success = open opendir
    full_audit:failure = all !open
    full_audit:facility = LOCAL7
    full_audit:priority = ALERT

 

Log rotation Setting:

rsyslogd

touch /etc/rsyslog.d/00-samba-audit.conf

local5.notice /var/log/samba/audit.log
& ~

/etc/logrotate.d/samba.audit

/var/log/samba/audit.log {
   weekly
   missingok
   rotate 7
   postrotate
      /etc/init.d/syslog-ng reload > /dev/null 2>&1 || true
   endscript
   compress
   notifempty
}

DOC:

http://www.samba.org/samba/docs/man/manpages-3/vfs_full_audit.8.html

 

P.S.

不受 syslog = 0 影響 !!

 


vfs_snapper

 

[share]
        vfs objects = snapper

users must be granted permission to list snapshots managed by snapper,

via snapper's ALLOW_USERS or ALLOW_GROUPS options.

Snapper can grant these users and groups .snapshots traversal access automatically via the SYNC_ACL option.

 


vfs_readahead

 

preload the kernel buffer cache

module detects read requests at multiples of a given offset

Windows Vista: asynchronously does multiple file read requests at offset boundaries of 0x80000 bytes

vfs objects = readahead
readahead:offset = 0x80000         # Unit: byte. Default: 0x80000
readahead:length = 0x80000       # Unit: byte. Default same as "readahead:offset"

 


vfs_btrfs

 

Btrfs allows for multiple files to share the same on-disk data through the use cloned ranges.

When an SMB client issues a request to copy duplicate data (via FSCTL_SRV_COPYCHUNK),

this module maps the request to a Btrfs clone range IOCTL,

instead of performing reads and writes required by a traditional copy.

Doing so saves storage capacity and greatly reduces disk IO.

This module also exposes Btrfs per-file compression support to SMB clients via the get/set compression fsctls.

 


vfs_dirsort

 

The vfs_dirsort module sorts directory entries alphabetically before sending them to the client.

 


hostname lookups

 

Default: hostname lookups = no

hostname lookups = expensive

 


log

 

[global] 
    ...............

    # Default: syslog = 1
    syslog = 0
    syslog only = no

    # 當 syslog only = no 時才有個別的 log file
    log file = /var/logs/samba.log.%I
    # Default: log level = 0   <- 沒有 log
    log level = 2

    # 是否有 log 時間
    debug timestamp = yes

    # 單位 kilobytes
    max log size = 512

# Level 2 will provide us with useful debugging information without wasting disk space on our server.
# 無事無幹, 1 已經很足夠

samba log user login

Example: log level = 2 passdb:5 auth:10 winbind:2

# auth:1

# 去到不能 login 的 Folder
[2013/08/20 12:33:57.018144,  1] smbd/process.c:457(receive_smb_talloc)
  receive_smb_raw_talloc failed for client 192.168.88.177 read error = NT_STATUS_CONNECTION_RESET.

# 入可以 login 的 Folder
[2013/08/20 12:34:40.167025,  1] smbd/service.c:1114(make_connection_snum)
  lwy-pc (192.168.88.177) connect to service tim initially as user tim (uid=1001, gid=1001) (pid 26681)

# auth:2

[2013/08/20 12:27:05.834179,  2] auth/auth.c:319(check_ntlm_password)
  check_ntlm_password:  Authentication for user [lwy] -> [lwy] FAILED with error NT_STATUS_NO_SUCH_USER

[2013/08/20 12:35:53.044999,  2] auth/auth.c:319(check_ntlm_password)
  check_ntlm_password:  Authentication for user [tim] -> [tim] FAILED with error NT_STATUS_WRONG_PASSWORD

[2013/08/20 12:27:14.656688,  2] auth/auth.c:309(check_ntlm_password)
  check_ntlm_password:  authentication for user [tim] -> [tim] -> [tim] succeeded

NT_STATUS_WRONG_PASSWORD

出現此情況, 如果肯定 password 正確, 那可以嘗試加入設定

# Client: Server 2003
ntlm auth = yes

log level = 1

[2013/08/20 12:30:47.835786,  1] smbd/service.c:1114(make_connection_snum)
  lwy-pc (192.168.88.177) connect to service tim initially as user tim (uid=1001, gid=1001) (pid 26196)

測試時要注意, net use * /delete 要一段時間後才有

lwy-pc (192.168.88.177) closed connection to service tim

那些 log 不會知某人 Access, Create, Delete 檔案

 


Template

[template]
    writable = yes
    browsable = yes
    valid users = andy, dave, jay

[data]
    path = /usr/local/samba
    copy = template

 


Client 篇

 

在 Linux 上連 Samba 比 Window 上難, 因為一切都要在 CLI 內連行 ~

找出 "電腦名稱" 與 IP 的對應

nmblookup home-desktop

querying home-desktop on 192.168.123.255
192.168.123.21 home-desktop<00>

SMB URL:

smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]]

工具: smbclient

安裝:

# C6

yum install samba-client

# Debain

apt-get install smbclient

會獲得:

  • smbtree    # linux 版的 "Network Neighborhood"
  • smbclient  # sambe 的 shell
  • smbget     # 類似 wget 工具
  • smbcacls   # Set or get ACLs
  • rpcclient

smbtree:

WORKGROUP
        \\FILESERVER                    myserver server
                \\FILESERVER\ml1640             laser printer
                \\FILESERVER\ml1640-raw         ml1640-raw
                \\FILESERVER\home-user          share laser-printer
                \\FILESERVER\IPC$               IPC Service (myserver server)
                \\FILESERVER\print$             Printer Drivers
                \\FILESERVER\FTP                Home Directories
        ................................

smbclient(shell):

查看資源:

# 以用戶 User 的身份列出 (-U|--user=USERNAME, -L|--list)

smbclient -U <User> -L Server [passwd]

i.e.

Sharename       Type      Comment
---------       ----      -------
download        Disk
homes           Disk      user home
...

Useful Opts

-A|--authentication-file=FILE

FILE:

username = <value>
password = <value>
domain   = <value>

i.e.

smbclient -L 192.168.123.41 -A /root/login/nas/tim.pw

-U username[%password]

If %password is not specified, the user will be prompted

environment variable: USER then LOGNAME then GUEST

-c <command>

ie.

smbclient //192.168.123.41/music -A /root/login/nas/tim.pw -c ls

進入 shell:

smbclient -U User //Server/folder [passwd]

shell cmd

smb: \> help

smb: \> help scopy

smb: \> ls

  .                                  DA        0  Tue Nov  5 15:28:00 2019
  ..                                 DA        0  Tue Mar  9 00:05:07 2021

                1026163016 blocks of size 1024. 687628312 blocks available

smb: \> du

                1026163016 blocks of size 1024. 687628312 blocks available
Total number of bytes: 0

smb: \> showconnect

//192.168.123.41/music

smb: \> pwd

Current directory is \\192.168.123.41\music\

smb: \> volume

Volume: |music| serial number 0xc6a0fee3

get / put / mget / mput / rename

lcd _ACG

!ls

put 1.mp3

... (47921.2 kb/s) (average 47921.2 kb/s)

Folder

du:        <mask> computes the total size of the current directory

mkdir

Upload a Folder

# recurse:        toggle directory recursion for mget and mput

                       沒有加時, 會 "Put file mp3?"; 加了後 "Put directory mp3?"

                       P.S. ls, rm 都會受影響 !

# prompt:        toggle prompting for filenames for mget and mput

# 沒有加時
Put file mp3/1.mp3? y
...
Put file mp3/3.mp3? y
...

scopy

<src> <dest> server-side copy file

tar

tar <c|x>[IXFqbgNan] current directory to/from <file name>

rm / rmdir

getfacl

smb: \> getfacl 20140415
# file: \20140415
# owner: 508
# group: 535
user::r--
group::r--
other::r--

stat

smb: \> stat 20140415
File: \20140415
Size: 0                 Blocks: 0       directory
Inode: 205193227        Links: 2
Access: (0444/dr--r--r--)       Uid: 508        Gid: 535
Access: 2014-04-15 11:55:03 +0800
Modify: 2014-04-15 11:54:36 +0800
Change: 2014-04-15 12:05:49 +0800

setmode

setmode filename perm=[+|-]rsha    # MS-DOS "attrib"

smbget:

  • -R, --recursive
  • -r, --resume
  • -u, --username
  • -p, --password
  • -D, --dots (進程)
  • -P, --keep-permissions

經測試, 要在 smb url 加入 user_name 及 password 才成功 download

Example:

smbget  -R smb://user:[email protected]/ftp/mp3

 


mount samba folder

 

Setup:

apt-get install cifs-utils

yum install cifs-utils               # Centos 7

modinfo cifs

filename:       /lib/modules/4.9.0-4-amd64/kernel/fs/cifs/cifs.ko
softdep:        pre: crypto-arc4 crypto-des crypto-ecb crypto-hmac crypto-md4 crypto-md5 crypto-aes crypto-cmac crypto-sha256
version:        2.09
description:    VFS to access servers complying with the SNIA CIFS Specification e.g. Samba and Windows
...
parm:           CIFSMaxBufSize:Network buffer size (not including header). Default: 16384 Range: 8192 to 130048 (uint)
parm:           cifs_min_rcv:Network buffers in pool. Default: 4 Range: 1 to 64 (uint)
parm:           cifs_min_small:Small network buffers in pool. Default: 30 Range: 2 to 256 (uint)
parm:           cifs_max_pending:Simultaneous requests to server. Default: 32767 Range: 2 to 32767. (uint)
parm:           enable_oplocks:Enable or disable oplocks. Default: y/Y/1 (bool)

mount.cifs -V

mount.cifs version: 5.5

/etc/fstab:

//<hostIP>/<sharename> <mountpoint-path> cifs 
    username=<u>,password=<pw>,rw,iocharset=utf8,file_mode=0777,dir_mode=0777,nounix 0 0

mount command:

mount -t cifs -o username=<u>,password=<pw> //<servername>/<sharename> /mnt/point/

另一個 login 方式:

-o credentials=/full/path/to/login.txt

login.txt:

username=value
password=value
domain=value

Login by environment variable - "PASSWD, USER"

ie.

PASSWD=$_P USER=$_U mount -t cifs $_F $_T

other option:

  • uid=512,gid=523
  • file_mode=0775, dir_mode=0775
  • cache=none|strict|loose
  • rsize=bytes,wsize=bytes
  • _netdev
  • nounix       // turn off multiple settings at once.
                     ( POSIX acls, POSIX locks, POSIX paths, symlink support and retrieving uids/gids/mode)
  • ro

 


Samba Variable

 

%I        Client's IP address
%m        Client's NetBIOS name
%M        Client's DNS name

%u        Current Unix username
%H        Home directory of %u

%S - Server share name

 


SLOW opening Word and Excel files

 

Samba server 3.6.3 very SLOW opening Word and Excel files

open the same files without delays:

reg add HKCU\Software\Microsoft\Office\11.0\Excel\Security \FileValidation /v EnableOnLoad /t REG_DWORD /d 0 /f
reg add HKCU\Software\Microsoft\Office\11.0\Word\Security\ FileValidation /v EnableOnLoad /t REG_DWORD /d 0 /f
reg add HKCU\Software\Microsoft\Office\11.0\Access\Securit y\FileValidation /v EnableOnLoad /t REG_DWORD /d 0 /f
reg add HKCU\Software\Microsoft\Office\11.0\Publisher\Secu rity\FileValidation /v EnableOnLoad /t REG_DWORD /d 0 /f

Changing SMB Settings on a per Machine Bassis

On Client side, check the following registry values are 0:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Lanmanworkstation\Parameters\Enablesecuritysignature
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Lanmanworkstation\Parameters\Requiresecuritysignature

On Server side, check the following registry values are 0:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Lanmanserver\Parameters\Enablesecuritysignature
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Lanmanserver\Parameters\Requiresecuritysignature  

Disable SMB 2.0.

Client

To disable SMB 2.0 for Windows Vista, Windows 7 or Windows systems that are the “client” systems run the following two commands:

sc config lanmanworkstation depend= bowser/mrxsmb10/nsi

sc config mrxsmb20 start= disabled

Server

Run "regedit" on Windows Server 2008 based computer.

Expand and locate the sub tree as follows.

HKLM\System\CurrentControlSet\Services\LanmanServer\Parameters

Add a new REG_DWORD key with the name of "Smb2" (without quotation mark)

Value name: Smb2

Value type: REG_DWORD

0 = disabled

Reboot the server.

 


Performance Turning

 

# use the more efficient sendfile system call for files that are exclusively oplocked.
# Default: false

use sendfile = Yes

# automatically closes connections after 15 minutes of inactivity.
# The deadtime only takes effect if the number of open files is zero.
# Default: 0

deadtime  = 15

# Samba will read from file asynchronously when size of request is bigger than this value
# Default: 0

aio read size = 16384
aio write size = 16384

# Default: socket options = TCP_NODELAY

[global]
socket options = TCP_NODELAY IPTOS_LOWDELAY SO_RCVBUF=65536 SO_SNDBUF=65536
deadtime = 15
  • TCP_NODELAY
        send as many packets as necessary to keep delay low
  • Buffers
        Default: 8192
  • SO_KEEPALIVE
        initiates a periodic check every four(4) hours to see if the client is still there (arranges to close dead connections)
  • IPTOS_X
        To set the DSCP field use the the IPTOS_X socket option in legacy IPv4
  • deadtime
        use with "SO_KEEPALIVE", Unit: minutes, Default 0

其他:

# THIS IS ONLY A GOOD OPTION FOR FILE SYSTEMS THAT SUPPORT UNWRITTEN EXTENTS
# LIKE XFS, EXT4, BTRFS, OCS2.
# help to reduce file fragmentation
# Default: strict allocate = no

strict allocate = Yes

# downgrade from a read-write oplock to a read-only oplock
# It is recommended that this parameter be turned on to speed access to shared executables.

Once one of the clients which have a read-only oplock writes to the file
all clients are notified (no reply is needed or waited for) and
told to break their oplocks to "none" and delete any read-ahead caches.

level2 oplocks = yes

 


smb protocol version

 

/etc/samba/smb.conf

# Used by Windows Vista
client min protocol = SMB2

# Used by Windows 8; S2012;  Samba 4.x
client max protocol = SMB3

Version

SMB 2.0

  • Samba 3.6
  • 很大改善的一個 Version !!

SMB 2.1

  • Introduced with Windows 7 and Server 2008 R2

SMB 3.0

  • the SMB Direct Protocol (SMB over remote direct memory access [RDMA])
  • SMB Multichannel (multiple connections per SMB session)
  • SMB Transparent Failove

SMB 3.0.2

  • Introduced with Windows 8.1 and Windows Server 2012 R2

SMB 3.1.1

  • Introduced with Windows 10 and Windows Server 2016
  • Supports AES-128 GCM encryption
  • Implements pre-authentication integrity check using SHA-512 hash

 


Check Client Usage

 

smbstatus

# 當有人([email protected])停留在 "pc_data" 內的 "music" 這 Folder 時

Samba version 4.8.0rc4-Ubuntu
PID     Username     Group        Machine                                    Protocol Version  Encryption           Signing
----------------------------------------------------------------------------------------------------------------------------------------
6495    tim          tim          192.168.123.21 (ipv4:192.168.123.21:52584) SMB2_10           -                    -

Service      pid     Machine       Connected at                     Encryption   Signing
---------------------------------------------------------------------------------------------
pc_data      6495    192.168.123.21 Thu Sep 12 10:51:12 HKT 2019 HKT -            -

Locked files:
Pid          Uid        DenyMode   Access      R/W        Oplock    SharePath      Name   Time
--------------------------------------------------------------------------------------------------
6495         0          DENY_NONE  0x100080    RDONLY     NONE      /data/pc_data  .      Thu Sep 12 23:16:10 2019
6495         0          DENY_NONE  0x100081    RDONLY     NONE      /data/pc_data  .      Thu Sep 12 23:16:12 2019
6495         0          DENY_NONE  0x100081    RDONLY     NONE      /data/pc_data  music  Thu Sep 12 23:16:12 2019

 


net command

 

net rpc shell           Open interactive shell on remote server

net rpc registry        Manage registry hives

net rpc service         list/start/stop/status remote services

net rpc info            Show basic info about a domain

net rpc shutdown        Shutdown a remote server

...

 


smbcontrol

 

send messages to smbd, nmbd or winbindd processes

ping

smbcontrol smbd ping

PONG from pid 3638

close-share

    Order smbd to close the client connections to the named share.
    "*" character which will close all currently open shares.
    This may be useful if you made changes to the access controls on the share.

close-denied-share

    Behave like close-share, but don't disconnect users that are still allowed to access the share.
    It can safely be sent to all smbds after changing share access controls.

kill-client-ip

Order smbd to close the client connections from a given IP address.

Debug

# Display current debuglevels

smbcontrol smbd debuglevel

PID 3638: all:0 tdb:0 ...

# Set debug level to the value specified by the parameter.

smbcontrol smbd debug 0

Reloading smb.conf without restarting the service (pid 沒有變到)

smbcontrol smbd reload-config

相當於

killall -HUP smbd nmbd

 


Instant SMB/AFP server-side copy

 

Instant SMB/AFP server-side copy

When you duplicate file, instead of actually copying bytes the filesystem creates reference to exiting data blocks. This is instant.

Samba 4.1.0 was the first release to ship with support for server-side copy operations via the SMB2 FSCTL_SRV_COPYCHUNK request.

OS Support

  • Server 2012 and later: via Windows Explorer or Robocopy
  • Server 2008: via Robocopy only
  • Win 8 and later: via Windows Explorer or Robocopy
  • Win 7: via Robocopy only
  • Linux kernel version 4.2 with SMB3+ mounts (via cp --reflink)

Btrfs Enhanced Server-Side Copy Offload

Samba 4.7.0 's VFS Module - FSCTL_DUPLICATE_EXTENTS_TO_FILE

smb.conf

[share]
   path = /mnt/btrfs_fs/        # must reside within a Btrfs filesystem
   vfs objects = btrfs

 


Ksmbd

 

kernel module which implements the server-side of the SMB3 protocol.

The target is to provide optimized performance

 


 

domain logons = Yes

Setting the domain logons parameter will make this samba server a domain controller.
The domain logons option enables Samba to perform domain authentication on behalf of other clients that request it.

 


Troubleshoot

 

Q1

The log file oversize

Dec 31 12:41:33 file smbd[13076]: [2014/12/31 12:41:33, 0] smbd/notify_inotify.c:inotify_handler(249)
Dec 31 12:41:33 file smbd[29642]: [2014/12/31 12:41:33, 0] smbd/notify_inotify.c:inotify_handler(249)
Dec 31 12:41:33 file smbd[13076]:   No data on inotify fd?!
Dec 31 12:41:33 file smbd[29642]:   No data on inotify fd?!

Answer

# Default: kernel change notify = yes

"kernel change notify = No"

This parameter specifies whether Samba should ask the kernel for change notifications in directories so that SMB clients can refresh whenever the data on the server changes. This parameter is only used when your kernel supports change notification to user programs using the inotify interface.

Q2

testparm 後見到

rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)

原因:

On MS Windows the number of file handlers on the client and the server must be identical,
else you will see the "too many files open"

# Global limits

cat /proc/sys/fs/file-max

sysctl -w fs.file-max=n

# User limits

switch to the concerned user, e. g. samba, and run

ulimit -Hn               # 4096

ulimit -Sn                # 1024

/etc/security/limits.conf

# user        soft/hard/-        resouce        limit
root              -              nofile         16384

Q3

killall -9 smbd

log

[2017/01/21 16:18:18.828700,  0] ../lib/util/become_daemon.c:124(daemon_ready)
  STATUS=daemon 'smbd' finished starting up and ready to serve connections

smbd -F

-F

If specified, this parameter causes the main smbd process to not daemonize,
i.e. double-fork and disassociate with the terminal.
Child processes are still created as normal to service each connection request
but the main process does not exit.

# Ubuntu 14

stop smbd

# Ubuntu 16

systemctl stop smbd.service

 


 

 

Creative Commons license icon Creative Commons license icon