This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users. This is a practical guide with concise explanations, however the reader is supposed to know what s/he is doing. 本文档汇集了Unix/Linux/BSD等系统的命令和任务,这对it工作者或高级用户们来说应该是非常有用的。 本文档也是一份实践指南,并且还附有简略的说明。但是,读者必须明白他自己在做什么事情,有什么后果。
Unix Toolbox revision 11
The latest version of this document can be found at Replace .xhtml on the link with .pdf for the PDF version and with .book.pdf for the booklet version. On a duplex printer the booklet will create a small book ready to bind. This XHTML page can be converted into a nice PDF document with a CSS3 compliant application (see the script example).
Error reports and comments are most welcome - c@cb.vu Colin Barschel.
# sysctl hw.model # CPU model # sysctl hw # Gives a lot of hardware information # sysctl vm # Memory usage # dmesg | grep "real mem" # Hardware memory # sysctl -a | grep mem # Kernel memory settings and info # sysctl dev # Configured devices # pciconf -l -cv # Show PCI devices # usbdevs -v # Show USB devices # atacontrol list # Show ATA devices
Load, statistics and messages
以下的命令有助于用来找出正在系统中运行着的程序。
# top # 显示和更新使用cpu最多的进程 # mpstat 1 # 显示cpu工作状态(app-admin/sysstat) # vmstat 2 # 显示虚拟内存的状态 # iostat 2 # 间隔2秒显示系统I/O状态(app-admin/sysstat) # systat -vmstat 1 # BSD summary of system statistics (1 s intervals) # systat -tcp 1 # BSD tcp connections (try also -ip) # systat -netstat 1 # BSD active network connections # systat -ifstat 1 # BSD network traffic through active interfaces # systat -iostat 1 # BSD CPU and and disk throughput # tail -n 500 /var/log/messages # 显示最后500行内核的系统日志信息 # tail /var/log/warn # syslog.conf中定义的系统警告信息的日志
Users 用户
# id # 显示活动用户的id号,以及登录和所属组的信息 # last # 显示最后登录系统的记录 # who # 显示已登录系统的用户 # groupadd admin # 添加一个admin名字的组 (Linux/Solaris) # useradd -c "Colin Barschel" -g admin -m colin # userdel colin # 删除用户colin (Linux/Solaris) # adduser joe # FreeBSD add user joe (interactive) # rmuser joe # FreeBSD delete user joe (interactive) # pw groupadd admin # Use pw on FreeBSD # pw groupmod admin -m newmember # Add a new member to a group # pw useradd colin -c "Colin Barschel" -g admin -m -s /bin/tcsh # pw userdel colin; pw groupdel admin
Encrypted passwords are stored in /etc/shadow for Linux and Solaris and /etc/master.passwd on FreeBSD. If the master.passwd is modified manually (say to delete a password), run # pwd_mkdb -p master.passwd to rebuild the database. 已经被加密的密码对linux系统和Solaris系统而言,它是存放在/etc/shadow文件里的。而对FreeBSD系统而言,它是存放在/etc/master.passwd文件里的。如果master.passwd被改写了(比如说删除了一个密码),那么就必须运行#pwd_mkdb -p master.passwd 来重建数据库。
To temporarily prevent logins system wide (for all users but root) use nologin. The message in nologin will be displayed.
# echo "Sorry no login now" > /etc/nologin # (Linux) # echo "Sorry no login now" > /var/run/nologin # (FreeBSD)
Limits 设限
Some application require higher limits on open files and sockets (like a proxy web server, database). The default limits are usually too low. 一些应用程序需要设置打开文件和接口的最高限制数。默认的限制数一般都太小。
Linux
Per shell/script
The shell limits are governed by ulimit. The status is checked with ulimit -a. For example to change the open files limit from 1024 to 10240 do: 对shell的设限由ulimit来做。可以用ulimit -a查看状态。比如将可打开的文件数限制从1024改到10240,就可以这么做:
# ulimit -n 10240 # This is only valid within the shell
The ulimit command can be used in a script to change the limits for the script only. ulimit命令可以用在脚本里,其作用域就只限定在这个脚本里。
Per user/process
Login users and applications can be configured in /etc/security/limits.conf. For example: 对登录用户和应用程序的限制可以在/etc/security/limits.conf文件里修改,比如:
# cat /etc/security/limits.conf * hard nproc 250 # 限制每个用户的进程数 asterisk hard nofile 409600 # 限制每个程序同时打开的文件数
System wide
Kernel limits are set with sysctl. Permanent limits are set in /etc/sysctl.conf. 内核限制用sycctl命令定义,定义的文件为/etc/sysctl.conf
# sysctl -a # 显示全部限制 # sysctl fs.file-max # 显示可打开的最多文件数字 # sysctl fs.file-max=102400 # 改变可打开的最多文件数字 # cat /etc/sysctl.conf fs.file-max=102400 # 要永久改变参数,则需要在sysctl.conf文件中修改 # cat /proc/sys/fs/file-nr # How many file descriptors are in use
FreeBSD
Per shell/script
Use the command limits in csh or tcsh or as in Linux, use ulimit in an sh or bash shell. Per user/process
The default limits on login are set in /etc/login.conf. An unlimited value is still limited by the system maximal value. System wide
Kernel limits are also set with sysctl. Permanent limits are set in /etc/sysctl.conf or /boot/loader.conf. The syntax is the same as Linux but the keys are different.
# sysctl -a # View all system limits # sysctl kern.maxfiles=XXXX # maximum number of file descriptors kern.ipc.nmbclusters=32768 # Permanent entry in /etc/sysctl.conf kern.maxfiles=65536 # Typical values for Squid kern.maxfilesperproc=32768 kern.ipc.somaxconn=8192 # TCP queue. Better for apache/sendmail # sysctl kern.openfiles # How many file descriptors are in use # sysctl kern.ipc.numopensockets # How many open sockets are in use
See The FreeBSD handbook Chapter 11 for details.
Solaris
The following values in /etc/system will increase the maximum file descriptors per proc:
set rlim_fd_max = 4096 # Hard limit on file descriptors for a single proc set rlim_fd_cur = 1024 # Soft limit on file descriptors for a single proc
Runlevels 运行级别
Linux
Once booted, the kernel starts init which then starts rc which starts all scripts belonging to a runlevel. The scripts are stored in /etc/init.d and are linked into /etc/rc.d/rcN.d with N the runlevel number. 一旦启动,内核开始初始化,由init到rc,再到同属某个运行级别的所有脚本。这些脚本都存放在/etc/init.d目录下,其中有些是/etc/rc.d/rcN.d目录下文件的一个链接,其中N就是运行级别数。(注,并不是所有的系统都是这么设计的,但脚本文件都必须在/etc/init.d目录下)
The default runlevel is configured in /etc/inittab. It is usually 3 or 5: 默认的运行级别在/etc/inittab文件里配置,一般设为3或5:
# grep default: /etc/inittab id:3:initdefault:
The actual runlevel (the list is shown below) can be changed with init. For example to go from 3 to 5: 当前的运行级别可以用init命令改变,比如把当前的运行级别由3改成5:
# init 5 # Enters runlevel 5
* 0 Shutdown and halt 关闭系统
* 1 Single-User mode (also S) 单用户模式
* 2 Multi-user without network 多用户模式,但不联网
* 3 Multi-user with network 多用户模式,并联网
* 5 Multi-user with X 多用户模式,并启用X图形系统
* 6 Reboot 重启
Use chkconfig to configure the programs that will be started at boot in a runlevel. 在redhat/fedora系列的linux中,可以用chkconfig命令来配置服务程序在不同运行级别中的预设动作。
# chkconfig --list # List all init scripts # chkconfig --list sshd # Report the status of sshd # chkconfig sshd --level 35 on # Configure sshd for levels 3 and 5 # chkconfig sshd off # Disable sshd for all runlevels
Debian and Debian based distributions like Ubuntu or Knoppix use the command update-rc.d to manage the runlevels scripts. Default is to start in 2,3,4 and 5 and shutdown in 0,1 and 6. debian系列用update-rc.d命令来管理各个运行级别的脚本。默认在运行级别2、3、4和5中开启,在运行级别0、1和6中关闭。
# update-rc.d sshd defaults # Activate sshd with the default runlevels # update-rc.d sshd start 20 2 3 4 5 . stop 20 0 1 6 . # With explicit arguments # update-rc.d -f sshd remove # Disable sshd for all runlevels # shutdown -h now (or # poweroff) # Shutdown and halt the system
FreeBSD
The BSD boot approach is different from the SysV, there are no runlevels. The final boot state (single user, with or without X) is configured in /etc/ttys. All OS scripts are located in /etc/rc.d/ and in /usr/local/etc/rc.d/ for third-party applications. The activation of the service is configured in /etc/rc.conf and /etc/rc.conf.local. The default behavior is configured in /etc/defaults/rc.conf. The scripts responds at least to start|stop|status.
# /etc/rc.d/sshd status sshd is running as pid 552. # shutdown now # Go into single-user mode # exit # Go back to multi-user mode # shutdown -p now # Shutdown and halt the system # shutdown -r now # Reboot
The process init can also be used to reach one of the following states level. For example # init 6 for reboot.
* 0 Halt and turn the power off (signal USR2)
* 1 Go to single-user mode (signal TERM)
* 6 Reboot the machine (signal INT)
* c Block further logins (signal TSTP)
* q Rescan the ttys(5) file (signal HUP)
Reset root password 重设root密码
Linux method 1 方法一
At the boot loader (lilo or grub), enter the following boot option: 在引导器上,键入下面得启动项:
init=/bin/sh
The kernel will mount the root partition and init will start the bourne shell instead of rc and then a runlevel. Use the command passwd at the prompt to change the password and then reboot. Forget the single user mode as you need the password for that. 内核会挂载根分区和初始化,反馈bash提示符。用passwd命令修改root用户密码,然后重启。
If, after booting, the root partition is mounted read only, remount it rw: 如果重启后,根分区被挂载成只读模式,那么需要重新挂载它成读写模式:
# mount -o remount,rw / # passwd # 也可以在/etc/shadow文件里删除root密码段 # sync; mount -o remount,ro / # sync before to remount read only # reboot
FreeBSD and Linux method 2 方法二
FreeBSD won't let you go away with the simple init trick. The solution is to mount the root partition from an other OS (like a rescue CD) and change the password on the disk. FreeBSD不会允许你用这个简单的init程序来诈取到它的控制权。解决办法就是从另一个操作系统(如修复CD)上来挂载根分区,然后修改密码。
* Boot a live CD or installation CD into a rescue mode which will give you a shell. 启动一个liveCD或者从某个安装CD引导进入rescue(修复)模式,获得一个shell提示符。
* Find the root partition with fdisk e.g. fdisk /dev/sda 用fdisk命令来查取根分区的位置。比如fdisk /dev/sda
* Mount it and use chroot: 挂载这个根分区,再用chroot命令切换。
# mount -o rw /dev/ad4s3a /mnt # chroot /mnt # chroot into /mnt # passwd # reboot
Alternatively on FreeBSD, boot in single user mode, remount / rw and use passwd.
# mount -u /; mount -a # will mount / rw # passwd # reboot
Kernel modules 内核模块
Linux
# lsmod # 显示所有已经加载的模块 # modprobe isdn # 加载模块isdn
FreeBSD
# kldstat # List all modules loaded in the kernel # kldload crypto # To load a module (here crypto)
Compile Kernel 编译内核(注,不同的发行版可能不会一样)
Linux
# cd /usr/src/linux # make mrproper # Clean everything, including config files # make oldconfig # 重新创建一个内核配置文件.config,如果有旧的.config文件的话,会出现提示修改的选项 # make menuconfig # or xconfig (Qt) or gconfig (GTK)在可视界面上配置内核选项 # make # Create a compressed kernel image编译内核 # make modules # Compile the modules # make modules_install # Install the modules编译并安装内核模块 # make install # Install the kernel安装内核(建议手动安装/usr/src/linux/arch/i386/boot/bzImage是内核文件,/usr/src/linux/System.map内核符号表) # reboot
FreeBSD
To modify and rebuild the kernel, copy the generic configuration file to a new name and edit it as needed. It is however also possible to edit the file GENERIC directly.
# cd /usr/src/sys/i386/conf/ # cp GENERIC MYKERNEL # cd /usr/src # make buildkernel KERNCONF=MYKERNEL # make installkernel KERNCONF=MYKERNEL
To rebuild the full OS:
# make buildworld # Build the full OS but not the kernel # make buildkernel # Use KERNCONF as above if appropriate # make installkernel # reboot # mergemaster -p # Compares only files known to be essential # make installworld # mergemaster # Update all configuration and other files # reboot
For small changes in the source, sometimes the short version is enough:
# make kernel world # Compile and install both kernel and OS # mergemaster # reboot
Processes 进程
Listing | Priority | Background/Foreground | Top | Kill
Listing and PIDs
Each process has a unique number, the PID. A list of all running process is retrieved with ps. 每一个进程都有一个独立的号码,这个号码就是PID。可以用ps反馈一个所有正在运行的进程列表。
# ps -auxefw # 所有正在运行的进程的一个扩展列表
However more typical usage is with a pipe or with pgrep: 不过,更多的典型用法是用管道结合其他命令或用pgrep完成:
Change the priority of a running process with renice. Negative numbers have a higher priority, the lowest is -20 and "nice" have a positive value. 用renice来改变进程的优先级。负数的优先级高,-20的优先级最高,nice命令用正数作为参数。
# renice -5 586 # 提高优先级 586: old priority 0, new priority -5
Start the process with a defined priority with nice. Positive is "nice" or weak, negative is strong scheduling priority. Make sure you know if /usr/bin/nice or the shell built-in is used (check with # which nice). 启动一个进程,并且同时用nice命令赋予它一个优先级。正数是降低优先级,负数是提高优先级。
# nice -n -5 top # 提高优先级 (/usr/bin/nice) # nice -n 5 top # 降低优先级 (/usr/bin/nice) # nice +5 top # tcsh builtin nice (same as above!)
Background/Foreground 后台/前台
When started from a shell, processes can be brought in the background and back to the foreground with [Ctrl]-[Z] (^Z), bg and fg. For example start two processes, bring them in the background, list the processes with jobs and bring one in the foreground. 从shell启动一个进程后,可以用ctrl-z,bg和fg命令来将进程作前后台切换。例如,启动两个进程,使它们转到后台,用jobs命令显示它们,并且使其中的一个转回前台。
Use nohup to start a process which has to keep running when the shell is closed (immune to hangups). 使用nohup命令来启动一个进程,使得该进程能够在shell关闭后继续运行。(对hangups命令免疫)
# nohup ping -i 60 > ping.log &
Top
The program top displays running information of processes. top程序显示正在运行的进程信息。
# top
While top is running press the key h for a help overview. Useful keys are: 在top命令运行的时候,可以用h来显示帮助。有用的关键字如下:
* u 加用户名,则显示只属于某个用户的所有进程。加一个+号或空格键,则显示所有用户的进程。
* k 加PID,杀掉某个PID的进程。
* 1 显示所有处理器的统计信息 (Linux only)
* R 大写的R用来升降排序。
Signals/Kill 杀死进程的信号
Terminate or send a signal with kill or killall. 终结或在kill或killall命令后加一个信号来杀死进程
# ping -i 60 cb.vu > ping.log & [1] 4712 # kill -s TERM 4712 # same as kill -15 4712 # killall -1 httpd # Kill HUP processes by exact name # pkill -9 http # Kill TERM processes by (part of) name # pkill -TERM -u www # Kill TERM processes owned by www # fuser -k -TERM -m /home # Kill every process accessing /home (to umount)
Important signals are: 重要的信号如下:
* 1 HUP (hang up)挂起
* 2 INT (interrupt)中断
* 3 QUIT (quit)退出
* 9 KILL (non-catchable, non-ignorable kill)硬杀死
* 15 TERM (software termination signal)软杀死
File System 文件系统
Disk info | Boot | Disk usage | Opened files | Mount/remount | Mount SMB | Mount image | Burn ISO | Create image | Memory disk | Disk performance
Permissions 权限
Change permission and ownership with chmod and chown. The default umask can be changed for all users in /etc/profile for Linux or /etc/login.conf for FreeBSD. The default umask is usually 022. The umask is subtracted from 777, thus umask 022 results in a permission 0f 755. 改变文件权限用chmod命令,改变文件所属用chown命令。对linux而言,可以在/etc/profile文件里改变针对所有用户的默认umask值,在FreeBSD中则是修改/etc/login.conf文件。一半,默认的umask值是022。权限值就是777减去umask值,因此,umask值为022就意味着权限是755。
# chmod [OPTION] MODE[,MODE] FILE # MODE is of the form [ugoa]*([-+=]([rwxXst])) # chmod 640 /var/log/maillog # Restrict the log -rw-r----- # chmod u=rw,g=r,o= /var/log/maillog # Same as above # chmod -R o-r /home/* # Recursive remove other readable for all users # chmod u+s /path/to/prog # Set SUID bit on executable (know what you do!) # find / -perm -u+s -print # Find all programs with the SUID bit # chown user:group /path/to/file # Change the user and group ownership of a file # chgrp group /path/to/file # Change the group ownership of a file
Disk information 磁盘信息
# diskinfo -v /dev/ad2 # information about disk (sector/size) FreeBSD # hdparm -I /dev/sda # information about the IDE/ATA disk (Linux) # fdisk /dev/ad2 # Display and manipulate the partition table # smartctl -a /dev/ad2 # Display the disk SMART info
Boot 启动
FreeBSD
To boot an old kernel if the new kernel doesn't boot, stop the boot at during the count down.
# du -sh * # 目录大小列表 # du -csh # 当前目录下的全部目录的大小 # du -ks * | sort -n -r # 对当前目录下所有文件进行以千字节为单位的降序排序 # ls -lSr # 显示当前目录下所有文件,按升序排列
Who has which files opened
This is useful to find out which file is blocking a partition which has to be unmounted and gives a typical error of: 使用下面的方法可以有效的发现某分区上的文件是否有正在被使用?由于文件正在被使用,所以导致分区不能卸载,并且会出现下面的那个错误提示:
# umount /home/ umount: unmount of /home # umount impossible because a file is locking home failed: Device busy
FreeBSD and most Unixes
# fstat -f /home # for a mount point # fstat -p PID # for an application with PID # fstat -u user # for a user name
Find opened log file (or other opened files), say for Xorg:
# ps ax | grep Xorg | awk '{print $1}' 1252 # fstat -p 1252 USER CMD PID FD MOUNT INUM MODE SZ|DV R/W root Xorg 1252 root / 2 drwxr-xr-x 512 r root Xorg 1252 text /usr 216016 -rws--x--x 1679848 r root Xorg 1252 0 /var 212042 -rw-r--r-- 56987 w
The file with inum 212042 is the only file in /var:
# find -x /var -inum 212042 /var/log/Xorg.0.log
Linux
Find opened files on a mount point with fuser or lsof: 用fuser或lsof命令来查找在一个已经挂载的分区上的被打开的文件:
# fuser -m /home # List processes accessing /home # lsof /home COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME tcsh 29029 eedcoba cwd DIR 0,18 12288 1048587 /home/eedcoba (guam:/home) lsof 29140 eedcoba cwd DIR 0,18 12288 1048587 /home/eedcoba (guam:/home)
Find the partition number containing with fdisk, this is usually the root partition, but it could be an other BSD slice too. If the FreeBSD has many slices, they are the one not listed in the fdisk table, but visible in /dev/sda* or /dev/hda*.
# fdisk /dev/sda # Find the FreeBSD partition /dev/sda3 * 5357 7905 20474842+ a5 FreeBSD # mount -t ufs -o ufstype=ufs2,ro /dev/sda3 /mnt /dev/sda10 = /tmp; /dev/sda11 /usr # The other slices
Remount
Remount a device without unmounting it. Necessary for fsck for example 重新挂摘一个设备并不需要先下载它。
# mount -o remount,ro / # Linux # mount -o ro / # FreeBSD
Copy the raw data from a cdrom into an iso image: 复制一个cdrom的镜像:
# dd if=/dev/cd0c of=file.iso
Mount an SMB share 挂摘一个samba共享目录
Suppose we want to access the SMB share myshare on the computer smbserver, the address as typed on a Windows PC is \\smbserver\myshare\. We mount on /mnt/smbshare. Warning> cifs wants an IP or DNS name, not a Windows name. 假设我们希望利用smbserver机器上的samba服务来共享myshare目录的话,在windows机器上的共享地址就是\\smbserver\myshare\。我们把它挂摘到/mnt/smbshare上。警告>之前必须知道windows服务器的ip地址或域名,而不是windows服务器的主机名。
Linux
# smbclient -U user -I 192.168.16.229 -L //smbshare/ # List the shares # mount -t smbfs -o username=winuser //smbserver/myshare /mnt/smbshare # mount -t cifs -o username=winuser,password=winpwd //192.168.16.229/myshare /mnt/share
Additionally with the package mount.cifs it is possible to store the credentials in a file, for example /home/user/.smb:
username=winuser password=winpwd
And mount as follow:
# mount -t cifs -o credentials=/home/user/.smb //192.168.16.229/myshare /mnt/smbshare
FreeBSD
Use -I to give the IP (or DNS name); smbserver is the Windows name.
# smbutil view -I 192.168.16.229 //winuser@smbserver # List the shares # mount_smbfs -I 192.168.16.229 //winuser@smbserver/myshare /mnt/smbshare
Mount an image 挂摘一个镜像
Linux loop-back linux回转
# mount -t iso9660 -o loop file.iso /mnt # Mount a CD image # mount -t ext3 -o loop file.img /mnt # Mount an image with ext3 fs
FreeBSD
With memory device (do # kldload md.ko if necessary):
# mdconfig -a -t vnode -f file.iso -u 0 # mount -t cd9660 /dev/md0 /mnt # umount /mnt; mdconfig -d -u 0 # Cleanup the md device
Or with virtual node:
# vnconfig /dev/vn0c file.iso; mount -t cd9660 /dev/vn0c /mnt # umount /mnt; vnconfig -u /dev/vn0c # Cleanup the vn device
Solaris and FreeBSD
with loop-back file interface or lofi:
# lofiadm -a file.iso # mount -F hsfs -o ro /dev/lofi/1 /mnt # umount /mnt; lofiadm -d /dev/lofi/1 # Cleanup the lofi device
Create and burn an ISO image 创建一个iso镜像
This will copy the cd or DVD sector for sector. Without conv=notrunc, the image will be smaller if there is less content on the cd. See below and the dd examples. 这个方法是以扇区为单位的复制cd或dvd。如果镜像大小不及一张cd的容量,则可以不用添加conv=notrunc参数。
Use mkisofs to create a CD/DVD image from files in a directory. To overcome the file names restrictions: -r enables the Rock Ridge extensions common to UNIX systems, -J enables Joliet extensions used by Microsoft systems. -L allows ISO9660 filenames to begin with a period. 使用mkisofs命令来为一个目录里的所有文件创建一个cd/dvd镜像。为了克服对文件名设定的限制,可以使用-r参数来使得unix系统使用the Rock Ridge扩展,使用-J参数来使得微软系统使用Joliet扩展。-L参数允许符合ISO9660的文件名。
# mkisofs -J -L -r -V TITLE -o imagefile.iso /path/to/dir
On FreeBSD, mkisofs is found in the ports in sysutils/cdrtools. Burn a CD/DVD ISO image
FreeBSD
FreeBSD does not enable DMA on ATAPI drives by default. DMA is enabled with the sysctl command and the arguments below, or with /boot/loader.conf with the following entries:
hw.ata.ata_dma="1" hw.ata.atapi_dma="1"
Use burncd with an ATAPI device (burncd is part of the base system) and cdrecord (in sysutils/cdrtools) with a SCSI drive. 使用burncd命令来刻录一个ATAPI设备,或用cdrecord命令来刻录一个SCSI设备。
# burncd -f /dev/acd0 data imagefile.iso fixate # For ATAPI drive # cdrecord -scanbus # To find the burner device (like 1,0,0) # cdrecord dev=1,0,0 imagefile.iso
Linux
Also use cdrecord with Linux as described above. Additionally it is possible to use the native ATAPI interface which is found with: 也可以使用cdrecord命令在linux下完成上面的任务,并且,cdrecord可以对ATAPI设备进行操作。
# cdrecord dev=ATAPI -scanbus
And burn the CD/DVD as above.如之前那样刻录cd/dvd。 Convert a Nero .nrg file to .iso将一个.nrg文件转换成.iso文件
Nero simply adds a 300Kb header to a normal iso image. This can be trimmed with dd. nero软件会在一个正常的iso镜像文件的头部增加300kb大小的内容。因此,可以用dd命令来调整掉这部分东西。
# route add -net 192.168.20.0 netmask 255.255.255.0 gw 192.168.16.254 # ip route add 192.168.20.0/24 via 192.168.16.254 # same as above with ip route # route add -net 192.168.20.0 netmask 255.255.255.0 dev eth0 # route add default gw 192.168.51.254 # ip route add default via 192.168.51.254 # same as above with ip route # route delete -net 192.168.20.0 netmask 255.255.255.0 gentoo下的网络设置都在/etc/conf.d/net文件中。
Check if a firewall is running (typical configuration only): 监测 Linux
# iptables -L -n -v # For status Open the iptables firewall # iptables -Z # Zero the packet and byte counters in all chains # iptables -F # Flush all chains # iptables -X # Delete all chains # iptables -P INPUT ACCEPT # Open everything # iptables -P FORWARD ACCEPT # iptables -P OUTPUT ACCEPT
FreeBSD
# ipfw show # For status # ipfw list 65535 # if answer is "65535 deny ip from any to any" the fw is disabled # sysctl net.inet.ip.fw.enable=0 # Disable # sysctl net.inet.ip.fw.enable=1 # Enable
# sysctl net.inet.ip.forwarding # Check IP forward 0=off, 1=on # sysctl net.inet.ip.forwarding=1 # sysctl net.inet.ip.fastforwarding=1 # For dedicated router or firewall Permanent with entry in /etc/rc.conf: gateway_enable="YES" # Set to YES if this host will be a gateway.
NAT Network Address Translation 网络地址转换
Linux
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE # to activate NAT # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 20022 -j DNAT \ --to 192.168.16.44:22 # Port forward 20022 to internal IP port ssh # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 993:995 -j DNAT \ --to 192.168.16.254:993:995 # Port forward of range 993-995 # ip route flush cache # iptables -L -t nat # Check NAT status
Delete the port forward with -D instead of -A.
FreeBSD
# natd -s -m -u -dynamic -f /etc/natd.conf -n fxp0 Or edit /etc/rc.conf with: firewall_enable="YES" # Set to YES to enable firewall functionality firewall_type="open" # Firewall type (see /etc/rc.firewall) natd_enable="YES" # Enable natd (if firewall_enable == YES). natd_interface="tun0" # Public interface or IP address to use. natd_flags="-s -m -u -dynamic -f /etc/natd.conf"
Port forward with:
# cat /etc/natd.conf same_ports yes use_sockets yes unregistered_only # redirect_port tcp insideIP:2300-2399 3300-3399 # port range redirect_port udp 192.168.51.103:7777 7777
DNS 域名解析服务
On Unix the DNS entries are valid for all interfaces and are stored in /etc/resolv.conf. The domain to which the host belongs is also stored in this file. A minimal configuration is: 注意,如果没有/etc/resolv.conf文件,或文件内容格式出错,那么系统就不能进行域名解析服务。
On Windows the DNS are configured per interface. To display the configured DNS and to flush the DNS cache use:
# ipconfig /? # Display help # ipconfig /all # See all information including DNS # ipconfig /flushdns # Flush the DNS cache
Forward queries
Dig is you friend to test the DNS settings. For example the public DNS server 213.133.105.2 ns.second-ns.de can be used for testing. See from which server the client receives the answer (simplified answer). dig命令可以很好的检测域名解析服务的设置情况。安装net-dns/bind-tools就可以得到dig命令。
# dig sleepyowl.net sleepyowl.net. 600 IN A 78.31.70.238 ;; SERVER: 192.168.51.254#53(192.168.51.254)
The router 192.168.51.254 answered and the response is the A entry. Any entry can be queried and the DNS server can be selected with @:
# dig MX google.com # dig @127.0.0.1 NS sun.com # To test the local server # dig @204.97.212.10 NS MX heise.de # Query an external server # dig AXFR @ns1.xname.org cb.vu # Get the full zone (zone transfer)
The program host is also powerful. host命令也很强大。
# host -t MX cb.vu # Get the mail MX entry # host -t NS -T sun.com # Get the NS record over a TCP connection # host -a sleepyowl.net # Get everything
Reverse queries 反向查询
Find the name belonging to an IP address (in-addr.arpa.). This can be done with dig, host and nslookup: 查找某个ip地址上的域名。
Single hosts can be configured in the file /etc/hosts instead of running named locally to resolve the hostname queries. The format is simple, for example: 单个主机的域名解析可以定义在/etc/hosts文件中,不必再运行named服务进程作域名解析。
78.31.70.238 sleepyowl.net sleepyowl
The priority between hosts and a dns query, that is the name resolution order, can be configured in /etc/nsswitch.conf AND /etc/host.conf. 在hosts文件和dns队列中间存在一个优先权的问题,系统先选择哪个文件来做域名解析需要看/etc/nsswitch.conf和/etc/host.conf文件中的定义。在nsswitch.conf文件里,file字段代表/etc/hosts文件,dns字段代表域名解析服务(named进程),谁写在前面就先用谁解析。在host.conf文件里的order行后hosts代表/etc/hosts文件,bind代表域名解析服务,谁在前就先用谁解析。nsswitch.conf只针对的是网络服务响应,host.conf针对是本地服务响应。
The file also exists on Windows, it is usually in:
C:\WINDOWS\SYSTEM32\DRIVERS\ETC
DHCP
Linux
Some distributions (SuSE) use dhcpcd as client. The default interface is eth0.
# dhcpcd -n eth0 # Trigger a renew # dhcpcd -k eth0 # release and shutdown
The lease with the full information is stored in:
/var/lib/dhcpcd/dhcpcd-eth0.info
FreeBSD
FreeBSD (and Debian) uses dhclient. To configure an interface (for example bge0) run:
# ipconfig /renew # renew all adapters # ipconfig /renew LAN # renew the adapter named "LAN" # ipconfig /release WLAN # release the adapter named "WLAN"
Yes it is a good idea to rename you adapter with simple names!
Traffic analysis
Bmon~tgr/bmon/ is a small console bandwidth monitor and can display the flow on different interfaces. Sniff with tcpdump
# tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.168.16.54\) # tcpdump -l > dump && tail -f dump # Buffered output # tcpdump -i rl0 -w traffic.rl0 # Write traffic in binary file # tcpdump -r traffic.rl0 # Read from file (also for ethereal # tcpdump port 80 # The two classic commands # tcpdump host google.com # tcpdump -i eth0 -X port \(110 or 143\) # Check if pop or imap is secure # tcpdump -n -i eth0 icmp # Only catch pings # tcpdump -i eth0 -s 0 -A port 80 | grep GET # -s 0 for full packet -A for ASCII
Additional important options:
* -A Print each packets in clear text (without header)
* -X Print packets in hex and ASCII
* -l Make stdout line buffered
* -D Print all interfaces available
On Windows use windump from Use windump -D to list the interfaces. Scan with nmap
Nmaphttp://insecure.org/nmap/ is a port scanner with OS detection, it is usually installed on most distributions and is also available for Windows. If you don't scan your servers, hackers do it for you...
# nmap cb.vu # scans all reserved TCP ports on the host # nmap -sP 192.168.16.0/24 # Find out which IP are used and by which host on 0/24 # nmap -sS -sV -O cb.vu # Do a stealth SYN scan with version and OS detection PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 3.8.1p1 FreeBSD-20060930 (protocol 2.0) 25/tcp open smtp Sendmail smtpd 8.13.6/8.13.6 80/tcp open http Apache httpd 2.0.59 ((FreeBSD) DAV/2 PHP/4. [...] Running: FreeBSD 5.X Uptime 33.120 days (since Fri Aug 31 11:41:04 2007)
Traffic control (QoS)
Traffic control manages the queuing, policing, scheduling, and other traffic parameters for a network. The following examples are simple practical uses of the Linux and FreeBSD capabilities to better use the available bandwidth. Limit upload
DSL or cable modems have a long queue to improve the upload throughput. However filling the queue with a fast device (e.g. ethernet) will dramatically decrease the interactivity. It is therefore useful to limit the device upload rate to match the physical capacity of the modem, this should greatly improve the interactivity. Set to about 90% of the modem maximal (cable) speed. Linux
For a 512 Kbit upload modem.
# tc qdisc add dev eth0 root tbf rate 480kbit latency 50ms burst 1540 # tc -s qdisc ls dev eth0 # Status # tc qdisc del dev eth0 root # Delete the queue # tc qdisc change dev eth0 root tbf rate 220kbit latency 50ms burst 1540
FreeBSD
FreeBSD uses the dummynet traffic shaper which is configured with ipfw. Pipes are used to set limits the bandwidth in units of [K|M]{bit/s|Byte/s}, 0 means unlimited bandwidth. Using the same pipe number will reconfigure it. For example limit the upload bandwidth to 500 Kbit.
# kldload dummynet # load the module if necessary # ipfw pipe 1 config bw 500Kbit/s # create a pipe with limited bandwidth # ipfw add pipe 1 ip from me to any # divert the full upload into the pipe
Quality of service
Linux
Priority queuing with tc to optimize VoIP. See the full example on voip-info.org or Suppose VoIP uses udp on ports 10000:11024 and device eth0 (could also be ppp0 or so). The following commands define the QoS to three queues and force the VoIP traffic to queue 1 with QoS 0x1e (all bits set). The default traffic flows into queue 3 and QoS Minimize-Delay flows into queue 2.
# tc qdisc add dev eth0 root handle 1: prio priomap 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 0 # tc qdisc add dev eth0 parent 1:1 handle 10: sfq # tc qdisc add dev eth0 parent 1:2 handle 20: sfq # tc qdisc add dev eth0 parent 1:3 handle 30: sfq # tc filter add dev eth0 protocol ip parent 1: prio 1 u32 \ match ip dport 10000 0x3C00 flowid 1:1 # use server port range match ip dst 123.23.0.1 flowid 1:1 # or/and use server IP
Status and remove with
# tc -s qdisc ls dev eth0 # queue status # tc qdisc del dev eth0 root # delete all QoS
Calculate port range and mask
The tc filter defines the port range with port and mask which you have to calculate. Find the 2^N ending of the port range, deduce the range and convert to HEX. This is your mask. Example for 10000 -> 11024, the range is 1024.
# 2^13 (8192) < 10000 < 2^14 (16384) # ending is 2^14 = 16384 # echo "obase=16;(2^14)-1024" | bc # mask is 0x3C00
FreeBSD
The max link bandwidth is 500Kbit/s and we define 3 queues with priority 100:10:1 for VoIP:ssh:all the rest.
# ipfw pipe 1 config bw 500Kbit/s # ipfw queue 1 config pipe 1 weight 100 # ipfw queue 2 config pipe 1 weight 10 # ipfw queue 3 config pipe 1 weight 1 # ipfw add 10 queue 1 proto udp dst-port 10000-11024 # ipfw add 11 queue 1 proto udp dst-ip 123.23.0.1 # or/and use server IP # ipfw add 20 queue 2 dsp-port ssh # ipfw add 30 queue 3 from me to any # all the rest
Status and remove with
# ipfw list # rules status # ipfw pipe list # pipe status # ipfw flush # deletes all rules but default
NIS Debugging
Some commands which should work on a well configured NIS client:
# ypwhich # get the connected NIS server name # domainname # The NIS domain name as configured # ypcat group # should display the group from the NIS server # cd /var/yp && make # Rebuild the yp database
Is ypbind running?
# ps auxww | grep ypbind /usr/sbin/ypbind -s -m -S servername1,servername2 # FreeBSD /usr/sbin/ypbind # Linux # yppoll passwd.byname Map passwd.byname has order number 1190635041. Mon Sep 24 13:57:21 2007 The master server is servername.domain.net.
Connect to a host without password using public key authentication. The idea is to append your public key to the authorized_keys2 file on the remote host. For this example let's connect host-client to host-server, the key is generated on the client.
* Use ssh-keygen to generate a key pair. ~/.ssh/id_dsa is the private key, ~/.ssh/id_dsa.pub is the public key.
* Copy only the public key to the server and append it to the file ~/.ssh/authorized_keys2 on your home on the server.
The non commercial version of the ssh.com client can be downloaded the main ftp site: ftp.ssh.com/pub/ssh/. Keys generated by the ssh.com client need to be converted for the OpenSSH server. This can be done with the ssh-keygen command.
* Create a key pair with the ssh.com client: Settings - User Authentication - Generate New....
* I use Key type DSA; key length 2048.
* Copy the public key generated by the ssh.com client to the server into the ~/.ssh folder.
* The keys are in C:\Documents and Settings\%USERNAME%\Application Data\SSH\UserKeys.
* Use the ssh-keygen command on the server to convert the key:
# cd ~/.ssh # ssh-keygen -i -f keyfilename.pub >> authorized_keys2
Notice: We used a DSA key, RSA is also possible. The key is not protected by a password. Using putty for Windows
Putty~sgtatham/putty/download.html is a simple and free ssh client for Windows.
* Create a key pair with the puTTYgen program.
* Save the public and private keys (for example into C:\Documents and Settings\%USERNAME%\.ssh).
* Copy the public key to the server into the ~/.ssh folder:
# scp .ssh/puttykey.pub root@192.168.51.254:.ssh/
* Use the ssh-keygen command on the server to convert the key for OpenSSH:
# cd ~/.ssh # ssh-keygen -i -f puttykey.pub >> authorized_keys2
* Point the private key location in the putty settings: Connection - SSH - Auth
Check fingerprint
At the first login, ssh will ask if the unknown host with the fingerprint has to be stored in the known hosts. To avoid a man-in-the-middle attack the administrator of the server can send you the server fingerprint which is then compared on the first login. Use ssh-keygen -l to get the fingerprint (on the server):
Now the client connecting to this server can verify that he is connecting to the right server:
# ssh linda The authenticity of host 'linda (192.168.16.54)' can't be established. DSA key fingerprint is 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee. Are you sure you want to continue connecting (yes/no)? yes
In Konqueror or Midnight Commander it is possible to access a remote file system with the address fish://user@gate. However the implementation is very slow.
Furthermore it is possible to mount a remote folder with sshfs a file system client based on SCP. See fuse sshfs
Tunneling
SSH tunneling allows to forward or reverse forward a port over the SSH connection, thus securing the traffic and accessing ports which would otherwise be blocked. This only works with TCP. The general nomenclature for forward and reverse is (see also ssh and NAT example):
# ssh -L localport:desthost:destport user@gate # desthost as seen from the gate # ssh -R destport:desthost:localport user@gate # forwards your localport to destination # ssh -X user@gate # To force X forwarding
This will connect to gate and forward the local port to the host desthost:destport. Note desthost is the destination host as seen by the gate, so if the connection is to the gate, then desthost is localhost. More than one port forward is possible. Direct forward on the gate
Let say we want to access the CVS (port 2401) and http (port 80) which are running on the gate. This is the simplest example, desthost is thus localhost, and we use the port 8080 locally instead of 80 so we don't need to be root. Once the ssh session is open, both services are accessible on the local ports.
The smb share can now be accessed with \\127.0.0.1\, but only if the local share is disabled, because the local share is listening on port 139.
It is possible to keep the local share enabled, for this we need to create a new virtual device with a new IP address for the tunnel, the smb share will be connected over this address. Furthermore the local RDP is already listening on 3389, so we choose 3388. For this example let's use a virtual IP of 10.1.1.1.
* With putty use Source port=10.1.1.1:139. It is possible to create multiple loop devices and tunnel. On Windows 2000, only putty worked for me.
* With the ssh.com client, disable "Allow local connections only". Since ssh.com will bind to all addresses, only a single share can be connected.
Now create the loopback interface with IP 10.1.1.1:
* # System->Control Panel->Add Hardware # Yes, Hardware is already connected # Add a new hardware device (at bottom).
* # Install the hardware that I manually select # Network adapters # Microsoft , Microsoft Loopback Adapter.
* Configure the IP address of the fake device to 10.1.1.1 mask 255.255.255.0, no gateway.
* advanced->WINS, Enable LMHosts Lookup; Disable NetBIOS over TCP/IP.
* # Enable Client for Microsoft Networks. # Disable File and Printer Sharing for Microsoft Networks.
I HAD to reboot for this to work. Now connect to the smb share with \\10.1.1.1 and remote desktop to 10.1.1.1:3388. Debug
If it is not working:
* Are the ports forwarded: netstat -an? Look at 0.0.0.0:139 or 10.1.1.1:139
* Does telnet 10.1.1.1 139 connect?
* You need the checkbox "Local ports accept connections from other hosts".
* Is "File and Printer Sharing for Microsoft Networks" disabled on the loopback interface?
Connect two clients behind NAT
Suppose two clients are behind a NAT gateway and client cliadmin has to connect to client cliuser (the destination), both can login to the gate with ssh and are running Linux with sshd. You don't need root access anywhere as long as the ports on gate are above 1024. We use 2022 on gate. Also since the gate is used locally, the option GatewayPorts is not necessary.
Suppose a Windows client with VNC listening on port 5900 has to be accessed from behind NAT. On client cliwin to gate:
# ssh -R 15900:localhost:5900 user@gate
On client cliadmin (from host to gate):
# ssh -L 5900:localhost:15900 admin@gate
Now the admin can connect directly to the client VNC with:
# vncconnect -display :0 localhost
VPN with SSH
As of version 4.3, OpenSSH can use the tun/tap device to encrypt a tunnel. This is very similar to other TLS based VPN solutions like OpenVPN. One advantage with SSH is that there is no need to install and configure additional software. Additionally the tunnel uses the SSH authentication like pre shared keys. The drawback is that the encapsulation is done over TCP which might result in poor performance on a slow link. Also the tunnel is relying on a single (fragile) TCP connection. This technique is very useful for a quick IP based VPN setup. There is no limitation as with the single TCP port forward, all layer 3/4 protocols like ICMP, TCP/UDP, etc. are forwarded over the VPN. In any case, the following options are needed in the sshd_conf file:
PermitRootLogin yes PermitTunnel yes
Single P2P connection
Here we are connecting two hosts, hclient and hserver with a peer to peer tunnel. The connection is started from hclient to hserver and is done as root. The tunnel end points are 10.0.1.1 (server) and 10.0.1.2 (client) and we create a device tun5 (this could also be an other number). The procedure is very simple:
* Connect with SSH using the tunnel option -w
* Configure the IP addresses of the tunnel. Once on the server and once on the client.
Connect to the server
Connection started on the client and commands are executed on the server. Server is on Linux
cli># ssh -w5:5 root@hserver srv># ifconfig tun5 10.0.1.1 netmask 255.255.255.252 # Executed on the server shell
Server is on FreeBSD
cli># ssh -w5:5 root@hserver srv># ifconfig tun5 10.0.1.1 10.0.1.2 # Executed on the server shell
Configure the client
Commands executed on the client:
cli># ifconfig tun5 10.0.1.2 netmask 255.255.255.252 # Client is on Linux cli># ifconfig tun5 10.0.1.2 10.0.1.1 # Client is on FreeBSD
The two hosts are now connected and can transparently communicate with any layer 3/4 protocol using the tunnel IP addresses.
Connect two networks
In addition to the p2p setup above, it is more useful to connect two private networks with an SSH VPN using two gates. Suppose for the example, netA is 192.168.51.0/24 and netB 192.168.16.0/24. The procedure is similar as above, we only need to add the routing. NAT must be activated on the private interface only if the gates are not the same as the default gateway of their network.
The two private networks are now transparently connected via the SSH VPN. The IP forward and NAT settings are only necessary if the gates are not the default gateways. In this case the clients would not know where to forward the response, and nat must be activated.
RSYNC
Rsync can almost completely replace cp and scp, furthermore interrupted transfers are efficiently restarted. A trailing slash (and the absence thereof) has different meanings, the man page is good... Here some examples:
Copy the directories with full content:
# rsync -a /home/colin/ /backup/colin/ # rsync -a /var/ /var_bak/ # rsync -aR --delete-during /home/user/ /backup/ # use relative (see below)
Same as before but over the network and with compression. Rsync uses SSH for the transport per default and will use the ssh key if they are set. Use ":" as with SCP. A typical remote copy:
Exclude any directory tmp within /home/user/ and keep the relative folders hierarchy, that is the remote directory will have the structure /backup/home/user/. This is typically used for backups.
Using the rsync daemon (used with "::") is much faster, but not encrypted over ssh. The location of /backup is defined by the configuration in /etc/rsyncd.conf. The variable RSYNC_PASSWORD can be set to avoid the need to enter the password manually.
# rsync -axSRz /home/ ruser@hostname::rmodule/backup/ # rsync -axSRz ruser@hostname::rmodule/backup/ /home/ # To copy back
Some important options:
* -a, --archive archive mode; same as -rlptgoD (no -H)
* -r, --recursive recurse into directories
* -R, --relative use relative path names
* -H, --hard-links preserve hard links
* -S, --sparse handle sparse files efficiently
* -x, --one-file-system don't cross file system boundaries
* --delete-during receiver deletes during xfer, not before
* --delete-after receiver deletes after transfer, not before
Rsync on Windows
Rsync is available for Windows through cygwin or as stand-alone packaged in cwrsync This is very convenient for automated backups. Install one of them (not both) and add the path to the Windows system variables: # Control Panel -> System -> tab Advanced, button Environment Variables. Edit the "Path" system variable and add the full path to the installed rsync, e.g. C:\Program Files\cwRsync\bin or C:\cygwin\bin. This way the commands rsync and ssh are available in a Windows command shell. Public key authentication
Rsync is automatically tunneled over SSH and thus uses the SSH authentication on the server. Automatic backups have to avoid a user interaction, for this the SSH public key authentication can be used and the rsync command will run without a password.
All the following commands are executed within a Windows console. In a console (Start -> Run -> cmd) create and upload the key as described in SSH, change "user" and "server" as appropriate. If the file authorized_keys2 does not exist yet, simply copy id_dsa.pub to authorized_keys2 and upload it.
# ssh-keygen -t dsa -N '' # Creates a public and a private key # rsync user@server:.ssh/authorized_keys2 . # Copy the file locally from the server # cat id_dsa.pub >> authorized_keys2 # Or use an editor to add the key # rsync authorized_keys2 user@server:.ssh/ # Copy the file back to the server # del authorized_keys2 # Remove the local copy
Now test it with (in one line):
rsync -rv "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \ 'user@server:My\ Documents/'
Automatic backup
Use a batch file to automate the backup and add the file in the scheduled tasks (Programs -> Accessories -> System Tools -> Scheduled Tasks). For example create the file backup.bat and replace user@server.
@ECHO OFF REM rsync the directory My Documents SETLOCAL SET CWRSYNCHOME=C:\PROGRAM FILES\CWRSYNC SET CYGWIN=nontsec SET CWOLDPATH=%PATH% REM uncomment the next line when using cygwin SET PATH=%CWRSYNCHOME%\BIN;%PATH% echo Press Control-C to abort rsync -av "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \ 'user@server:My\ Documents/' pause
SUDO
Sudo is a standard way to give users some administrative rights without giving out the root password. Sudo is very useful in a multi user environment with a mix of server and workstations. Simply call the command with sudo:
# sudo /etc/init.d/dhcpd restart # Run the rc script as root # sudo -u sysadmin whoami # Run cmd as an other user
Configuration
Sudo is configured in /etc/sudoers and must only be edited with visudo. The basic syntax is (the lists are comma separated):
user hosts = (runas) commands # In /etc/sudoers
* users one or more users or %group (like %wheel) to gain the rights
* hosts list of hosts (or ALL)
* runas list of users (or ALL) that the command rule can be run as. It is enclosed in ( )!
* commands list of commands (or ALL) that will be run as root or as (runas)
Additionally those keywords can be defined as alias, they are called User_Alias, Host_Alias, Runas_Alias and Cmnd_Alias. This is useful for larger setups. Here a sudoers example:
# cat /etc/sudoers # Host aliases are subnets or hostnames. Host_Alias DMZ = 212.118.81.40/28 Host_Alias DESKTOP = work1, work2
# User aliases are a list of users which can have the same rights User_Alias ADMINS = colin, luca, admin User_Alias DEVEL = joe, jack, julia Runas_Alias DBA = oracle,pgsql
# Command aliases define the full path of a list of commands Cmnd_Alias SYSTEM = /sbin/reboot,/usr/bin/kill,/sbin/halt,/sbin/shutdown,/etc/init.d/ Cmnd_Alias PW = /usr/bin/passwd [A-z]*, !/usr/bin/passwd root # Not root pwd! Cmnd_Alias DEBUG = /usr/sbin/tcpdump,/usr/bin/wireshark,/usr/bin/nmap
# The actual rules root,ADMINS ALL = (ALL) NOPASSWD: ALL # ADMINS can do anything w/o a password. DEVEL DESKTOP = (ALL) NOPASSWD: ALL # Developers have full right on desktops DEVEL DMZ = (ALL) NOPASSWD: DEBUG # Developers can debug the DMZ servers.
# User sysadmin can mess around in the DMZ servers with some commands. sysadmin DMZ = (ALL) NOPASSWD: SYSTEM,PW,DEBUG sysadmin ALL,!DMZ = (ALL) NOPASSWD: ALL # Can do anything outside the DMZ. %dba ALL = (DBA) ALL # Group dba can run as database user.
# anyone can mount/unmount a cd-rom on the desktop machines ALL DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom
Encrypt Files
A single file
Encrypt and decrypt:
# openssl des -salt -in file -out file.des # openssl des -d -salt -in file.des -out file
Note that the file can of course be a tar archive.
tar and encrypt a whole directory
# tar -cf - directory | openssl des -salt -out directory.tar.des # Encrypt # openssl des -d -salt -in directory.tar.des | tar -x # Decrypt
tar zip and encrypt a whole directory
# tar -zcf - directory | openssl des -salt -out directory.tar.gz.des # Encrypt # openssl des -d -salt -in directory.tar.gz.des | tar -xz # Decrypt
* Use -k mysecretpassword after des to avoid the interactive password request. However note that this is highly insecure.
* Use des3 instead of des to get even stronger encryption (Triple-DES Cipher). This uses also more CPU.
Encrypt Partitions
Linux with LUKS | Linux dm-crypt only | FreeBSD GELI | FBSD pwd only
There are (many) other alternative methods to encrypt disks, I only show here the methods I know and use. Keep in mind that the security is only good as long the OS has not been tempered with. An intruder could easily record the password from the keyboard events. Furthermore the data is freely accessible when the partition is attached and will not prevent an intruder to have access to it in this state. Linux
Those instructions use the Linux dm-crypt (device-mapper) facility available on the 2.6 kernel. In this example, lets encrypt the partition /dev/sdc1, it could be however any other partition or disk, or USB or a file based partition created with losetup. In this case we would use /dev/loop0. See file image partition. The device mapper uses labels to identify a partition. We use sdc1 in this example, but it could be any string. dm-crypt with LUKS
LUKS with dm-crypt has better encryption and makes it possible to have multiple passphrase for the same partition or to change the password easily. To test if LUKS is available, simply type # cryptsetup --help, if nothing about LUKS shows up, use the instructions below Without LUKS. First create a partition if necessary: fdisk /dev/sdc. Create encrypted partition
# dd if=/dev/urandom of=/dev/sdc1 # Optional. For paranoids only (takes days) # cryptsetup -y luksFormat /dev/sdc1 # This destroys any data on sdc1 # cryptsetup luksOpen /dev/sdc1 sdc1 # mkfs.ext3 /dev/mapper/sdc1 # create ext3 file system # mount -t ext3 /dev/mapper/sdc1 /mnt # umount /mnt # cryptsetup luksClose sdc1 # Detach the encrypted partition
# cryptsetup -y create sdc1 /dev/sdc1 # or any other partition like /dev/loop0 # dmsetup ls # check it, will display: sdc1 (254, 0) # mkfs.ext3 /dev/mapper/sdc1 # This is done only the first time! # mount -t ext3 /dev/mapper/sdc1 /mnt # umount /mnt/ # cryptsetup remove sdc1 # Detach the encrypted partition
Do exactly the same (without the mkfs part!) to re-attach the partition. If the password is not correct, the mount command will fail. In this case simply remove the map sdc1 (cryptsetup remove sdc1) and create it again. FreeBSD
The two popular FreeBSD disk encryption modules are gbde and geli. I now use geli because it is faster and also uses the crypto device for hardware acceleration. See The FreeBSD handbook Chapter 18.6 for all the details. The geli module must be loaded or compiled into the kernel:
options GEOM_ELI device crypto # or as module: # echo 'geom_eli_load="YES"' >> /boot/loader.conf # or do: kldload geom_eli
Use password and key
I use those settings for a typical disk encryption, it uses a passphrase AND a key to encrypt the master key. That is you need both the password and the generated key /root/ad1.key to attach the partition. The master key is stored inside the partition and is not visible. See below for typical USB or file based image. Create encrypted partition
# dd if=/dev/random of=/root/ad1.key bs=64 count=1 # this key encrypts the mater key # geli init -s 4096 -K /root/ad1.key /dev/ad1 # -s 8192 is also OK for disks # geli attach -k /root/ad1.key /dev/ad1 # DO make a backup of /root/ad1.key # dd if=/dev/random of=/dev/ad1.eli bs=1m # Optional and takes a long time # newfs /dev/ad1.eli # Create file system # mount /dev/ad1.eli /mnt
Attach
# geli attach -k /root/ad1.key /dev/ad1 # fsck -ny -t ffs /dev/ad1.eli # In doubt check the file system # mount /dev/ad1.eli /mnt
Detach
The detach procedure is done automatically on shutdown.
# umount /mnt # geli detach /dev/ad1.eli
/etc/fstab
The encrypted partition can be configured to be mounted with /etc/fstab. The password will be prompted when booting. The following settings are required for this example:
It is more convenient to encrypt a USB stick or file based image with a passphrase only and no key. In this case it is not necessary to carry the additional key file around. The procedure is very much the same as above, simply without the key file. Let's encrypt a file based image /cryptedfile of 1 GB.
So called SSL/TLS certificates are cryptographic public key certificates and are composed of a public and a private key. The certificates are used to authenticate the endpoints and encrypt the data. They are used for example on a web server (https) or mail server (imaps). Procedure
* We need a certificate authority to sign our certificate. This step is usually provided by a vendor like Thawte, Verisign, etc., however we can also create our own.
* Create a certificate signing request. This request is like an unsigned certificate (the public part) and already contains all necessary information. The certificate request is normally sent to the authority vendor for signing. This step also creates the private key on the local machine.
* Sign the certificate with the certificate authority.
* If necessary join the certificate and the key in a single file to be used by the application (web server, mail server etc.).
Configure OpenSSL
We use /usr/local/certs as directory for this example check or edit /etc/ssl/openssl.cnf accordingly to your settings so you know where the files will be created. Here are the relevant part of openssl.cnf:
[ CA_default ] dir = /usr/local/certs/CA # Where everything is kept certs = $dir/certs # Where the issued certs are kept crl_dir = $dir/crl # Where the issued crl are kept database = $dir/index.txt # database index file.
Make sure the directories exist or create them
# mkdir -p /usr/local/certs/CA # cd /usr/local/certs/CA # mkdir certs crl newcerts private # echo "01" > serial # Only if serial does not exist # touch index.txt
Create a certificate authority
If you do not have a certificate authority from a vendor, you'll have to create your own. This step is not necessary if one intend to use a vendor to sign the request. To make a certificate authority (CA):
To make a new certificate (for mail server or web server for example), first create a request certificate with its private key. If your application do not support encrypted private key (for example UW-IMAP does not), then disable encryption with -nodes.
# openssl req -new -keyout newkey.pem -out newreq.pem \ -config /etc/ssl/openssl.cnf # openssl req -nodes -new -keyout newkey.pem -out newreq.pem \ -config /etc/ssl/openssl.cnf # No encryption for the key
Sign the certificate
The certificate request has to be signed by the CA to be valid, this step is usually done by the vendor. Note: replace "servername" with the name of your server in the next commands.
Now servernamekey.pem is the private key and servernamecert.pem is the server certificate.
Create united certificate
The IMAP server wants to have both private key and server certificate in the same file. And in general, this is also easier to handle, but the file has to be kept securely!. Apache also can deal with it well. Create a file servername.pem containing both the certificate and key.
* Open the private key (servernamekey.pem) with a text editor and copy the private key into the "servername.pem" file.
* Do the same with the server certificate (servernamecert.pem).
The final servername.pem file should look like this:
What we have now in the directory /usr/local/certs/:
* CA/private/cakey.pem (CA server private key)
* CA/cacert.pem (CA server public key)
* certs/servernamekey.pem (server private key)
* certs/servernamecert.pem (server signed certificate)
* certs/servername.pem (server certificate with private key)
Keep the private key secure!
View certificate information
To view the certificate information simply do:
# openssl x509 -text -in servernamecert.pem # View the certificate info # openssl req -noout -text -in server.csr # View the request info
CVS
Server setup | CVS test | SSH tunneling | CVS usage
Server setup
Initiate the CVS
Decide where the main repository will rest and create a root cvs. For example /usr/local/cvs (as root):
# mkdir -p /usr/local/cvs # setenv CVSROOT /usr/local/cvs # Set CVSROOT to the new location (local) # cvs init # Creates all internal CVS config files # cd /root # cvs checkout CVSROOT # Checkout the config files to modify them # cd CVSROOT edit config ( fine as it is) # cvs commit config cat >> writers # Create a writers file (optionally also readers) colin ^D # Use [Control][D] to quit the edit # cvs add writers # Add the file writers into the repository # cvs edit checkoutlist # cat >> checkoutlist writers ^D # Use [Control][D] to quit the edit # cvs commit # Commit all the configuration changes
Add a readers file if you want to differentiate read and write permissions Note: Do not (ever) edit files directly into the main cvs, but rather checkout the file, modify it and check it in. We did this with the file writers to define the write access.
There are three popular ways to access the CVS at this point. The first two don't need any further configuration. See the examples on CVSROOT below for how to use them:
* Direct local access to the file system. The user(s) need sufficient file permission to access the CS directly and there is no further authentication in addition to the OS login. However this is only useful if the repository is local.
* Remote access with ssh with the ext protocol. Any use with an ssh shell account and read/write permissions on the CVS server can access the CVS directly with ext over ssh without any additional tunnel. There is no server process running on the CVS for this to work. The ssh login does the authentication.
* Remote access with pserver. This is the preferred use for larger user base as the users are authenticated by the CVS pserver with a dedicated password database, there is therefore no need for local users accounts. This setup is explained below.
Network setup with inetd
The CVS can be run locally only if a network access is not needed. For a remote access, the daemon inetd can start the pserver with the following line in /etc/inetd.conf (/etc/xinetd.d/cvs on SuSE):
It is a good idea to block the cvs port from the Internet with the firewall and use an ssh tunnel to access the repository remotely.
Separate authentication
It is possible to have cvs users which are not part of the OS (no local users). This is actually probably wanted too from the security point of view. Simply add a file named passwd (in the CVSROOT directory) containing the users login and password in the crypt format. This is can be done with the apache htpasswd tool.
Note: This passwd file is the only file which has to be edited directly in the CVSROOT directory. Also it won't be checked out. More info with htpasswd --help
Now add :cvs at the end of each line to tell the cvs server to change the user to cvs (or whatever your cvs server is running under). It looks like this:
Test the login as normal user (for example here me)
# cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs login Logging in to :pserver:colin@192.168.50.254:2401/usr/local/cvs CVS password:
CVSROOT variable
This is an environment variable used to specify the location of the repository we're doing operations on. For local use, it can be just set to the directory of the repository. For use over the network, the transport protocol must be specified. Set the CVSROOT variable with setenv CVSROOT string on a csh, tcsh shell, or with export CVSROOT=string on a sh, bash shell.
# setenv CVSROOT :pserver:@:/cvsdirectory For example: # setenv CVSROOT /usr/local/cvs # Used locally only # setenv CVSROOT :local:/usr/local/cvs # Same as above # setenv CVSROOT :ext:user@cvsserver:/usr/local/cvs # Direct access with SSH # setenv CVS_RSH ssh # for the ext access # setenv CVSROOT :pserver:user@cvsserver.254:/usr/local/cvs # network with pserver
When the login succeeded one can import a new project into the repository: cd into your project root directory
Where MyProject is the name of the new project in the repository (used later to checkout). Cvs will import the current directory content into the new project.
We need 2 shells for this. On the first shell we connect to the cvs server with ssh and port-forward the cvs connection. On the second shell we use the cvs normally as if it where running locally.
on shell 1:
# ssh -L2401:localhost:2401 colin@cvs_server # Connect directly to the CVS server. Or: # ssh -L2401:cvs_server:2401 colin@gateway # Use a gateway to reach the CVS
on shell 2:
# setenv CVSROOT :pserver:colin@localhost:/usr/local/cvs # cvs login Logging in to :pserver:colin@localhost:2401/usr/local/cvs CVS password: # cvs checkout MyProject/src
CVS commands and usage
Import
The import command is used to add a whole directory, it must be run from within the directory to be imported. Say the directory /devel/ contains all files and subdirectories to be imported. The directory name on the CVS (the module) will be called "myapp".
# cvs import [options] directory-name vendor-tag release-tag # cd /devel # Must be inside the project to import it # cvs import myapp Company R1_0 # Release tag can be anything in one word
After a while a new directory "/devel/tools/" was added and it has to be imported too.
# cd /devel/tools # cvs import myapp/tools Company R1_0
Checkout update add commit
# cvs co myapp/tools # Will only checkout the directory tools # cvs co -r R1_1 myapp # Checkout myapp at release R1_1 (is sticky) # cvs -q -d update -P # A typical CVS update # cvs update -A # Reset any sticky tag (or date, option) # cvs add newfile # Add a new file # cvs add -kb newfile # Add a new binary file # cvs commit file1 file2 # Commit the two files only # cvs commit -m "message" # Commit all changes done with a message
Create a patch
It is best to create and apply a patch from the working development directory related to the project, or from within the source directory.
# cd /devel/project # diff -Naur olddir newdir > patchfile # Create a patch from a directory or a file # diff -Naur oldfile newfile > patchfile
Apply a patch
Sometimes it is necessary to strip a directory level from the patch, depending how it was created. In case of difficulties, simply look at the first lines of the patch and try -p0, -p1 or -p2.
# cd /devel/project # patch --dry-run -p0 < patchfile # Test the path without applying it # patch -p0 < patchfile # patch -p1 < patchfile # strip off the 1st level from the path
SVN
Server setup | SVN+SSH | SVN over http | SVN usage
Subversion (SVN) is a version control system designed to be the successor of CVS (Concurrent Versions System). The concept is similar to CVS, but many shortcomings where improved. See also the SVN book Server setup
The initiation of the repository is fairly simple (here for example /home/svn/ must exist):
Now the access to the repository is made possible with:
* file:// Direct file system access with the svn client with. This requires local permissions on the file system.
* svn:// or svn+ssh:// Remote access with the svnserve server (also over SSH). This requires local permissions on the file system.
* http:// Remote access with webdav using apache. No local users are necessary for this method.
Using the local file system, it is now possible to import and then check out an existing project. Unlike with CVS it is not necessary to cd into the project directory, simply give the full path:
As with the local file access, every user needs an ssh access to the server (with a local account) and also read/write access. This method might be suitable for a small group. All users could belong to a subversion group which owns the repository, for example:
Remote access over http (https) is the only good solution for a larger user group. This method uses the apache authentication, not the local accounts. This is a typical but small apache configuration:
LoadModule dav_module modules/mod_dav.so LoadModule dav_svn_module modules/mod_dav_svn.so LoadModule authz_svn_module modules/mod_authz_svn.so # Only for access control
DAV svn # any "/svn/foo" URL will map to a repository /home/svn/foo SVNParentPath /home/svn AuthType Basic AuthName "Subversion repository" AuthzSVNAccessFile /etc/apache2/svn.acl AuthUserFile /etc/apache2/svn-passwd Require valid-user
The apache server needs full access to the repository:
# chown -R www:www /home/svn
Create a user with htpasswd2:
# htpasswd -c /etc/svn-passwd user1 # -c creates the file
Access control svn.acl example
# Default it read access. "* =" would be default no access [/] * = r [groups] project1-developers = joe, jack, jane # Give write access to the developers [project1:] @project1-developers = rw
SVN commands and usage
See also the Subversion Quick Reference Card Tortoise SVN is a nice Windows interface. Import
A new project, that is a directory with some files, is imported into the repository with the import command. Import is also used to add a directory with its content to an existing project.
# svn help import # Get help for any command # Add a new directory (with content) into the src dir on project1 # svn import /project1/newdir -m 'add newdir'
Typical SVN commands
# svn co # Checkout the most recent version # Tags and branches are created by copying # svn mkdir # Create the tags directory # svn copy -m "Tag rc1 rel." \
# svn status [--verbose] # Check files status into working dir # svn add src/file.h src/file.cpp # Add two files # svn commit -m 'Added new class file' # Commit the changes with a message # svn ls # List all tags # svn move foo.c bar.c # Move (rename) files # svn delete some_old_file # Delete files
Useful Commands
less | vi | mail | tar | dd | screen | find | Miscellaneous
less
The less command displays a text document on the console. It is present on most installation.
# less unixtoolbox.xhtml
Some important commands are (^N stands for [control]-[N]):
* h H good help on display
* f ^F ^V SPACE Forward one window (or N lines).
* b ^B ESC-v Backward one window (or N lines).
* F Forward forever; like "tail -f".
* /pattern Search forward for (N-th) matching line.
* ?pattern Search backward for (N-th) matching line.
* n Repeat previous search (for N-th occurrence).
* N Repeat previous search in reverse direction.
* q quit
vi
Vi is present on ANY Linux/Unix installation and it is therefore useful to know some basic commands. There are two modes: command mode and insertion mode. The commands mode is accessed with [ESC], the insertion mode with i. Quit
* :w newfilename save the file to newfilename
* :wq or :x save and quit
* :q! quit without saving
Search and move
* /string Search forward for string
* ?string Search back for string
* n Search for next instance of string
* N Search for previous instance of string
* { Move a paragraph back
* } Move a paragraph forward
* 1G Move to the first line of the file
* nG Move to the n th line of the file
* G Move to the last line of the file
* :%s/OLD/NEW/g Search and replace every occurrence
Delete text
* dd delete current line
* D Delete to the end of the line
* dw Delete word
* x Delete character
* u Undo last
* U Undo all changes to current line
mail
The mail command is a basic application to read and send email, it is usually installed. To send an email simply type "mail user@domain". The first line is the subject, then the mail content. Terminate and send the email with a single dot (.) in a new line. Example:
# mail c@cb.vu Subject: Your text is full of typos "For a moment, nothing happened. Then, after a second or so, nothing continued to happen." . EOT #
This is also working with a pipe:
# echo "This is the mail body" | mail c@cb.vu
This is also a simple way to test the mail server.
tar
The command tar (tape archive) creates and extracts archives of file and directories. The archive .tar is uncompressed, a compressed archive has the extension .tgz or .tar.gz (zip) or .tbz (bzip2). Do not use absolute path when creating an archive, you probably want to unpack it somewhere else. Some typical commands are: Create
# cd / # tar -cf home.tar home/ # archive the whole /home directory (c for create) # tar -czf home.tgz home/ # same with zip compression # tar -cjf home.tbz home/ # same with bzip2 compression
Only include one (or two) directories from a tree, but keep the relative structure. For example archive /usr/local/etc and /usr/local/www and the first directory in the archive should be local/.
# tar -C /usr -czf local.tgz local/etc local/www # tar -C /usr -xzf local.tgz # To untar the local dir into /usr # cd /usr; tar -xzf local.tgz # Is the same as above
Extract
# tar -tzf home.tgz # look inside the archive without extracting (list) # tar -xf home.tar # extract the archive here (x for extract) # tar -xzf home.tgz # same with zip compression # tar -xjf home.tgz # same with bzip2 compression # tar -xjf home.tgz home/colin/file.txt # Restore a single file
More advanced
# tar c dir/ | gzip | ssh user@remote 'dd of=dir.tgz' # arch dir/ and store remotely. # tar cvf - `find . -print` > backup.tar # arch the current directory. # tar -cf - -C /etc . | tar xpf - -C /backup/etc # Copy directories # tar -cf - -C /etc . | ssh user@remote tar xpf - -C /backup/etc # Remote copy. # tar -czf home.tgz --exclude '*.o' --exclude 'tmp/' home/
dd
The program dd (disk dump) is used to copy partitions and disks and for other copy tricks. Typical usage: