advanced unix

99
Advanced UNIX Advanced UNIX Spring 2007 Spring 2007 Review Chap 10-14 Review Chap 10-14

Upload: gibson

Post on 04-Jan-2016

48 views

Category:

Documents


0 download

DESCRIPTION

Advanced UNIX. Spring 2007 Review Chap 10-14. Definition of root & su. root (1): a file system term describing the top level directory of a drive or storage volume. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Advanced UNIX

Advanced UNIXAdvanced UNIX

Spring 2007Spring 2007

Review Chap 10-14Review Chap 10-14

Page 2: Advanced UNIX

Definition of root & suDefinition of root & su rootroot (1): a file system term describing (1): a file system term describing

the top level directory of a drive or the top level directory of a drive or storage volume. storage volume.

rootroot (2), or (2), or root accessroot access: authorization : authorization within Unix-based operating systems within Unix-based operating systems that allows a user to make system-wide that allows a user to make system-wide changes. This includes the ability to changes. This includes the ability to open and modify files that are off-limits open and modify files that are off-limits to normal users, such as system files to normal users, such as system files and and files within other users' home and and files within other users' home directories. directories.

supersuper useruser (su): a user who has been (su): a user who has been given root access. given root access.

Page 3: Advanced UNIX

The root accountThe root account

Never login in as rootNever login in as root• It is dangerousIt is dangerous• There is There is no audit trailno audit trail• Always login with your personal accountAlways login with your personal account

Then su to rootThen su to root

• Disable root logins from the networkDisable root logins from the network RSC (Remote System Console)RSC (Remote System Console)

• Change the root password frequentlyChange the root password frequently• DoD does this every 90 daysDoD does this every 90 days

Page 4: Advanced UNIX

The Shell PromptThe Shell Prompt

The command line prompt will The command line prompt will indicate if you are logged in as root indicate if you are logged in as root by displaying a by displaying a ## before the cursor before the cursor

For System-V derivatives of UNIX you For System-V derivatives of UNIX you will see a will see a $$ if you are logged in as a if you are logged in as a normal user, normal user, %% if your are on a if your are on a Berkeley derivative of UNIXBerkeley derivative of UNIX

Page 5: Advanced UNIX

Changing a PasswordChanging a Password

To Change the password of the To Change the password of the account you’re logged in as type the account you’re logged in as type the following:following:

passwd <enter>passwd <enter> To change the password of another To change the password of another

user type the following:user type the following:passwd <userid>passwd <userid>

For class you should change your For class you should change your password password

Page 6: Advanced UNIX

Using the su commandUsing the su command

The su command allows one to The su command allows one to become another user without logging become another user without logging off or to assume a role. The default off or to assume a role. The default user user namename is root (super user). is root (super user). • To su to root type the following:To su to root type the following:

susu

• To su to another user type the following:To su to another user type the following:

su <userid>su <userid>

Page 7: Advanced UNIX

Administration ToolsAdministration Tools

With Fedora the Sys Admin tools With Fedora the Sys Admin tools have the following syntaxhave the following syntax

““system-config-xxxxsystem-config-xxxx”” GUI Admin ToolsGUI Admin Tools

• Vary from Windows ManagerVary from Windows Manager GnomeGnome KDEKDE Etc…Etc…

Page 8: Advanced UNIX

Administration CommandsAdministration Commands

Most system administration Most system administration commands are locate in “commands are locate in “sbinsbin” ” directories such as:directories such as:• /sbin/sbin• /usr/sbin/usr/sbin• /usr/local/sbin/usr/local/sbin

Page 9: Advanced UNIX

Administrative Config FilesAdministrative Config Files

Most configuration files are located in Most configuration files are located in the the /etc/etc directory directory• /etc/passwd/etc/passwd• /etc/shadow/etc/shadow• /etc/mail/*/etc/mail/*• /etc/hosts/etc/hosts• /etc/fstab/etc/fstab• /etc/resolv.conf/etc/resolv.conf• See pages 367-371See pages 367-371

Page 10: Advanced UNIX

Administrative Log FilesAdministrative Log Files

Most logs are located in Most logs are located in /var/log/var/log directorydirectory• /var/log/messages/var/log/messages• /var/log/lp/var/log/lp• /var/log/mail or /var/log/maillog/var/log/mail or /var/log/maillog• /var/log/cron/var/log/cron• /var/log/wtmp/var/log/wtmp

Page 11: Advanced UNIX

Limited root Access With sudoLimited root Access With sudo

You can grant access to root You can grant access to root commands to specific users using commands to specific users using the the sudosudo command command

Key files are:Key files are:• /etc/sudoers/etc/sudoers• /usr/sbin/visudo/usr/sbin/visudo• visudo - edits the sudoers file visudo - edits the sudoers file

Page 12: Advanced UNIX

Administrative ToolsAdministrative Tools

superuser = rootsuperuser = root• Unrestricted accessUnrestricted access• Become a superuserBecome a superuser

Log in to rootLog in to root Use su or su –Use su or su –

• Inherits the env from current shellInherits the env from current shell

• Only use superuser when it is neededOnly use superuser when it is needed• Change root password periodicallyChange root password periodically

Employment status change for SAEmployment status change for SA Unauthorized accessUnauthorized access

Page 13: Advanced UNIX

Administrative ToolsAdministrative Tools

• Always lock your screenAlways lock your screen Use xlock or simply log offUse xlock or simply log off

• Controlling su accessControlling su access System VSystem V BSD – member’s of group 0BSD – member’s of group 0 Linux – GNU su does not check Linux – GNU su does not check

membership of group 0membership of group 0

• Run a command with su same timeRun a command with su same time su root –c “command”su root –c “command”

Page 14: Advanced UNIX

Administrative ToolsAdministrative Tools Facility sudoFacility sudo

• Selective accessSelective access• Allow some user to run specific commands Allow some user to run specific commands

as root without having to know the root as root without having to know the root passwordpassword

RUN sudo commandRUN sudo command• Type in user’s own passwordType in user’s own password• Good for a configurable time, default 5 minutesGood for a configurable time, default 5 minutes

• Configuration file /etc/sudoersConfiguration file /etc/sudoers UsersUsers CommandsCommands FormatFormat

Users host=commandsUsers host=commands

Page 15: Advanced UNIX

Administrative ToolsAdministrative Tools

• Advantages of sudoAdvantages of sudo Command logging - accountabilitiesCommand logging - accountabilities Operators can do choresOperators can do chores Hide the real root passwordHide the real root password Revoke the privilege without changing Revoke the privilege without changing

the root passwordthe root password A list of users with privileged access is A list of users with privileged access is

maintained maintained Less chance of root shell left unattendedLess chance of root shell left unattended

Page 16: Advanced UNIX

System AdministrationSystem Administration

Some additional duties of a system Some additional duties of a system administrator are:administrator are:• Hardware ConfigurationHardware Configuration• File System ManagementFile System Management• System MonitoringSystem Monitoring

For hardware configuration a common For hardware configuration a common Linux tool is Linux tool is KudzuKudzu• http://rhlinux.redhat.com/kudzu/http://rhlinux.redhat.com/kudzu/

Page 17: Advanced UNIX

KudzuKudzu

Hardware probing tool run at system boot Hardware probing tool run at system boot time to determine what hardware has time to determine what hardware has been added or removed from the system.been added or removed from the system.

kudzukudzu is normally configured to run at is normally configured to run at startupstartup

It will check you system for hardware then It will check you system for hardware then compare the results with compare the results with /etc/sysconfig/hwconf/etc/sysconfig/hwconf

If changes are detected If changes are detected kudzukudzu will prompt will prompt you to change your system configurationyou to change your system configuration

Page 18: Advanced UNIX

KudzuKudzu

Devices Devices kudzukudzu will detect and will detect and configure are:configure are:• Network devicesNetwork devices• SCSI devicesSCSI devices• Audio devicesAudio devices• Input/Output devices (keyboards, mice)Input/Output devices (keyboards, mice)• CD-ROMsCD-ROMs• ScannersScanners

Page 19: Advanced UNIX

ModulesModules WWhat is a loadable kernel modulehat is a loadable kernel module

WWhen to use moduleshen to use modules

Intel 80386 memory managementIntel 80386 memory management

How module gets loaded in proper locationHow module gets loaded in proper location

Internals of moduleInternals of module

LLinking and unlinking moduleinking and unlinking module

Page 20: Advanced UNIX

Kernel module descriptionKernel module description To add a new code to a Linux kernel, it is To add a new code to a Linux kernel, it is

necessary to add some source files to kernel necessary to add some source files to kernel source tree and recompile the kernel. source tree and recompile the kernel.

But you can also add code to the Linux But you can also add code to the Linux kernel while it is running. A chunk of code kernel while it is running. A chunk of code added in such way is called a loadable kernel added in such way is called a loadable kernel modulemodule

Typical modules:Typical modules:• device driversdevice drivers• file system driversfile system drivers• system callssystem calls

Page 21: Advanced UNIX

When kernel code must be a When kernel code must be a ModuleModule

Some higher level component of Linux Some higher level component of Linux kernel can be compiled as moduleskernel can be compiled as modules

Some Linux kernel code must be linked Some Linux kernel code must be linked statically then component is included in the statically then component is included in the kernel or it is not compiled at allkernel or it is not compiled at all

Basic Rules of Thumb:Basic Rules of Thumb:• Installed kernels are bloatedInstalled kernels are bloated• A working kernel should be built with anything A working kernel should be built with anything

that is necessary to get the system booted upthat is necessary to get the system booted up• Everything else can be built as a modulesEverything else can be built as a modules

Page 22: Advanced UNIX

Advantages of modulesAdvantages of modules

There is no necessity to rebuild the kernel, when a There is no necessity to rebuild the kernel, when a new kernel option is addednew kernel option is added

Modules help find system problems (if system Modules help find system problems (if system

problem caused a module just don't load it)problem caused a module just don't load it)

Modules save memoryModules save memory

Modules are much easier to maintain and debugModules are much easier to maintain and debug

Modules once loaded are as fast as a kernelModules once loaded are as fast as a kernel

Page 23: Advanced UNIX

Module ImplementationModule Implementation

Modules are stored in the file system as Modules are stored in the file system as ELFELF ((EExecutable and xecutable and LLinkable inkable FFormat) ormat) object filesobject files

The kernel makes sure that the rest of the kernel The kernel makes sure that the rest of the kernel

can reach the module's global symbolscan reach the module's global symbols

Module must know the addresses of symbols Module must know the addresses of symbols

(variables and functions) in the kernel and in other (variables and functions) in the kernel and in other

modules The modules The

kernel keeps track of the use of modules, so that no kernel keeps track of the use of modules, so that no

modules is unloaded while another module or modules is unloaded while another module or

kernel is using itkernel is using it

Page 24: Advanced UNIX

Programs for linking and unlinkingPrograms for linking and unlinking insmodinsmod

• Reads from the name of the module to be linkedReads from the name of the module to be linked• Locates the file containing the module's object codeLocates the file containing the module's object code• Computes the size of the memory area needed to store Computes the size of the memory area needed to store

the module code, its name, andthe module code, its name, and the module objectthe module object lsmodlsmod

• reads /proc/modulesreads /proc/modules rmmodrmmod

• Invokes the query_module( ) system callInvokes the query_module( ) system call• Invokes the delete_module( ) system callInvokes the delete_module( ) system call

Use the QM_REFS subcommand several times, to retrieve Use the QM_REFS subcommand several times, to retrieve dependency information on the linked modulesdependency information on the linked modules

modprobemodprobe• takes care of possible complications due to moduletakes care of possible complications due to module

ddependencies, uses depmod program and ependencies, uses depmod program and /etc/modules.conf/etc/modules.conf file file

Page 25: Advanced UNIX

Disk devices are represented by device files Disk devices are represented by device files that reside in the that reside in the /dev/dev directorydirectory• Device fileDevice file – a file used by Linux commands that – a file used by Linux commands that

represent a specific device on the systemrepresent a specific device on the system• Character devicesCharacter devices

Transfer data to and from the system one character or Transfer data to and from the system one character or data bit at a timedata bit at a time

• Block devicesBlock devices Storage devices that transfer to and from the system in Storage devices that transfer to and from the system in

chunks of many bits by caching the information in RAMchunks of many bits by caching the information in RAM Can transfer information must faster than character Can transfer information must faster than character

devicesdevices

File System AdministrationFile System Administration

Page 26: Advanced UNIX

MountingMountingMountingMounting Process used to associate a device with a directory Process used to associate a device with a directory

in the logical directory tree such that users may in the logical directory tree such that users may store data on that devicestore data on that device

Mount pointMount point Directory in a file structure to which something is Directory in a file structure to which something is

mountedmounted

Mount floppy to default mount point (directory)Mount floppy to default mount point (directory)$ $ mount /dev/fd0mount /dev/fd0

Mount floppy to specified mount point (directory)Mount floppy to specified mount point (directory)$ $ mount /dev/fd0 /floppermount /dev/fd0 /flopper

Page 27: Advanced UNIX

Working with Hard DisksWorking with Hard Disks

IDE hard disk drives attach to the mainboard with an IDE cable and must be configured on one of four configurations, each of which has a different device file:• Primary master (/dev/hda)• Primary slave (/dev/hdb)• Secondary master (/dev/hdc)• Secondary slave (/dev/hdd)

Page 28: Advanced UNIX

Working with Hard DisksWorking with Hard Disks

SCSI hard disks are well-suited to SCSI hard disks are well-suited to UNIX/Linux servers that require a UNIX/Linux servers that require a great deal of storage space for great deal of storage space for programs and user filesprograms and user files

Different device files associated with Different device files associated with SCSI hard disks:SCSI hard disks:• First SCSI hard disk drive (/dev/sda)First SCSI hard disk drive (/dev/sda)• Second SCSI hard disk drive (/dev/sdb)Second SCSI hard disk drive (/dev/sdb)• Third SCSI hard disk drive (/dev/sdc)Third SCSI hard disk drive (/dev/sdc)

Page 29: Advanced UNIX

Hard Disk PartitioningHard Disk Partitioning

Recall that hard disks have the largest Recall that hard disks have the largest storage capacity of any device used to storage capacity of any device used to store information on a regular basisstore information on a regular basis• This poses some problems, because as the This poses some problems, because as the

size of a disk increases, organization size of a disk increases, organization becomes more difficult and the chance of becomes more difficult and the chance of error increaseserror increases

PartitionPartition• A physical division of a hard disk driveA physical division of a hard disk drive

Page 30: Advanced UNIX

User ManagementUser Management There are many more aspects to user There are many more aspects to user

management than just creating an management than just creating an account and setting a passwordaccount and setting a password• setting password expirationsetting password expiration• setting password complexitysetting password complexity• setting account expirationsetting account expiration• manage groupsmanage groups

Next we will set up a user account, set Next we will set up a user account, set password expiration, modify the default password expiration, modify the default password length, add a group and set the password length, add a group and set the default group for new users (from the default group for new users (from the command line of course)command line of course)

Page 31: Advanced UNIX

Class LabClass Lab

Using vi, change the max number of Using vi, change the max number of days a password can be used to days a password can be used to 180180• Edit Edit /etc/login.defs/etc/login.defs• Change PASS_MAX_DAYS to Change PASS_MAX_DAYS to 180180

Using vi change the minimum Using vi change the minimum password length to password length to 77• Edit Edit /etc/login.defs/etc/login.defs• PASS_MIN_LEN to PASS_MIN_LEN to 77

Page 32: Advanced UNIX

Class LabClass Lab

Create a new group called Create a new group called studentsstudents using the groupadd commandusing the groupadd command(as root) (as root) groupadd studentsgroupadd students

Change default group for new users Change default group for new users to students using the useradd to students using the useradd commandcommand(as root)(as root) useradd –D –g studentsuseradd –D –g students

Create an account for yourselfCreate an account for yourself

Page 33: Advanced UNIX

Class LabClass Lab

Create a new user with an expiration Create a new user with an expiration date of 02/28/2007date of 02/28/2007useradd –e 02/28/2007 user1useradd –e 02/28/2007 user1

Look at /etc/shadowLook at /etc/shadowuser1:!!:13555:0:180:7::13572:user1:!!:13555:0:180:7::13572:

The 13555 is the number of days The 13555 is the number of days from 1 Jan 1970 (the UNIX Epoch from 1 Jan 1970 (the UNIX Epoch date) and 13572 is 28 Feb 2007date) and 13572 is 28 Feb 2007

Page 34: Advanced UNIX

Class LabClass Lab

Add your full name to the account you Add your full name to the account you created for yourself using usermodcreated for yourself using usermodusermod –c “<yourname>” <userid>usermod –c “<yourname>” <userid>

Bottom Line – Many, many ways to Bottom Line – Many, many ways to manage manage your usersyour users. Including the . Including the various GUI applications.various GUI applications.

Page 35: Advanced UNIX

Unix “Unix “EpochEpoch” Date = ” Date = 1 Jan 19701 Jan 1970

The early Unix engineers picked that The early Unix engineers picked that date arbitrarily, because they needed date arbitrarily, because they needed to set a uniform date for the start of to set a uniform date for the start of time, and New Year's Day, 1970 time, and New Year's Day, 1970 seemed most convenient. seemed most convenient.

Page 36: Advanced UNIX

System ProfilesSystem Profiles

When a user logs in a system profile When a user logs in a system profile is establishedis established• Set’s environment variablesSet’s environment variables

I.e. PATH=/bin;/usr/bin;I.e. PATH=/bin;/usr/bin;• Set’s alias’sSet’s alias’s

I.e. alias rm ‘rm –i’I.e. alias rm ‘rm –i’alias cp ‘cp –I’alias cp ‘cp –I’alias cls ‘clear’alias cls ‘clear’

Page 37: Advanced UNIX

System ProfilesSystem Profiles

Various system-wide profiles:Various system-wide profiles:• /etc/profile/etc/profile (bourne shell) (bourne shell)• /etc/bashrc/etc/bashrc (bash shell) (bash shell)• /etc/tcshrc (c-shell)/etc/tcshrc (c-shell)

User specific profiles (located in home User specific profiles (located in home dir)dir)• ~/.profile~/.profile• ~/.bashrc~/.bashrc• ~/.tcshrc~/.tcshrc

Page 38: Advanced UNIX

Shell ScriptsShell Scripts

A A shell scriptshell script is a group of commands, is a group of commands, functions, variables, etc., that can be run functions, variables, etc., that can be run from the shell prompt (command line)from the shell prompt (command line)

Chapter 12 gives an overview of how shell Chapter 12 gives an overview of how shell scripts work and can be used.scripts work and can be used.• Automate system choresAutomate system chores• Application startupApplication startup• Even generate web pagesEven generate web pages

http://www.wildbill.org/rose/spring07.cgihttp://www.wildbill.org/rose/spring07.cgi

Page 39: Advanced UNIX

Shell Scripts (/etc/init.d/*)Shell Scripts (/etc/init.d/*)

Many of the startup scripts are Many of the startup scripts are located in the located in the /etc/init.d/etc/init.d directory directory

Know and understand Know and understand symbolic linkssymbolic links A A symbolic Linksymbolic Link is where a file has is where a file has

one main name, but there's an extra one main name, but there's an extra entry in the file name table that entry in the file name table that refers any accesses back to the main refers any accesses back to the main namename

Page 40: Advanced UNIX

Shell Scripts (/etc/init.d/*)Shell Scripts (/etc/init.d/*)

Many of the startup scripts are Many of the startup scripts are located in the located in the /etc/init.d/etc/init.d directory directory

Know and understand Know and understand symbolic linkssymbolic links A A symbolic Linksymbolic Link is where a file has is where a file has

one main name, but there's an extra one main name, but there's an extra entry in the file name table that entry in the file name table that refers any accesses back to the main refers any accesses back to the main namename

Page 41: Advanced UNIX

Symbolic LinksSymbolic Links

Symbolic links are set up using the ln Symbolic links are set up using the ln command with the -s option - so for command with the -s option - so for exampleexampleln -s filename1.txt ln -s filename1.txt filename2.txtfilename2.txt

Page 42: Advanced UNIX

LILOLILO /etc/lilo.conf/etc/lilo.conf

• Location of kernelLocation of kernel• Disk partition to mount as root file Disk partition to mount as root file

systemsystem

Map installerMap installer• Read configuration fileRead configuration file• Write boot loaders, OS info to hard Write boot loaders, OS info to hard

diskdisk

Page 43: Advanced UNIX

GRUBGRUB

Boot time shellBoot time shell GRUB interactive command GRUB interactive command

promptprompt Run new configuration on the Run new configuration on the

flyfly Dynamic default configurationDynamic default configuration Can use to boot other OSCan use to boot other OS

Page 44: Advanced UNIX

GRUBGRUB /boot/grub/grub.conf/boot/grub/grub.conf

• # general section # general section • splashimage splashimage

(hd0,0)/grub/splash.xpm.gz(hd0,0)/grub/splash.xpm.gz• default 0 default 0 • timeout 30 timeout 30 • password -md5 password -md5 encoded-passwordencoded-password

• title Linux title Linux • root (hd0,0) root (hd0,0)

kernel /vmlinuz ro root=/dev/hda2 kernel /vmlinuz ro root=/dev/hda2

Page 45: Advanced UNIX

Compare LILO and GRUBCompare LILO and GRUB LILOLILO

• TraditionalTraditional• Need to be Need to be

reinstalled in the reinstalled in the master boot record master boot record after replacing the after replacing the kernel or changing kernel or changing the boot the boot configurationconfiguration

GRUB GRUB • NewerNewer• FlexibleFlexible• Interactive Interactive

command promptcommand prompt

Page 46: Advanced UNIX

Kernel initializationKernel initialization Checks system hardwareChecks system hardware Identifies devicesIdentifies devices

KernelKernel• Makes hardware do what the Makes hardware do what the

programs wantprograms want

Page 47: Advanced UNIX

Kernel InitializationKernel Initialization

Probe essential devicesProbe essential devices• CPU, Console, MemoryCPU, Console, Memory

Probe other hardware SubsystemProbe other hardware Subsystem• I/O buses, Network interfaces, Hard I/O buses, Network interfaces, Hard

disks, CD-ROM drives, Floppy disks, CD-ROM drives, Floppy drives, Storage devicesdrives, Storage devices

Page 48: Advanced UNIX

Kernel InitializationKernel Initialization

File System initializationFile System initialization• Logical volume manager subsystemLogical volume manager subsystem• RAIDRAID• SCSI DevicesSCSI Devices• Hard disk partitionsHard disk partitions

Change configuration of kernelChange configuration of kernel• /usr/src/linux/make menuconfig or /usr/src/linux/make menuconfig or

xconfigxconfig• rdevrdev• Boot loader parameterBoot loader parameter

Page 49: Advanced UNIX

InitInit Location: Location: /sbin/init/sbin/init Uses functions from libraries written in CUses functions from libraries written in C Checks and mounts file systemChecks and mounts file system Starts up daemons to log system messagesStarts up daemons to log system messages Starts the Starts the gettygetty processes that put the processes that put the

login prompts on your virtual terminalslogin prompts on your virtual terminals NetworkingNetworking Serves web pageServes web page Listen to the mouseListen to the mouse

Page 50: Advanced UNIX

Inittab fileInittab file

Location: Location: /etc/inittab/etc/inittab xx:levels:action:processxx:levels:action:process XxXx

• Label for the entryLabel for the entry LevelsLevels

• Specific system operating modeSpecific system operating mode• Predefined set of system Predefined set of system

processesprocesses

Page 51: Advanced UNIX

Run levels in initRun levels in init 00: : Halted system (ready for powering Halted system (ready for powering

off) off) 11:: Conversion to/preparation for single Conversion to/preparation for single

user mode user mode 22:: Non-networked multiuser mode Non-networked multiuser mode 33:: Networked multiuser mode Networked multiuser mode 44:: Networked multiuser mode with Networked multiuser mode with

graphical login graphical login 66:: Reboot mode Reboot mode

Page 52: Advanced UNIX

Run levels in initRun levels in init SS,,ss:: Single user mode Single user mode UU,,uu:: Init process re-execution Init process re-execution

(pseudo run level) (pseudo run level) QQ,,qq:: Force reread of configuration Force reread of configuration

file (pseudo run level) file (pseudo run level) aa,,bb,,cc:: On-demand process On-demand process

initialization pseudo run levels initialization pseudo run levels

Page 53: Advanced UNIX

Inittab fileInittab file ActionsActions

• waitwait:: Start the process and wait for it to Start the process and wait for it to finish before going onto the next entry.finish before going onto the next entry.

• onceonce:: Start the process only if it is not Start the process only if it is not already running (don't wait).already running (don't wait).

• respawnrespawn:: Start the process (don't wait) Start the process (don't wait) and automatically re-start it if the and automatically re-start it if the process later dies.process later dies.

Page 54: Advanced UNIX

Inittab fileInittab file• bootwaitbootwait:: Execute the process only at Execute the process only at

boot time, waiting for it to finish.boot time, waiting for it to finish.• initdefaultinitdefault:: Specifies default run level. Specifies default run level.• ctrlaltdelctrlaltdel:: Execute the action when the Execute the action when the

Ctrl-Alt-Del key sequence is detected.Ctrl-Alt-Del key sequence is detected.• power*power*:: Several keywords are defined Several keywords are defined

for various power failure-related events for various power failure-related events (see examples below)(see examples below)

Page 55: Advanced UNIX

InittabInittab Program to interpret the Program to interpret the

initialization script – bashinitialization script – bash Script link to other scriptsScript link to other scripts Several scriptsSeveral scripts

• Initialization scriptInitialization script• Run-level scriptRun-level script

Page 56: Advanced UNIX

Initialization scriptInitialization script Initialization scriptInitialization script

• (Red hat) (Red hat) /etc/rc.d/rc.sysinit/etc/rc.d/rc.sysinit• File system get checked and mountedFile system get checked and mounted

/etc/fstab/etc/fstab

• Clock setClock set• Swap space enabledSwap space enabled• HostnameHostname

Page 57: Advanced UNIX

Shutting down sequenceShutting down sequence shutdownshutdown [ [-h-h//rr] ] (warning message)(warning message) Logins are blockedLogins are blocked All process are notified that the system is All process are notified that the system is

going down by signal SIGTERMgoing down by signal SIGTERM Process to exit cleanlyProcess to exit cleanly Signal the init process to change the run Signal the init process to change the run

level level • Default 1, -h flag 0, -r flag 6Default 1, -h flag 0, -r flag 6

Page 58: Advanced UNIX

Shutting down Shutting down unmount -aunmount -a unmounts all the unmounts all the

partitions listed in fstabpartitions listed in fstab shutdown -Fshutdown -F = Force fsck on reboot = Force fsck on reboot

• Journaling file systemJournaling file system saves a transaction log of file system saves a transaction log of file system

changeschanges replay when the system is restartedreplay when the system is restarted

Page 59: Advanced UNIX

Service ManagementService Management

There are plenty of GUI tools to control There are plenty of GUI tools to control system startup scripts (/etc/init.d/*)system startup scripts (/etc/init.d/*)

The command line tool of choice is called The command line tool of choice is called chkconfigchkconfig

chkconfig chkconfig provides a simple command-provides a simple command-line tool for maintaining the /etc/rc[0-6].d line tool for maintaining the /etc/rc[0-6].d directory hierarchy by relieving system directory hierarchy by relieving system administrators of the task of directly administrators of the task of directly manipulating the numerous symbolic links manipulating the numerous symbolic links in those directories (see in those directories (see man chkconfigman chkconfig))

Page 60: Advanced UNIX

Service ManagementService Management

To list all the services typeTo list all the services type

chkconfig --listchkconfig --list This will display This will display allall the services and there the services and there

status with each run level and you may status with each run level and you may want to pipe it to ‘want to pipe it to ‘lessless’ or ‘’ or ‘moremore’’

To modify or change the run level(s) for To modify or change the run level(s) for when the daemon or service is started when the daemon or service is started type:type:chkconfig --level <runlevels> <service> on/offchkconfig --level <runlevels> <service> on/off

Page 61: Advanced UNIX

Service ManagementService Management

So to change the network service to So to change the network service to run for levels 3 and 5 only type:run for levels 3 and 5 only type:chkconfig –level 35 network onchkconfig –level 35 network on

You can also add a service/daemon You can also add a service/daemon to your configuration using the –add to your configuration using the –add switchswitchchkconfig --add <service>chkconfig --add <service>

To turn a service off or onTo turn a service off or onchkconfig <service> off chkconfig <service> off or or onon

Page 62: Advanced UNIX

The “Super Daemon”The “Super Daemon” xinetdxinetd - the extended Internet services - the extended Internet services

daemon (not to be confused with daemon (not to be confused with initdinitd)) xinetdxinetd performs the same function as performs the same function as

inetdinetd: it starts programs that provide : it starts programs that provide Internet services. Internet services.

Instead of having such servers started at Instead of having such servers started at system initialization time, and be dormant system initialization time, and be dormant until a connection request arrives, until a connection request arrives, • xinetdxinetd is the only daemon started and it listens is the only daemon started and it listens

on all service ports for the services listed in its on all service ports for the services listed in its configuration file.configuration file.

Page 63: Advanced UNIX

The “Super Daemon”The “Super Daemon”

Benefits are:Benefits are:• Fewer running processesFewer running processes• Access control and logging (PAM)Access control and logging (PAM)

logging controllogging control• log on success, failure, bothlog on success, failure, both• specify what is logged (user name, duration)specify what is logged (user name, duration)

• IMHO the book examples are not that IMHO the book examples are not that good so here are some of mine:good so here are some of mine:

sshdsshd cvscvs rsyncrsync

Page 64: Advanced UNIX

The “Super Daemon”The “Super Daemon”

/etc/xinetd.conf/etc/xinetd.conf is the configuration file is the configuration file /etc/xinetd.d/etc/xinetd.d is the directory where all is the directory where all

the real info is.the real info is. Demo: Demo: /etc/xinet.d/etc/xinet.d Many security experts say you should Many security experts say you should

shut down xinetd and delete the files shut down xinetd and delete the files from from /etc/xinet.d/etc/xinet.d -- this is if you are -- this is if you are going to really lock down a servergoing to really lock down a server

One thing I will say – If you are not One thing I will say – If you are not using it shut it down/turn it off.using it shut it down/turn it off.

Page 65: Advanced UNIX

rsyncrsync

rsync -avz dir1 node01:.rsync -avz dir1 node01:. Option Option aa stands for archive (preserve links stands for archive (preserve links

and timestamps); and timestamps); vv is for verbose and is for verbose and zz is is for data compression when sending-for data compression when sending-receiving.receiving.• In the case above, rsync was running in the clear In the case above, rsync was running in the clear

To run rsync over ssh, specify To run rsync over ssh, specify "-e ssh"-e ssh" " option: option:

rsync -e ssh -avz dir1 node01:.rsync -e ssh -avz dir1 node01:.

Page 66: Advanced UNIX

UNIX Scheduler SystemUNIX Scheduler System The The croncron system is used to schedule commands system is used to schedule commands

to be executed periodically. to be executed periodically. • The name is derived from Greek The name is derived from Greek chronoschronos (χρόνος), (χρόνος),

meaning time.meaning time. The major components:The major components:

• crondcrond• crontabcrontab• atat or or batchbatch

Generally, the schedules modified by Generally, the schedules modified by crontabcrontab are are enacted by a daemon, enacted by a daemon, crondcrond, ,

crondcrond runs in the background runs in the background • checks once a minute to see if any of the scheduled jobs checks once a minute to see if any of the scheduled jobs

need to be executed. need to be executed. • If so, it executes them. These jobs are generally referred If so, it executes them. These jobs are generally referred

to as cron jobs.to as cron jobs.

Page 67: Advanced UNIX

UNIX Scheduler SystemUNIX Scheduler System The directories:The directories:

• /etc/cron.d/etc/cron.d• /etc/cron.hourly/etc/cron.hourly• /etc/cron.daily/etc/cron.daily• /etc/cron.weekly/etc/cron.weekly• /etc/cron.monthly/etc/cron.monthly

The files:The files:• /etc/crontab/etc/crontab• /etc/cron.deny/etc/cron.deny• /var/spool/cron/<user-cron>/var/spool/cron/<user-cron>• /etc/cron.allow/etc/cron.allow• /etc/cron.deny/etc/cron.deny

Page 68: Advanced UNIX

crontab and at commandscrontab and at commands

crontab commands:crontab commands:• List:List: crontab –lcrontab –l• Edit:Edit: crontab –e crontab –e • Dump:Dump: crontab –l > cronfilecrontab –l > cronfile

at commandsat commands• Edit:Edit: at at or or batchbatch• List:List: atqatq• Remove:Remove: atrmatrm

Page 69: Advanced UNIX

Crontab FieldsCrontab Fields

1.1. Minute 0-59Minute 0-592.2. Hour 0-23Hour 0-233.3. Day 1-31Day 1-314.4. Month 1-12Month 1-125.5. Weekday 0-6 (0=Sunday)Weekday 0-6 (0=Sunday)

* Matches everything* Matches everything1-3 Matches range1-3 Matches range1,5 Matches Series1,5 Matches Series

Page 70: Advanced UNIX

CronCron Write your own Cron fileWrite your own Cron file

• Format:Format: Minute Hour Day Month DayofWeek CommandMinute Hour Day Month DayofWeek Command

• Examples:Examples: 10 0,4,8,12,16,20 * * * ping –c 60 www.yahoo.com10 0,4,8,12,16,20 * * * ping –c 60 www.yahoo.com 0 22 * * 5 ./test.sh0 22 * * 5 ./test.sh

• Wildcard Wildcard ** for any entry for any entry• Comma Comma ,, indicates multiple values (NO space inside) indicates multiple values (NO space inside)• Dash Dash –– indicate a range indicate a range

9-179-17: from 9am to 5pm: from 9am to 5pm• Slash Slash // indicate stepped values indicate stepped values

*/2*/2 : every 2 hour, minute… : every 2 hour, minute…

Page 71: Advanced UNIX

at & batchat & batch

at: run command once at a specified timeat: run command once at a specified time• For example:For example:

at 2:00at 2:00 ./test.sh./test.sh

• Ctrl + d to exitCtrl + d to exit batch: run command once when system is batch: run command once when system is

idleidle• OS decides an appropriate time to runOS decides an appropriate time to run• Similar syntax as atSimilar syntax as at

Page 72: Advanced UNIX

System BackupsSystem Backups

Why backup your files?Why backup your files?• System crashSystem crash

Hard driveHard drive Stupid SA tricksStupid SA tricks HackersHackers

You can make it a simple processYou can make it a simple process• Shell scriptsShell scripts

Or an involved processOr an involved process• Open source or COTS applicationOpen source or COTS application

Page 73: Advanced UNIX

Backup SchemesBackup Schemes

  Full backupFull backup::• Backing up all files on your computer Backing up all files on your computer

Incremental backupIncremental backup::• Backing up all files which have been modified Backing up all files which have been modified

since the last Full backupsince the last Full backup Disk MirroringDisk Mirroring (Raid-1): (Raid-1): Network Backup:Network Backup:

• All of the above can be done over the networkAll of the above can be done over the network

Page 74: Advanced UNIX

More Backup SoftwareMore Backup Software

Rsync (542)Rsync (542) cdrecord (page 551)cdrecord (page 551) dump (page 557)dump (page 557) mirrordir (page 492)mirrordir (page 492) pax (page 566)pax (page 566) amanda (page 502)amanda (page 502) tar, cpio, dd, etc…..tar, cpio, dd, etc…..

Page 75: Advanced UNIX

Hacker vs CrackerHacker vs Cracker

Many definitions aboundMany definitions abound Most are inaccurateMost are inaccurate Look to the Request For Comment Look to the Request For Comment

Files (RFC’s)Files (RFC’s)• Specifically RFC 1983 “Specifically RFC 1983 “Internet Users' Internet Users'

GlossaryGlossary””• It defines Hacker and Cracker as:It defines Hacker and Cracker as:

Page 76: Advanced UNIX

CrackerCracker

A cracker is an individual who A cracker is an individual who attempts to access computer attempts to access computer systems without authorization. These systems without authorization. These individuals are often malicious, as individuals are often malicious, as opposed to hackers, and have many opposed to hackers, and have many means at their disposal for breaking means at their disposal for breaking into a system. into a system.

Page 77: Advanced UNIX

HackerHacker

A Hacker is a person who delights in A Hacker is a person who delights in having an intimate understanding of having an intimate understanding of the internal workings of a system, the internal workings of a system, computers and computer networks in computers and computer networks in particular. The term is often misused particular. The term is often misused in a pejorative context, where in a pejorative context, where "cracker" would be the correct term. "cracker" would be the correct term.

Page 78: Advanced UNIX

Attack TrendsAttack Trends

AutomationAutomation SophisticationSophistication Vulnerability IDVulnerability ID Firewall HolesFirewall Holes Asymmetric ThreatAsymmetric Threat Infrastructure AttacksInfrastructure Attacks

Page 79: Advanced UNIX

Point’s of AttackPoint’s of Attack

Web ClientsWeb Clients Email ClientsEmail Clients Network Shares (Netbios, NFS, etc.)Network Shares (Netbios, NFS, etc.) Network Servers (Web, FTP, ssh, etc.)Network Servers (Web, FTP, ssh, etc.) Application ServersApplication Servers Database ServersDatabase Servers

Page 80: Advanced UNIX

Post ScannersPost Scanners

Port scanners are a useful toolsPort scanners are a useful tools Port scanners are software designed to Port scanners are software designed to

search a network host or hosts for open search a network host or hosts for open ports. ports.

This is often used by administrators to This is often used by administrators to check the security of their check the security of their system/networks and by crackers to system/networks and by crackers to detect attack pointsdetect attack points

Page 81: Advanced UNIX

Port ScannersPort Scanners

There are numerous port scanners There are numerous port scanners available today. Freeware, available today. Freeware, Shareware and Commercial of the Shareware and Commercial of the Shelf (COTS)Shelf (COTS)

Many Network/Security Many Network/Security Administrators use port scanners to Administrators use port scanners to detect unauthorized services running detect unauthorized services running on their networkon their network

Page 82: Advanced UNIX

Port ScannersPort Scanners

NmapNmap: ("Network Mapper") is an : ("Network Mapper") is an open source utility for network open source utility for network exploration or security auditing. It exploration or security auditing. It was designed to rapidly scan large was designed to rapidly scan large networks.networks.

FoundstoneFoundstone Vision Vision: Reports all open : Reports all open TCP and UDP ports and maps them to TCP and UDP ports and maps them to the owning process or application. the owning process or application.

Page 83: Advanced UNIX

Port ScannersPort Scanners

FoundstoneFoundstone FportFport: Identify unknown : Identify unknown open ports and their associated open ports and their associated applicationsapplications

FoundstoneFoundstone ScanlineScanline: Formerly : Formerly FScan. Command line port scannerFScan. Command line port scanner

FoundstoneFoundstone SuperScanSuperScan: Powerful TCP : Powerful TCP port scanner, pinger, resolverport scanner, pinger, resolver

……and many, many more…and many, many more…

Page 84: Advanced UNIX

nmapnmap

Version 3.70 (should be installed on Version 3.70 (should be installed on your class hard drive)your class hard drive)

Written by Fyodor: Written by Fyodor: [email protected]@dhp.com http://www.insecure.org/nmap/http://www.insecure.org/nmap/ To install on your FC6 system:To install on your FC6 system:

• yum install nmapyum install nmap Go ahead an do this now if you Go ahead an do this now if you

haven’t already…haven’t already…

Page 85: Advanced UNIX

Types of ScansTypes of Scans

TCP Scan TCP Scan – simple scan to detect open ports (aka listeners)– simple scan to detect open ports (aka listeners) ACK scanACK scan - can find packets allowed through a stateless - can find packets allowed through a stateless

packet filter. packet filter. FIN scanFIN scan - can determine if ports are open/closed, even if - can determine if ports are open/closed, even if

SYN packets are filtered. SYN packets are filtered. Protocol scanProtocol scan - determines what IP level protocols (TCP, UDP, - determines what IP level protocols (TCP, UDP,

GRE, etc.) are enabled. GRE, etc.) are enabled. Proxy scanProxy scan - a proxy (SOCKS or HTTP) is used to perform the - a proxy (SOCKS or HTTP) is used to perform the

scan. The target will see the proxy's IP address as the scan. The target will see the proxy's IP address as the source. This can also be done using some FTP servers. source. This can also be done using some FTP servers.

Idle ScanIdle Scan - Another method of scanning without revealing - Another method of scanning without revealing your IP address, taking advantage of the predictable ipid your IP address, taking advantage of the predictable ipid flaw. flaw.

ICMP scanICMP scan - determines if a host responds to ICMP requests, - determines if a host responds to ICMP requests, such as echo (ping), netmask, etc. such as echo (ping), netmask, etc.

Page 86: Advanced UNIX

Network ToolsNetwork Tools

There are many, many network tools There are many, many network tools that come with a standard Linux that come with a standard Linux installation.installation.

They can be used for network They can be used for network troubleshooting, for cause network troubleshooting, for cause network trouble and for detecting the same.trouble and for detecting the same.

Chapter 14 discusses a few of themChapter 14 discusses a few of them

Page 87: Advanced UNIX

Network ToolsNetwork Tools

The The netstatnetstat command is one such command is one such tooltool

It will show you the number of It will show you the number of tcp/udptcp/udp connections and the services connections and the services that are listening on your systemthat are listening on your system

Demo Demo netstatnetstat

Page 88: Advanced UNIX

Network ToolsNetwork Tools

One tool often overlooked by the book One tool often overlooked by the book is is lsoflsof

lsoflsof or "list open files" is one of the or "list open files" is one of the systems administrator's number one systems administrator's number one toolstools

You trace what processes are using You trace what processes are using which services as well as which files which services as well as which files are open and by which processesare open and by which processes

Demo Demo lsoflsof

Page 89: Advanced UNIX

Network ToolsNetwork Tools

Many “root kits” deployed by vandals Many “root kits” deployed by vandals replace the tools an SA would use to replace the tools an SA would use to detect the attackdetect the attack• ps, ls, netstat, lsof, etc.ps, ls, netstat, lsof, etc.

Always have original binaries and/or Always have original binaries and/or the tool source code availablethe tool source code available

See lecture I gave to Rose Cyber See lecture I gave to Rose Cyber Security Club:Security Club:• http://www.wildbill.org/rosehttp://www.wildbill.org/rose

Page 90: Advanced UNIX

Network ServicesNetwork Services

Each Network Service is a Point of Each Network Service is a Point of AttackAttack

Remove/Disable all unneeded Remove/Disable all unneeded servicesservices• /etc/services/etc/services – a text file that relates the – a text file that relates the

ports to the servicesports to the services• /etc/init.d/etc/init.d• chkconfigchkconfig

Page 91: Advanced UNIX

TCP WrappersTCP Wrappers

For the services that you need to have For the services that you need to have running consider using running consider using tcp_wrapperstcp_wrappers• Provides for added access controlProvides for added access control• /etc/host.allow/etc/host.allow• /etc/host.deny/etc/host.deny• Note: many services now hav wrapper support Note: many services now hav wrapper support

programmed into the source codeprogrammed into the source code The Super Daemon The Super Daemon xinetdxinetd now has tcp now has tcp

wrappers built in so any service using wrappers built in so any service using xinetd can take advantage of tcp wrappers xinetd can take advantage of tcp wrappers if it is not already encodedif it is not already encoded

Page 92: Advanced UNIX

TCP WrappersTCP Wrappers

Other services also use tcp wrappers Other services also use tcp wrappers such as “Very Secure FTP” such as “Very Secure FTP” • vsftpd FTP server vsftpd FTP server • Controlled in the vsftpd configuration Controlled in the vsftpd configuration

filefile Access to rsync can be controlled by Access to rsync can be controlled by

TCP Wrappers via xinetdTCP Wrappers via xinetd

Page 93: Advanced UNIX

TCP WrappersTCP Wrappers Uses two files to define the access to the Uses two files to define the access to the

servicesservices• /etc/hosts.allow/etc/hosts.allow• /etc/hosts.deny/etc/hosts.deny

You can create a deny-by-default to all You can create a deny-by-default to all services that use tcp wrappersservices that use tcp wrappers

Don’t be misled into thinking this can Don’t be misled into thinking this can secure you server 100%secure you server 100%• Understand that not all services can or do use Understand that not all services can or do use

tcp wrapperstcp wrappers• tcp wrappers is tcp wrappers is notnot a Firewall but an access a Firewall but an access

control processcontrol process

Page 94: Advanced UNIX

TCP WrappersTCP Wrappers

Good Example in the book Good Example in the book Demo: tcp wrappersDemo: tcp wrappers

• hosts.allowhosts.allow• hosts.denyhosts.deny

Page 95: Advanced UNIX

FirewallsFirewalls

Several types of Firewalls:Several types of Firewalls:• Packet filterPacket filter

Iptables – layer 2 networkIptables – layer 2 network

• Stateful filterStateful filter Cisco PIX – layer 3 and 4Cisco PIX – layer 3 and 4

• Stateful inspectionStateful inspection Checkpoint Firewall-1Checkpoint Firewall-1

• Application proxy Application proxy Sidewinder – layers 5 thru 7Sidewinder – layers 5 thru 7

• Good reference for firewalls:Good reference for firewalls:http://www.interhack.net/pubs/fwfaq/http://www.interhack.net/pubs/fwfaq/

Page 96: Advanced UNIX

Introduction to iptablesIntroduction to iptables

33rdrd generation firewall on Linux generation firewall on Linux Supports basic packet filtering as Supports basic packet filtering as

well as connection state trackingwell as connection state tracking For our needs for this course, we will For our needs for this course, we will

use simple/basic packet filteringuse simple/basic packet filtering

Page 97: Advanced UNIX

IptablesIptables

iptablesiptables is a filtering firewall is a filtering firewall Comes standard as part of LinuxComes standard as part of Linux

• Older versions of Linux have ipchainsOlder versions of Linux have ipchains FC comes with a relatively good FC comes with a relatively good

initial configurationinitial configuration Use chkconfig check to see if your Use chkconfig check to see if your

iptables is configured to start on bootiptables is configured to start on bootchkconfig --list iptableschkconfig --list iptables

Page 98: Advanced UNIX

IptablesIptables

If is not then enabled it via the If is not then enabled it via the following command:following command:

chkconfig –levels 235 iptables onchkconfig –levels 235 iptables on To start iptables enter:To start iptables enter:

/etc/init.d/iptables start/etc/init.d/iptables start

OrOr

service iptables startservice iptables start

Page 99: Advanced UNIX

Dropping vs Rejecting PacketsDropping vs Rejecting Packets

Rejecting packets COULD resource starve Rejecting packets COULD resource starve your systemyour system

Dropping packets could cause network Dropping packets could cause network diagnostic hell for the other end if you diagnostic hell for the other end if you don’t respond ‘nicely’don’t respond ‘nicely’

Dana’s Law: It is better to DROP packets Dana’s Law: It is better to DROP packets and buy your favorite network admin a and buy your favorite network admin a beer than to REJECT and have alarms go beer than to REJECT and have alarms go off at 2 in the morning during a DoS, off at 2 in the morning during a DoS, waking you up.waking you up.