• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/222

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

222 Cards in this Set

  • Front
  • Back

PATH Environment Variable

Unusually important environment variable. It set the path for a session, which is a colon-delimited list of directories in which Linux searches for executable programs when you type a program name.

USER or USERNAME Environment Variable

This is your current username. It's maintained by the system.

SHELL Environment Variable

This variable holds the path to the current command shell.

PWD Environment Variable

This is the present working directory. It is maintained by the system. Programs may use it to search for files when you don't provide a complete pathname.

HOSTNAME Environment Varialbe

This is the current TCP/IP hostname of the computer

HOME Environment Variable

This variable points to your home directory. Some programs use it to help them look for configuration files or as a default location in which to store files.

MAIL Environment Variable

This variable holds the location of the user's mail spool. It is usually /var/spool/mail/username

LANG Environment Variable

The system holds your current language, specified as a locale, using this variable

TZ Environment Variable

You can set this environment variable to you own time zone. The most common format is :filename, as in :/usr/share/zoneinfo/Europe/London


A second format, common on non-Linux systems, is std offset, where std is a three-character or longer time zone (such as EST) and offset is a time relative to UTC, with positive values representing offsets west of the Prime Meridian and negative values being east of it. for instans EST+5 specified US Eastern Time. This format is used when daylight saving time is not in effect


If daylight saving time is in effect, a variant on the preceding method is possible: std offset dst[offset],start[/time],end[time]. This specification adds the daylight saving time code as well encoded as start and end dates ( and optionally times). For instance EST+5EDT,M3.10.0/2,M11.3.0/2 specifies US Eastern time with daylight saving time encoded with dates for 2013

LD_LIBRARY_PATH Environment Variable

This variable indicated directories in which library files may be found.

PS1 environment Variable

This is the default prompt in bash

TERM Environment Variable

This is the name of the current terminal type

DISPLAY Environment Variable

This variable identifies the display used by X. It's usually :0.0 which means the first (numbered from 0) display on the computer. You can run multiple X sessions on one computer, in which case one gets a different DISPLAY number--for instance :0.0 for the first session and :1:0 for the second

EDITOR Environment Variable

Some programs launch the program pointed to by this environment variable when they need to call a text editor.

alias command

aliases are new names you can give to regular commands.


alias alias_name='commands'

/etc/profile

Global login file for configuring the shell

~/.bash_login


~/.profile


~/.bash_profile

User login file for configuring the shell

/etc/bashrc


/etc/bash.bashrc

Global non-login file for configuring the shell

~/.bashrc

User non-login file for configuring the shell

~/.bash_logout

user shell logout script -- script that runs when the user logs out

#!/bin/sh

Line that begins a shell script to identify (select) the shell (interpreter) that's used to run it.

executing a shell script

1) type name preceded by ./


2) source it:


-source my-script


-. my-script


*When you source a script it has access to environment variable in the calling shell (even if they have not been exported) . Ordinarily, only exported variable are available to scripts.


*Variables that are set in the script will be available in the calling shell


*Sourcing a script causes it to execute in the calling shell's language, whereas running a script normally causes it to use the shell language specified on the hashbang line

Script Parameters

Variables that are passed to a script are represented by a dollar sign($) followed by a number from 0 to 9--$0 stands for the name of the script, $1 is the first parameter, $2 is the second parameter, and so on

assigning a value to a shell variable from the output of a command

When assigning a value to a shell variable from the output of a command, that command should be enclosed in back-tick characters (`)

read shell command

used to read variable from standard input, as in read response to read input for subsequent access as $response

Shell conditions expression: if

The if keyword's conditions expression appears in brackets after the if command. -f file is true if file exists and is a regular file; -s file is true if file exists and has a size greater than 0; string1 == string2 is true if the two strings have the same values


if [ -s /tmp/tempstuff ]


then


echo "/tmp/tempstuff found; aborting!"


exit


fi


An alternative form for a conditional expression uses the test keyword rather than square brackets around the conditional:


if test -s /tmp/tempstuff


A commands return value can be tested by using the command as the condition


if [command]


then


additional-commands


fi


The else clause


if [conditiona-expression]


then


commands


else


other-commands


fi

Shell condition expression: &&

When conditionals are combined with &&, both sides of the operator must be true for the condition as a whole to be true.

Shell condition expression: ||

When conditionals are combined with ||, if either side of the operator is true, the condition as a whole is true

shell case command

case word in


pattern1) comman(s) ;;


pattern2) comman(s) ;;


...


esac

shell for loop

for d in `ls *.wav`; do


aplay $d


done

shell while loop

while [condition]


do


commands


done

shell until loop

?

shell seq command

This command generates a list of numbers starting from its first argument and continuing to its last one. For instance, typing seq 1 10 generates 10 lines, each with a number between 1 and 10


You can use a for loop beginning for x in `seq 1 10` to have the loop execute 10 times, with the value of $x incrementing with each iteration

shell functions

A function is a part of a script that performs a specific subtask and that can be called by name from other parts of the script


Functions are defined by placing parentheses after the functions name and enclosing the line that make up the function within curly braces:


myfn() {


commands


}

shell lists command

? See 105.1 Customize and use the shell environment

env shell command

displays all the environment variables


To set an environment variable for just one program you can do


env DISPLAY=seeker.example.com:0.0 nedit


This command launches the nedit program such that it attempts to use the :0.0 display on seeker.example.com rather than the default local display (or whatever the original DISPLAY environment variable specified)


-i or --ignore-environment begins with a completely empty environment


-u or --unset=VARNAME unsets the specified variable $VARNAME

export shell command

To make a variable available to programs you launch from the shell you use the export command.


HOSTNAME=carson.example.com


export HOSTNAME


or combine the two commands for brevity


export HOSTNAME=carson.example.com

setting a environment variable

You can set an environment variable via an equal-sign assignment operator:


HOSTNAME=carson.example.com

unset command

To delete an environment variable, use the unset command, which takes the name of an environment variable (without the loeaning $ symbol) as an option.

set command

This builtin is so complicated that it deserves its own section. set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables.


set


set [--abefhkmnptuvxBCEHPT] [-o option-name] [argument …] set [+abefhkmnptuvxBCEHPT] [+o option-name] [argument …]


If no options or arguments are supplied, set displays the names and values of all shell variables and functions, sorted according to the current locale, in a format that may be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In POSIX mode, only shell variables are listed.


https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html

skeleton directory

The default set of files copied by useradd for new user accounts


/etc/skel contains a handful of user configuration files such as .bashrc. You can add files (and even directories) to this directory, including user configuration files, a starting directory tree, a README file for new users, and anything else you like. These files are copies into users's directories and users are given ownership of thecompies

The mail program

The mail program is intended to be used on the command line to send or receive messages. The basic syntax for mail is a follows:


mail [-v] [-s subject] [-c cc-addr] [-b bcc-addr] to-addr


mail [-v] [-f [name] | -u user]


To read your email pass the -f options to the program, optionally followed by the name of the mail spool file. Alternatively, you can use the -u user option to read the mail of the specified user.

SQL insert command

For storing data


INSERT INTO table VALUES('lizard','green',6,'soft',10.00);


SQL update command

UPDATE table SET size=5 WHERE name='lizard'

SQL select command

SELECT * from table where condition=true

SQL delete command

DELETE FROM table WHERE condition=true

SQL GROUP BY

This command is used with mathematical operators such as SUM() to restrict the operation of the operator to the specified columns. See page 462


SELECT objects.name, objects.value, SUM(value) FROM objects, locations WHERE locations.name=objects.name GROUP BY value;

SQL ORDER BY

You can return data as an ordered list by specifying a field name after the ORDER BY keyword

SQL JOIN

A second way to combine data from multiple tables.


SELECT objects.name, objects.color, locations.location FROM objects JOIN locations WHERE objects.name=locations,name and objects.color='green';

SUID/SGID

The set user ID (SUID) are indicated by and s in the owner's execute bit positions in the permission string as in rxsr-xr-x


The set group ID (SGID) is indicated by an s in the group execute bit position in the permission string as in rwxr-sr-x


To set both SUID and SGID bits


chmod 6750 program


ls -l program


-rwsr-s---


also


chmod u+s sets SUID


chmod g+s sets SGID


---


find with the -perm mode option searches for files with the specified permission mode



To search for SUID and SGID files, you should pass a mode of +6000. The symbolic representation for the SUID and SGID bits is 6000, and the plus sign (+) tells find to locate any file with any of the specified bits set. (You could search for SUID files alone by passing +4000 or SGID alone by passing +2000.) You may also want to pass -type f, which restricts the search to regular files. (Directories use the SUID and SGID bits differently, as described in Chapter 4.) Thus, to search the entire computer for SUID and SGID programs, you type this:


# find / -perm +6000 -type f


The result is a list of files, one per line, that have either the SUID or the SGID bits set.


chown/chgrp command

The chgrp and chown commands can both change the group ownership of a file. The chgrp command takes a group name and a filename as parameters. The chown command normally changes a file's owner; but if you provide a group name preceded by a dot(.) or colon(:), it changes the group of a file.

Verify that the video card and monitor are supported by an X server

The X server itself includes the capacity to query the hardware and produce a configuration file. To do this, type XFree86 -configure (for XFree86) or Xord -configure (for X.org-X11) as root when no X server is running. The result should be a file called /root/XF86Config.new (for XFree86) or /root/xorg/conf.new (for X.org-X11). This file may not produce optimal results, but it's a starting point for manual modifications

/etc/X11/xorg.conf

The X server's configuration file is called xorg.conf.



Two "InputDevice" sections for keyboard and mouse


A "Module" section


A "Monitor" Section


A "Device" section for the videocard


A "Screen" Section that ties the videocard and the monitor. Sets the Default color depth


A "ServerLayout" section that links the Screen, the mouse (a InputDevice), and the keyboard (a InputDevice)

Setting the Resolution and Color Depth on X


Screen "Screen"


Identifier "Screen0"


Device "Videocard0"


Monitor "Monitor0"


DefaultDepth 24


SubSection "Display"


Depth 24


Modes "1920x1080" "1280x1024" "1024x768"


EndSubSection


SubSection "Display"


Depth 8


Modes "1024x768" "800x600" "640x480"


EndSubSection


EndSection


To choose between the Display subsections, you include a DefaultDepth line.

xdpyinfo

Sometimes it's helpful to know about the capabilities of your display, as it's managed by X. When you type xdpyinfo, the result is copious information about the current display, such as the X version number, the resolution and color depth of all the current displays.


For still more technical information, your can use the -ext extension option to xpdyinfo. the extension is the name of an X extension, which is a software module that provides extended capabilities to X. (The basic xpdyinfo command, without any options, lists all hte available extensions)

xwininfo

You can obtain detailed technical information about a specific window with the xwininfo command. In basic use, you type xwininfo, move the cursor over a window, and click. The result is a list of assorted data about the window you clicked.


Se page 281-282

Font server

Add to the Files sections of XF86Config or xorg.conf



Section "Files"


FontPath "unix:/7100"


FontPath "tcp/fount.pangaea.edu:7100"


EndSection


If your computer is configured to use a fond server, yo add or delete fonts to the font server's configuration file.


The font's server configurationfile /etc/X11/fs/config lists the font path using the catalogue keyword as a comma-delimited list:


catalogue = /usr/share/fonts/100dpi:unscaled, /usr/share/fonts/Type1,/usr/share/fonts/truetype,/usr/share/fonts/URW,/usr/share/fonts/Speedo,/usr/share/fonts100dpi


The final entry ends without a comma.


Once you've saved your changes, you must restart the font server:


/etc/init.d/xfs resart


At this point, you should restart X or "type xset fp rehash" to have X re-examine its font path, including the fonts delivered via the font server.

X GUI Logins

The X GUI Login employs a network login protocol, the X Display Manager Control Protocol (XDMCP).


Common XDMCP servers are: the X Display Manager (XDM), the KDE Display Manager (KDM), the GNOME Display Manager (GDM), the MDM Display Manager (MDM; a recursive acronym),and the Light Display Manager (LightDM)


-runlevel 3 stops X and the XDMCP server


-runlevel 5 starts X and the XDMCP server


use telinit to change runlevel


Permanently change default runlevel in /etc/inittab


id:5:initdefault:

XDM

XDM's main configuration file is /etc/X11/xdm/xdm-config


If you want to enable the computer to report to remote login requests from other X servers on the network or if you want to verify that the system is not so configured, you should pay attention to the line:


DisplayManager.requestPort: 0


This line tells XDM to not access a conventional server port. To activate XDM as a remote login server, you should change 0 to 177, the tradicional XDMCP port. You must then restart XDM.

Change the display manager greeting

In the X resources file (/etc/X11/xdm/Xresources) you can change the text displayed by XDM by altering the xlogin*greeting resource inthis file

KDM

Sometimes KDM users the XDM configuration files, other times they are stored in /etc/X11/kdm or /etc/kde/kdm and sometimes they are stored in /usr/lib/kde4/libexec


You should set the enable option to yes in the [Xdmcp] section of kdmrc if you want to enable remote logins.

GDM

GMD configuration files are usually stored in /etc/X11/gdm or /etc/gdm. In the past, the most important of these files was gdm.conf, and it had a format similar to kdmrc. More recent versions of GDM place this file elsewhere and give it a new fomat.


You should set the enable option to yes in the [xdmcp] section of gdm.conf if you want to enable remote logins.

xhost

xhost +zeus in apollo's terminal tells apollo to acces for display in its X server data that originates from zeus.



X may ignore network sessions for security reasons. To work around this change in gdm.conf DisallowTCP=true to DisallowTCP=false.


On newer versions of GDM, edit /etc/gdm/custom.conf,and add a line that reads DisallowTCP=false to the [security] sections


For XDM or KDM, they rely on settings in the Xservers file in /etc/X11/xdm. In a line that begins with :0 remove the string -nolisten tcp if it is there

Sticky Keys

When enabled, this options caused keyboard modifier keys (Ctrl, Alt, and Shift) to "stick" when pressed, affecting the next regular key to be pressed even after release of the sticky key. This can be useful for users who have difficulty pressing multiple keys simultaneously.

Mouse Keys

This option enables you to use the cursor keypad on your keyboard to emulate a mouse.

Bounce Keys

If a user tends to accidentally press a single key multiple times, the bounce keys option may be able to compensate for this tendency.

Slow Keys

When activated, this options requires a key to be pressed for longer than a specified period of time before it registers as a keypress. This feature is useful for individuals who tend to accidentally press keys.

Keyboard repeat rate

The repeat delay and rate can be set.

Mouse gestures

Gestures are similar to keyboard shortcuts but are for mice; they permit you to activate program options by moving your mouse in particular ways.

On Screen Keyboards

This is an application that displays the image of a keyboard. Using the mouse to press the keys on the keyboard works much like using a real keyboard. See The GNOME On-Screen Keyboard (GOK)


systemsettings or Configure Desktop fom main menu and then Application Appearance


See also Xfce accesible fro the Appearance item in its System Settings panel.

Can change fonts and font sizes

Adjusting Contrast

In KDE, you can set themes in the same System Settings preferences dialog box in which you set the fonts; you click the Colors icon in the left pane and select the theme you want to use.

Orca

This program is a creen reader that's been integrated into GNOME 2.16 and later

emacspeak

This program aims to enable those with visual impairments to use a Linux computer.

Braille Displays

A Braille display is a special type of computer monitor. Rather than display data visually, it creates a tactile display of the textual information in Braille.


To use a Braille display, special Linux software is required. The BRLTTY project provides a Linux daemon that redirect text-mode console output to a Braille Display.


Linux kernels since 2.6.26 include direct support for Braille displays

Screen Magnifier Tools

A screen magnifier application enlarges part of the screen -- typically the area immediately surrounding the mouse. One common magnifier is KMag, which is part of the KDE suite.

/etc/group

Every group has anywhere from no members to as many members as there are users on the computer. This file controls group membership.



project1:x:501:sally,sam,ellen,george


Group Name


Password


GID


User List

useradd command

This program is called adduser on some distributions.


basic syntax


useradd [-c comment] [-d home-dir] [-e expire-date] [-f inactive-days] [--g default-group] [-G group[,. . .]] [-m [-k skeleton-dir] | -M] [-p password] [-s shell] [-u UID [-o]] [-r] [-n] username


See page 333

passwd command

passwd [-k] [-l] [-u [-f]] [-d] [-S] username


See page 336

usermod command

This utility changes an existing account instead of creating a new one


-d parameter changes a user's home directory, but it doesn't move any files. Adding -m causes usermod to move the user's files to a new location


-l parameter changes the user's login name to the specified value


*may lock and unlock a user's password with the -L and -U options, respectively.

chage command

The chage command enables you to modify account settings relating to account expiration.


chage [-l] [-m mindays] [-M maxdays] [-d lastday] [-I inactivedays] [-E expiredate] [-W warndays] username

/etc/password file

sally:x:1029:100:Sally Jones:/home/sally:/bin/bash


Each field has a specific meaning as follows


Username


Password - most linux systems user a shadow password system in which the password is stored in /etc/password


UID


Primary GID


Comment


Home Directory


Default Shell

/etc/shadow

sally:$6$EmoFk:ZPkHpczVN2XRcMdyj8:15505:0:-1:7:-1:-1:


The meaning of each colon-delimited filed on this line is as follows:


Username


Password


Last Password Change


Days Until a Change is Allowed


Days Before a Change is Required


Days of Warning Before Password Expiratin


Days Between Expiration and Deactivation


Expiration Date


Special Flag


*For fields relating to day counts, a value of -1 or 99999 indicates that the relevant feature has been disabled.

userdel command

userdel command is used to do the job of removing a user's entries from /etc/passwd and, if the systems users shadow passwords, /etc/shadow . The userdel command takes just three parameters


-r or --remove parameter causes the system to remove all files from the user's mail spool and home directory, as well as the home directory


-f or --force parameter can force deletion of the account while a user is logged in in conjunctions with -r. This option also forces removal of the mail spool even if it's owned by another user and forces removal of the home directory even if another user uses the same home direcotry

How to find a users files

find / -uid 1029


or with -user

groupadd command

Linux provides the groupadd command to add a new group


groupadd [-g GID [-o]] [-r] [-f] groupname


See page 344

groupmod command

The groupmod command modified an existing group's settings.


groupmod [-g GID [-o]] [-n newgroupname] oldgroupname

groupdel command

Deleting groups is done via the groupdel command, which takes a single parameter: a group name.


Find files owned by a group

find / -gid 1003

The cron program

The corn program is a daemon that runs continuously looking for events that cause it to spring into action.


It "wakes up" once a minute, examines configuration files in /var/spool/cron and /etc/cron.d directories and the /etc/crontab file, and executes commands specified by these configuration files if the time matches the time listed in these files


cron jobs are unsuperviced so the shouldn't require user input.

/etc/crontab file

This file controls system cron jobs. This file normally begins with several lines that set environment variables, such as $PATH and $MAILTO. The file then contains several lines that resemble the following:


02 4 * * * root run-parts /etc/cron.daily



This line beings with five fields that specify the time. The fields are, in order, the minute (0-59), the hour (0-23), the day of the month (1-31), the month (1-12), and the day of the week (0-7; both 0 and 7 correspond to Sunday). For the month and day of the week values, you can use the first three letters of the name rather than the number of you like.



You can specify multiple values in several ways:


An asterisk (*) matches all possible values


A list separated by commas (such as 0,6,12,18) matches any of the specified values


Two values separated by a dash (-) indicate a range, inclusive of the end points.


A slash, when used in conjunction with some other multi-value option specified stepped values--a ranges in which some members are skipped. For instance */10 in the minute field indicates a job that's run every 10 minutes.



After the first five fields, entries continue with the account name to be used when execuring the program and the command to be run

/etc/cron.interval


or


/etc/cron.d/interval

Interval is a word associated with the run frequency which include monthly, daily, weekly, and hourly cron jobs

user cron jobs

To create a user cron job, you use the crontab utility


crontab [-u user] [-l | -e | -r] [file]


The -l option cause crontab to display the current crontab; -r removes the current crontab; and -e open an editor so that you can edit the current crontab


User crontab files are stored in /var/spool/cron, /var/spool/cron/tabs, or /var/spool/cron/crontabs.


Each file in this directory is named after the user under whose name it runs.

/etc/cron.allow

Allowed Users List -This file contains a list of users who should be permitted access to cron. If this file is present, only users whose names appear in the file may user cron; all others are denied access. If this file isn't present, anybody may use cron, assuming access isn't restricted by executable permissions or a disallowed-users list.


/etc/cron.deny

Disallowed Users List. This file contains a list of users who should be denied access to cron.

at command

program to run a single command at a specific point in the future on a one-time basis rather than an ongoing basis. Ordinarily, this command takes a single option: a time



example


at -f commands.sh noon


See page 373

/etc/at.allow

analogous to /etc/cron.allow

/etc/at.deny

analogous to /etc/cron.deny

atq

utility that lists pending at jobs

atrm

utility to remove an at job from the queue

/etc/localtime

Linux looks at the /etc/localtime file for information about its local time zone. It is not a plain text file. It is a link or a copy of a file in /usr/share/zoneinfo/*

/usr/share/zoneinfo

Directory containing the localtime files

/etc/timezone

Text mode time zone data -- looks like America/New_York

tzselect

program to change timezone

tzconfig

program to change timezone

locale

a locale is a way of specifying the computer's (or user's) language, country, and related information for purposes of customizing displays. A single locale takes the following form:


[language[_territory][.codeset][@modifier]]



language can be en (english), fr (French)


territory can be US (United States), FR (France)


codeset can be ASCII, UTF-8


modifier is a locale-specific code that modifies how it works



the locale command without any arguments shows how the several local environment variables are set



"locale -a" identifies which locales are available to a system at the moment

ISO-8859

ISO-8859 was an early attempt to extend ASCII; it employs an eight bit to extend ASCII by 128 characters, giving room for the characters needed by a small number of non-Roman alphabets. ISO-8859 is broken down into many substandards, each of which handles on language or small group of languages. ISO-8859-1 covers Western European languages and ISO-8859-5 provides Cyrillic support.

UTF-8

The latest language codeset is the 8-bit Unicode Transformation Format. UTF-8 starts with ASCII, but it extends it by supporting variable byte extensions so that a single character can take anywhere from one to four bytes to be encoded. This provides the ability to encode text in any language supported by Unicode, which is a character set designed to support as many languages as possible. The bit advantage of UTF-8 over ISO-8859 is that there's no need to specify a substandard; UTF-8 handles all of its writing systems automatically.

LC_ALL environment variable

environment variable that chan change locale


LC_ALL=en_GM.UTF-8

LANG environment variable

?


LANG=C

When you set LANG to C, programs that see this environment variable display output without passing it through locale translations.

Change the encoding of a file

iconv -f encoding -t encoding [inputfile]. . .


If you omit the target encoding, iconv uses your current locale for guidance

LC_*

use locale without any arguments to see how these variables are set

date command

by itself results in the time that includes a standard three letter time zone code.



Manually Setting the Time



date [-u | --utc | --universal] [MMDDhhmm[[CC]YY][.SS]]


pool.ntp.org

public NTP server pool

/etc/ntp.conf

This file contains various NTP options, but the most important are the server lines:


server clock.example.com


server time.pangaea.edu


server time.luna.edu


Each of these points to a single NTP server. When the local NTP daemon starts up, it contacts all the servers specified in the file, measures the accuracy agains each other, and settles on one as its primary time source.


Typically, you list about three upstream server for a system that;s to serve many other computers.

ntpd

The NTP daemon. If started with its -g option enables it to perform a one-time clock setting to a value that's wildly divergent from the current time (Ordinarily, ntpd exits if the time server's time differs from the local time by more than a few minutes)

hwclock

hwclock utility enables you to set the hardware clock.


to view the hardware clock, pass the -r or --show option. The time is displayed in local time, even if the hardware clock is set to UTC.


To set the hardware clock to a date you specify, you ned two options: --set and --date=newdate. The newdate is in the date format that the date programs accepts.


To set the hardware Clock based on the Software Clock use --systohc


To set the software clock based on the Hardware clock use --hctosys


You can tell Linux to treat the hardware clock as storing UTC by using the --utc option or to treat it as holding local time by using --localtime option. The default is whichever was last used when the hardware clock was set.


ntpdate command

This program is part of the NTP suite, and it performs a one-time clock setting. To use it, type the command name followed by the hostname or IP address of an NTP server:


ntpdate clock.example.com


ntpdate, however, has been deprecated

syslogd

a daemon to handle log maintenance in a unified way. The daemon runs in the background and accepts date delivered from servers and other programs that are configured to use the log daemon. The daemon can then use information provided by the server to classify the message and direct it to the appropriate log file. This configuration enables you to consolidate messages from various servers in a handful of standard log files, which can be much easier to use and manage that potentially dozens of log files from the various servers running on the system

klogd

a daemon that manages logging of kernel messages

/etc/syslog.conf

The syslogd configuration file.



The format of /etc/syslog.conf is as follows:


Comments are denoted by a hash mark (#)


Non comment lines take the following form


facility.priority action



The facility is a code word for the type of program or tool that generated the message to be logged; the priority is a code word for the importance of this message; and the action is a file, remote computer, or other location that's to accept the message


An asterisk (*) refers to al facilities. More than one facility can be specified in one selector by separating the facilities with commas (,).



Multiple selectors for a single action can be specified by separating the selectors with a semicolon(;)



Most commonly an action is a filename, typically in the /var/log directory tree. Other possible logging locations include a device filename for a console (such as /dev/console) to display data on the screen, a remote machine name preceded by an at sign (@) to log data to the specified system, and a list of usernames of individuals who should see the message if they're logged on. For the last of these options, and asterisk (*) means all logged-in users.

Valid syslog.conf facility

auth, authpriv, cron, daemon, kern, lpr, mail, mark, news, security, syslog, user, uucp, and local0 through local7


security facility is identical to auth, but auth is the preferred name


mark facility is reserved for internal use


An asterisk (*) refers to al facilities. More than one facility can be specified in one selector by separating the facilities with commas (,).

Valid syslog.conf priority codes

debug, info, notice, warning, warn, error, err, crit, alert, emerg, and panic


The warning priority is identical to warn


The error priority is identical to err


the emerge priority is identical to panic


The error, warn, and panic priority names are deprecated


These priorities represent ascending levels of importance


The debug level logs the most information


the emerg priority logs the most important messages, which indicate very serious problemns


When a program sends a message to the system logger, it includes a priority code; the logger logs the message to a file if you've configure it to log messages of that level or higher. alert priority messages will log messages that are classified as alert or emerg.


An exception to this rule is if you precede the priority code by an equal sign (=), as =crit, which describes what to do with messages of crit priority only. An exclamation mark (!) reverses the meaning of a match. A priority of * refers to all priorities

logger command

logger is for manually creating a log entry or have a script do so.


logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message . . .]


See page 352


logger shutting down for system maintenance


will result in an entry, probably in /var/log/messages


sendmail

The sendmail programs was for many years the dominant email server package on the internet. It's very powerful, but it's also difficult to configure because its configuration file formats are rather arcane. In recent years it's lost some of its dominance.

postfix

Postfix was designed as a modular replacement for sendmail--rather than a single programs that does everything (as sendmail is designed), Postfix uses multiple programs, each of which handles its own specific small task. This designs improves security in theory. Postfix tends to be easier to configure than sendmail. It's the default email server on many Linux distributions.

exim

Exim is a monolithic server, like sendmail. It has a much simpler configuration file format as so is easier to configure. A few Linux distributions use Exim as the default email server.

qmail

qmail is a modular server with security as a major design goal. qmail is easier to configure than sendmail. It's not the standard email server in any Linux distribution because its license is a bit strange and complicates qmail distribution with Linux.

mailq

The mailq is the main tool to help in email queue management. This program was originally part of the sendmail package, but Postfix, Exim, qmail, and other Linux SMTP servers have all implemented compatible commands.


The basic command, without any options, shows the contents of the e-mail queue on all systems


In most cases, typing mailq is equivalent to typing sendmail -bp


to clear the mail queue typing sendmail -q will do the job with most SMTP servers. "postqueue" is the equivalent in Postfix and "runq" in Exim.

email alises

email aliases enable one address to stand in for another one.

/etc/aliases or


/etc/mail/aliases

The alises file format:


Comment lines begin with hash marks (#)


other lines take the following form:


name addr1[,addr2[,...]]



The name that leads the line is a local name such as postmaster. Each address (addr1, addr2, and so on) can be the name of a local account to which the messages are forwarded, the name of the local file in which messages are stored (denoted by a leading slash), a command through which messages are piped (denoted by a leading vertical bar character), the name of a file whose contents are treated as a series of addresses (denoted by a leading :include: string), or a full email address (such as fred@example.com)

newaliases command

Some mail servers, including sendmail, Postfix, and qmail, require you to compile /etc/aliases into a binary file that can be processed more quickly. To do so, use the newaliases command



Exim has a newaliases command for compatibility with sendmail, but is doesn't do anything by default

~/.forward

The ~/.forward should contain a new address -- either a username on the current computer or an entire email address on another computer.


Email for that user is sent to the address in the file

lpr

Users submit print jobs by using a program called lpr. lpr sends the print job into a specified queue. This queue corresponds to a directory on the hard disk, typically in a subdirectory of the /var/spool/cups directory



Specify a Queue name -- The -Pqueuename option enables you to specify a print queue. If you omit this options, the default printer is used.


Specifying the -r options causes lpr to delete the original file after printing it.


The -h option suppresses the banner for a single print job.


The -m username options causes lpd to send email to username when print jobs is complete


The -# number as in -# 3 specifies the number of copies of a print jobs (in the example 3)

/etc/cups

directories that sores various CUPS configuration files

/etc/cups/printers.conf

File to add or delete printers

/etc/cups/ppd subdirectory

Stores PostScript Printer Definition files

/etc/cups/cupsd.conf

controls acces to the printer server in a format similar to the Apache Web Server configuration file format.

http://localhost:631

address of the CUPS daemon using a web browser

uri for a Unix or Linux server that uses the old LPD protocol

lpd://hostname/queue

uri for Windows printer

smb://username:password@SERVER/SHARE

lpq utility

lpq displays information about the print queue--how many files it contains, how large they are, who their owners are, etc.

lprm command

The lprm command removes one or more jobs from the print queue


If lprm is used with a number, that number is understood to be the job ID (as shown in lpq) of the job that's to be deleted


If a user runs the BSD or CUPS lprm and passes a dash (-) to the program, it removes all the jobs belonging to the user. (root may remove anybody's print jobs; ordinary users may only remove their own jobs from the queue)

cupsenable

enable a queue

cupsdisable

disable a queue

lpmove

move a job from one queue to another

IP protocol

The Internet Protocol (IP) is the core protocol in TCP/IP. IP is an internet layer (aka a network layer or layer 2) protocol. IP provides a "best effort" method for transferring packets between computers--that is, the packets aren't guaranteed to reach their destination. Packets may also arrive out of order or corrupted. Other components of the TCP/IP stack must deal with these issues and have their own ways of doing so. IP is also the portion of TCP/IP with which IP addressed are associated.

ICMP protocol

The Internet Control Message Protocol (ICMP) is a simple protocol for communicating data. ICMP is most often used to send error messages between computers-- for instance, to signal that a requested service isn't available.


this is often done by modifying an IP packet and returning it to its sender, which means that ICP is technically and internet layer protocol, although it relies upon IP. Inmost cases, you won't use programs that generate ICMP packets on demand; they're created behind the scenes as you use other protocols. One exception is the ping program.

UDP protocol

The User Datagram Protocol (UDP) is the simplest of the common transport layer (aka layer 3) TCP/IP protocols. It doesn't provide sophisticated procedures to correct for out of order packets, guarantee delivery, or otherwise improve the limitations of IP. This fact can be a problem, but it can also mean that UDP can be faster than more sophisticated tools that provide such improvements to IP. Common application layer protocols that are built atop UDP include the Domain Name Service (DNS)m the Network File System (NFS), and many streaming media protocols.

TCP protocol

The Transmission Control Protocol (TCP) may be the most widely used transport layer protocol in the TCP/IP stack. Unlike UDP, TCP creates full connections with error checking and correction as well as other features. These features simplify the creation of network protocols that must exchange large amounts of data, but the features come at a cost: TCP imposes a small performance penalty. Most of the applications layer protocols with which you may already be familiar, including the Simple Mail Transfer Protocol (SMTP), the Hypertext Transfer Protocol (HTTP), and the File Transfer Protocol (FTP), are built atop TCP.

IPv4 vs IPv6

IPv4 supports a theoretical maximum of about 4 billion addresses (2^32) (4 bytes). IPv6 raises the number of addresses to 2^128(16 bytes).



IPv6 makes multicasting--the simultaneous transmission of data from one computer to multiple recipients--part of the basic IP specification, compared to an optional (albeit commonly implemented) part of IPv4.



IPv6 includes a new feature, known as stateless address auto configuration (SLAAC), which simplifies initial network setup. This feature is similar in some way to the Dynamic Host Configuration Protocol (DHCP) that's commonly used on IPv4. (DHCP can also be used on IPv6; which works best depends on the local network's configuration)



IPv6 originated the Internet Protocol Security (IPsec) tools, which can improve the security of Internet connections. IPsec has since been back ported to IPv4



IPv6 has streamlined some data structures, enabling quicker processing by routers.

ifconfig command

ifconfig ethn, where n is the number of the interface (0 for the first card, 1 for the second, and so on)


The HWaddr shows the Media Access Control (MAC) address.

IPv4 addresses

IPv4 addresses are usually expressed as four base 10 numbers (0-255) separated by periods, as in 172.30.9.102



This address is broken into two components: a network address and a computer address. The network address identifies a block of IP addresses that are used by one physical network, and the computer address identifies one computer within that network.



The network mask (also known as the subnet mask or netmask) is a number that identifies the portion of the IP address that's a network address and the part that's a computer address. It's helpful to think of this in binary (base 2) because the netmask uses binary 1 values to represent the network portion of an address and binary 0 values to represent the computer address. The network portion ordinarily leans the computer portion. Expressed in base 10, these addresses usually consist f 255 or 0 values, 255 being a network byte and 0 being a computer byte.



Another way of expressing a netmask is a single number representing the number of network bits in the address. This number usually follows the IP address and a slash. For instance 172.30.9.102/16 is equivalent to 172.30.9.102 with a netmask of 255.255.0.0--the last number shows the network portion to be two solid 8bit bytes and hence is 16 bits. The longer notation showing all 4 bytes of the netmask is referred to as dotted quad notation.



On modern IPv4 network, netmasks are often described in Classess Inter Domain Routing (CIDR) form. Such network masks can be broken at any bit boundary for any address

IPv6 address

IPv6 addresses consist of eight groups of four digit hexadecimal numbers separated by colons, ad in fed1:-db8:85a3:08d3:1319:8a2e:0370:7334. If one or more groups of four digits is 0000, that group or those groups may be omitted leaving two colons. Only one such group of zeroes an be compressed in this way, because if you removed two groups, there would be no way of telling how may sets of zeroes would have to be replace in each group.

IPv4 network classes and private network ranges

Class A


Address Range 1.0.0.0-127.255.255.255


Reserved private addresses 10.0.0.0-10.255.255.255



Class B


Address Range 128.0.0.0-191.255.255.255


Reserved private addresses 172.16.0.0-172.31.255.255



Class C


Address Range 192.0.0.0-223.255.255.255


Reserved private addresses 192.168.0.0-192.168.255.255



Class D


Address Range 224.0.0.0-239.255.255.255


Reserved private addresses none



Class E


Address Range 240.0.0.0-239.255.255.255


Reserved private addresses none



Classes A, B, and C are for general networking use. Class D addressed are reserved for multicasting--sending data to multiple computers simultaneously. Class E addresses are reserved for future use. There are a few special cases within most ranges. For instance, the 127.x.y.z addressees are reserved for use as loopback (aka localhost) devices -- these addresses refer to the computer on which the address is entered. Addresses in which all the machine bits are set to 1 refer to the network block itself--they are used for broadcasts.

IPv6 private addresses

IPv6 site local addresses may be routed within a site but not off site. They being with the hexadecimal number fec, fed, fee, or fef. Link local addresses are restricted to a single network segment; they shouldn't be routed at all. These addresses begin with the hexadecimal number fe8, fe9, fea, or feb.

hostnames

hostnames are composed of two parts: machine names and domain nammes



Top Level Domains TLDs such as .com, .edu, .org. TLD names appear at the end of an Internet Address.



Four TLDs--.example, .invalid, .localhost, .test-- are reserved for guaranteeing that you don't accidentally give your computer a name that legitimately belongs to somebody else.



Three second-level domains--.example.com, .example.net, and example.org--are also reserved and may be safely used.


nslookup command

This program performs Domain Name System (DNS) lookups (on individual computers by default) and returns the results. It also sports an interactive mode in which you can perform a series of queries. This program is officially deprecated. Thus, you should get in the habit of using host or dig instead of nslookup.

host command

This programs serves as a replacement for the simpler uses of nslookup, but it lacks an interactive mode, and of course many details of its operation differ. In the simplest case, you can type "host target.name", where target.name is the hostname or IP address you want to look up.

dig command

This program performs more complex DNS lookups than host. Although you can use it to find the IP address for a single hostname (or hostname for a single IP address), it's more flexible than host.

whois command

You can look up information on a domain as a whole with this command. For instance, typing whois sybex.com reveals who owns the sybex.com domain, who to contact in case of problems, and so on. You may want to use this command with -H, which omits the lengthy legal disclaimers that many domain registries insist on delivering along with whois information.

/etc/hosts

This file holds mappings of IP addresses to hostnames, on a one line per mapping basis. Each mapping includes at least one name, and sometimes more:



127.0.0.1 localhost


192.168.7.23 apollo.luna.edu apollo

/etc/nsswitch.conf

Configures Name Service Switch (NSS) service. The hosts line lists the order of the files and dns options, which stands for /etc/hosts and DNS, respectively (in what order Linux normally performs lookups)


hosts: files dns


Reverse the order of the files and dns options to have the system consult DNS before it consults /etc/hosts



/etc/nsswitch.conf file supports many more options. For instance, you can perform name resolution using Windows NetBIOS calls or a Lightweight Directory Access Protocol (LDPA) server by adding the appropriate options to the hosts line, along with the necessary support software. The passwd, shadow, and group lines control how Linux authenticates users and manages groups.

/etc/networks

works much like /etc/hosts but it applies to network addresses



loopback 127.0.0.0


mynet 192.168.7.0



This example sets up two linkages: the loopback name to the 127.0.0.0/8 network and mynet for the 192.168.7.0/24 network.



It's seldom necessary to edit this file.

Port 20

Exam: yes


TCP or UDP: TCP


Purpose: File Transfer Protocol (FTP) data

Port 21

Exam: yes


TCP or UDP: TCP


Purpose: File Transfer Protocol (FTP)

Port 22

Exam: yes


TCP or UDP: TCP


Purpose: Secure Shell (SSH)

Port 23

Exam: yes


TCP or UDP: TCP


Purpose: Telnet

Port 25

Exam: yes


TCP or UDP: TCP


Purpose: Simple Mail Transfer Protocol (SMTP)

Port 53

Exam: yes


TCP or UDP: TCP and UDP


Purpose: Domain Name System (DNS)

Port 67

Exam: no


TCP or UDP: UDP


Purpose: Dynamic Host Configuration Protocol (DHCP)

Port 80

Exam: yes


TCP or UDP: TCP


Purpose: Hypertext Transfoer Protocol (HTTP)

Port 110

Exam: no


TCP or UDP: TCP


Purpose: Post Office Protocol version 3 (POP-3)

Port 111

Exam: no


TCP or UDP: TCP and UDP


Purpose: Portmapper

Port 113

Exam: no


TCP or UDP: TCP


Purpose: auth/ident

Port 119

Exam: yes


TCP or UDP: TCP


Purpose: Network News Transfer Protocl (NNTP)

Port 139

Exam: yes


TCP or UDP: TCP


Purpose: NetBIOS Session (windows File Sharing)

Port 143

Exam: yes


TCP or UDP: TCP


Purpose: Interactive Mail Access Protocol (IMAP)

Port 161

Exam: yes


TCP or UDP: UDP


Purpose: Simple Network Management Protocol (SNMP)

Port 177

Exam: no


TCP or UDP: UDP


Purpose: XDMCP

Port 389

Exam: no


TCP or UDP: TCP


Purpose: LDAP

Port 443

Exam: yes


TCP or UDP: TCP


Purpose: HTTP over SSL (HTTPS)

Port 445

Exam: no


TCP or UDP: TCP


Purpose: Microsoft Directory Services (DS)

Port 465

Exam: yes


TCP or UDP: TCP


Purpose: SMTP over SSL; or URL Rendezvous Directory (URD)

Port 631

Exam: no


TCP or UDP: TCP


Purpose: Internet Printing Protocol (IPP)

Port 993

Exam: yes


TCP or UDP: TCP


Purpose: IMAP over SSL

Port 995

Exam: yes


TCP or UDP: TCP


Purpose: POP-3 over SSL

Port 5900+

Exam: no


TCP or UDP: TCP


Purpose: Remote Framebuffer (RFB)

Port 6000-6007

Exam: no


TCP or UDP: TCP


Purpose: The X Window System

/etc/services

The /etc/services file maps port numbers to names of servers. This file consists of lines that being with a name and end with a port number, including the type of protocol it uses (TCP or UDP):



ssh 22/tcp # SSH Remote Login Protocol

/etc/resolv.conf

In order for Linux to use DNS to translate between IP addresses and hostnames, you must specify at least one DNS server in the /etc/resolv.conf. Precede the IP address of the DNS server by the keyword nameserver as in nameserever 192.168.29.1

ifconfig program

This program is critically important for setting both the IP address and netmask. This program can also display current settings. BAsic use of ifconfig to bing up a network interface resembles the following:


ifconfig interface up addr netmask mask

route command

route {add | del| [-net | -host] target [netmask nm] [gw gw] [reject] [[dev] interface]



You must enable routing if you're setting up a router. Ordinarily, a Linux system won't forward packets it receives from one system that are directed to another system. If Linux is to act as a router, though, it must accept these packets and send them on to the destination ( or at least to an appropriate gateway). To enable this feature, you must modify a key file in the /proc filesystem:


$ echo "1" > /proc/sys/net/ipv4/ip_forward


This command enables ip forwarding. Permanently setting this options requires modifying a configuration file. Some distributions set it in /etc/sysctl.conf:


net.ipv4.ip_forward = 1



to set up a route for traffic beyond your current network.


route add default gw 192.168.2.1



To use route for diagnostic purposes, you might try the following:


route -n


The -n options causes it to not attempt to find the hostnames associated with IP addresses. Although hostnames are often useful, this lookup can be slow or fail altogether if your DNS configuration is broken, so using -n with route is often necessary.

ifup/ifdown commands

These commands combine the functions of several other network commands, most notably ifconfig and route. In their simplest forms, they bring interfaces up or shut them down based on information in whatever files your distribution uses to store network configuration data:


ifup eth0


ifdown eth0

hostname command

Tool for setting your hostname locally.


hostname nessus.example.com

/etc/hostname

file for setting your hostname permanently

ping command

The most basic network test, which sends a simple ICMP packet to the system you name (via IP address or hostname) and waits for a reply. In Linux, ping continues sending packets once every second or so until you interrupt it with a Ctrl-C keystroke. You can specify a limited number of tests via the -c num option.

traceroute command

A step up from ping. sends a series of three test packets to each computer between your system and a specified target system.



The -n option to this command tells it to display target computers' IP addresses rather than their hostnames. This can speed up the process a bit, particularly if you're having DNS problems.



Using traceroute you can localize problems in network connectivity

tracepath command

tracepath is an alternative to traceroute. In basic operation, it's similar, although it produces one line of output for each test packet so yields longer outputs than traceroute. There are also fewer tracepath options than there are traceroute options.

netstat command

Another useful diagnostic tool is netstat. This is something of a Swiss Army knife of network tools because it can be used in place of several others, depending on the parameters it’s passed. It can also return information that’s not easily obtained in other ways. Examples include the following:


Interface Information Pass netstat the --interface or -i parameter to obtain information about your network interfaces similar to what ifconfig returns. (Some versions of netstat return information in the same format, but others display the information differently.)


Routing Information You can use the --route or -r parameter to obtain a routing table listing similar to what the route command displays.


Masquerade Information Pass netstat the --masquerade or -M parameter to obtain information about connections mediated by Linux’s NAT features, which often go by the name IP masquerading. NAT enables a Linux router to “hide” a network behind a single IP address. This can be a good way to stretch limited IPv4 addresses.


Program Use Some versions of netstat support the --program (or -p) parameter, which attempts to provide information about the programs that are using network connections. This attempt isn’t always successful, but it often is, so you can see what programs are making outside connections.


Open Ports When used with various other parameters, or without any parameters at all,netstat returns information about open ports and the systems to which they connect.


All Connections The --all or -a option is used in conjunction with others. It causesnetstat to display information about the ports that server programs open to listen for network connections, in addition to already-open connections. This use of netstat is described in more detail in Chapter 10, “Securing Your System.”


Keep in mind that netstat is a very powerful tool, and its options and output aren’t entirely consistent from one distribution to another. You may want to peruse its man page and experiment with it to learn what it can do.



For spotting unnecessary servers, you can use netstat with its -a and -p options


When you use the -p option to obtain the name and PID of the process using a port, thenetstat output is wider than 80 columns. You may want to open an extra-wide terminal window to handle this output or redirect it to a file that you can study in a text editor capable of displaying more than 80 columns. To quickly spot servers listening for connections, type netstat -lp rather than netstat -ap. The result will show all servers that are listening for connections, omitting client connections and specific server instances that are already connected to clients.

telnet command

This program and protocol is mainly a remote login tool; type the program name followed by the name of a remote system to receive a login prompt on that system:



You can use Telnet to debug network protocols; if you give it a port number after the remote hostname, the telnet program connects to that port, enabling you to interact with the server:

ftp command

Sometimes the File Transfer Protocol (FTP) can be a useful diagnostic tool, as well. This program, as its name suggests, enables you to transfer files between systems. To use it, type the program name followed by the FTP server’s name. You’ll then see a login prompt and be able to issue FTP commands:



The basic ftpclient displays a file size, transfer time, and transfer rate (1e+03 Kbytes/sec—in other words, 1 × 103 KiB/s, or 1000 KiB/s). This can be a useful way to test your network transfer speed, although you’ll get more reliable results with files that are several hundred kilobytes or larger in size. In addition to get, which retrieves files, you can issue commands such as put to upload a file; ls or dir to display the remote system’s directory contents; cd to change directories on the remote system; delete to remove a file; and quit or exit to exit from the program. You can use the help or ? command to see a list of available ftp commands.

/etc/inetd.d

The inetd package was once the standard super server in Linux, and it’s still used on some systems.


You control servers that launch via inetd through the /etc/inetd.conf file or files in/etc/inetd.d. The /etc/inetd.conf file consists of a series of lines, one for each server. A typical line resembles the following:


ftp stream tcp nowait root /usr/sbin/tcpd /usr/sbin/in.ftpd -l


Instead of using a single monolithic /etc/inetd.conf file, recent versions of inetd enable you to split the configuration into several files in the /etc/inetd.d directory. Doing so enables you to easily add or delete server configurations by adding or deleting their configuration files. For brevity, the following paragraphs refer only to /etc/inetd.conf, but the description applies to files in /etc/inetd.d, as well.


Each line in /etc/inetd.conf consists of several fields separated by one or more spaces. The meanings of these fields are as follows:


Service Name The first field (ftp in the preceding example) is the name of the service as it appears in the /etc/services file.


Socket Type The socket type entry tells the system what type of connection to expect—a reliable two-way connection (stream), a less reliable connection with less overhead (dgram), a low-level connection to the network (raw), or various others. The differences between these types are highly technical; your main concern in editing this entry should be to correctly type the value specified by the server’s documentation.


Protocol This is the TCP/IP transport-layer protocol used, usually tcp or udp.


Wait/No Wait For dgram socket types, this entry specifies whether the server connects to its client and frees the socket (nowait) or processes all its packets and then times out (wait). Servers that use other socket types should specify nowait in this field.


User This is the username used to run the server. The root and nobody users are common choices, but others are possible as well. As a general rule, you should run servers with a low-privilege user whenever possible as a security precaution. Some servers require root access, though. Consult the server’s documentation for details.


Server Name This is the filename of the server. In the preceding example, the server is specified as /usr/sbin/tcpd, which is the TCP Wrappers binary. As described shortly in “Controlling Access via TCP Wrappers,” this program is an important security tool and should usually be included as the means of launching programs via inetd.


Parameters Everything after the server name consists of parameters that are passed to the server. If you use TCP Wrappers, you pass the name of the true target server (such as/usr/sbin/in.ftpd) in this field, along with its parameters.


The hash mark (#) is a comment symbol for /etc/inetd.conf. Therefore, if a server is running via inetd and you want to disable it, you can place a hash mark at the start of the line. If you want to add a server to inetd.conf, you need to create an entry for it. Most servers that can be run from inetd include sample entries in their documentation. Many distributions ship withinetd.conf files that include entries for common servers as well, although many of them are commented out; remove the hash mark at the start of the line to activate the server.


After modifying inetd.conf, you must restart the inetd super server. You can generally restart it by using your startup script system, as described in Chapter 5, “Booting Linux and Editing Files.” On most computers, typing something similar to the following should work:


# /etc/init.d/inetd restart


Alternatively, you can tell inetd to reload its configuration by using a reload parameter rather than restart. The restart option shuts down the server and then starts it again. When you use reload, the server never stops running; it just rereads the configuration file and implements any changes. As a practical matter, the two are similar. Using restart is more likely to correctly implement changes, but it’s also more likely to disrupt existing connections.


Instead of using the SysV startup scripts, you can use kill or killall (described in Chapter 2, “Managing Software”) to pass the SIGHUP signal to inetd. This signal causes many servers, including inetd, to reload their configuration files. For instance, you can type kill -HUP pid if you know the process ID (PID) of inetd, or you can type killall -HUP inetd to have all instances of inetd reload their configuration files. (Ordinarily, only one instance of inetdruns on a system.) In practice, this should work very much like the reload option to the SysV startup script—in fact, such scripts often use this technique to implement this option.

Controlling Access via TCP Wrappers

The TCP Wrappers package provides a program known as tcpd. Instead of having inetd call a server directly, inetd calls tcpd, which does two things: It checks whether a client is authorized to access the server, and if the client has this authorization, tcpd calls the server program.


TCP Wrappers is configured through two files: /etc/hosts.allow and /etc/hosts.deny. The first of these specifies computers that are allowed access to the system in a particular way, the implication being that systems not listed are not permitted access. By contrast, hosts.denylists computers that are not allowed access; all others are granted access to the system. If a computer is listed in both files, hosts.allow takes precedence.


Both files use the same basic format. The files consist of lines of the following form:


daemon-list : client-list


The daemon-list is a list of servers, using the names for the servers that appear in/etc/services. Wildcards are also available, such as ALL for all servers.


The client-list is a list of computers to be granted or denied access to the specified daemons. You can specify computers by name or by IP address, and you can specify a network by using a leading or trailing dot (.) when identifying networks by name or IP address block, respectively. For instance, .luna.edu blocks all computers in the luna.edudomain, and 192.168.7. blocks all computers in the 192.168.7.0/24 network. You can also use wildcards in the client-list, such as ALL (all computers). EXCEPT creates an exception. For instance, when placed in hosts.deny, 192.168.7. EXCEPT 192.168.7.105 blocks all computers in the 192.168.7.0/24 network except for 192.168.7.105.


The man pages for hosts.allow and hosts.deny (they’re actually the same document) provide additional information about more advanced features. You should consult them as you build TCP Wrappers rules.



Remember that not all servers are protected by TCP Wrappers. Normally, only those servers that inetd runs via tcpd are so protected. Such servers often include, but are not limited to, Telnet, FTP, TFTP, rlogin, finger, POP, and IMAP servers. A few servers can independently parse the TCP Wrappers configuration files, though; consult the server’s documentation if in doubt.

/etc/xinetd.conf

The xinetd program is an extended super server. It provides the functionality of inetd plus security options that are similar to those of TCP Wrappers. Modern versions of Fedora, Mandriva, Red Hat, SUSE, and a few other distributions use xinetd by default. Other distributions may use it in the future. If you like, you can replace inetd with xinetd on any distribution.


The /etc/xinetd.conf file controls xinetd. On distributions that use xinetd by default, this file contains only global default options and a directive to include files stored in/etc/xinetd.d. Each server that should run via xinetd then installs a file in /etc/xinetd.dwith its own configuration options.


Whether the entry for a server goes in /etc/xinetd.conf or a file in /etc/xinetd.d, it contains information similar to that in the inetd.conf file. The xinetd configuration file, though, spreads the information across multiple lines and labels it more explicitly. Listing 10.1 shows an example that’s equivalent to the earlier inetd.conf entry from “Setting Up inetd.” This entry provides precisely the same information as the inetd.conf entry except that it doesn’t include a reference to /usr/sbin/tcpd, the TCP Wrappers binary. Because xinetd includes similar functionality, it’s generally not used with TCP Wrappers.


Listing 10.1: Sample xinetd configuration entry


service ftp { socket_type = stream protocol = tcp wait = no user = root server = /usr/sbin/in.ftpd server_args = -l }


One additional xinetd.conf parameter is commonly present: disable. If you include the linedisable = yes in a service definition, xinetd ignores the entry. Some server packages install startup files in /etc/xinetd.d that have this option set by default; you must edit the file and change the entry to read disable = no to enable the server. You can also disable a set of servers by listing their names in the defaults section of the main xinetd.conf file on a line called disabled, as in disabled = ftp shell.


As with inetd, after you make changes to xinetd’s configuration, you must restart the super server. You do this by typing a command similar to the one used to restart inetd. As with that command, you can use either reload or restart, with similar effects:


# /etc/init.d/xinetd restart


Also as with inetd, you may pass the SIGHUP signal to xinetd via the kill or killallcommand to have it reload its configuration file. This approach may be preferable if you’re using a distribution that doesn’t use a conventional SysV startup script to launch xinetd.


Controlling Access via xinetd


Security is handled on a server-by-server basis through the use of configuration parameters in /etc/xinetd.conf or the server-specific configuration files. Some of these options are similar to the function of hosts.allow and hosts.deny:


Network Interface The bind option tells xinetd to listen on only one network interface for the service. For instance, you can specify bind = 192.168.23.7 on a router to have it listen only on the Ethernet card associated with that address. This feature is extremely useful in routers, but it isn’t as useful in computers with just one network interface. You can, however, use this option to bind a server only to the loopback interface, 127.0.0.1, if a server should be available only locally. You might do this with a configuration tool like the Samba Web Administration Tool (SWAT). A synonym for this option is interface.


Allowed IP or Network Addresses You can use the only_from option to specify IP addresses, networks (as in 192.168.78.0/24), or computer names on this line, separated by spaces. The result is that xinetd will accept connections only from these addresses, similar to TCP Wrappers’ hosts.allow entries.


Disallowed IP or Network Addresses The no_access option is the opposite of only_from; you list computers or networks here that you want to blacklist. This is similar to thehosts.deny file of TCP Wrappers.


Access Times The access_times option sets times during which users may access the server. The time range is specified in the form hour:min-hour:min, using a 24-hour clock. Note that this option affects only the times during which the server will respond. If the xinetd access_times option is set to 8:00-17:00 and somebody logs in at 4:59 p.m. (one minute before the end time), that user may continue using the system well beyond the 5:00 p.m. cutoff time.


You should enter these options into the files in /etc/xinetd.d that correspond to the servers you want to protect. Place the lines between the opening brace ({) and closing brace (}) for the service. If you want to restrict all your xinetd-controlled servers, you can place the entries in the defaults section in /etc/xinetd.conf.

lsof command

The lsof program nominally lists open files. It can be used to identify what files are open in a directory, find who’s accessing them, and so on. The definition of file used by lsof is broad, though; it includes network connections. Thus, you can use lsof instead of netstat for some tasks, including locating servers that are in use. In its most basic form in this role, you should pass the -i parameter to lsof


If you type lsof -i as an ordinary user, you’ll see only your own network connections; thus, in order for this command to be a useful diagnostic for system security, you must run it as root.


You can restrict the output of lsof by including an address after the -i option. The address takes the following form:


[46][protocol][@hostname|hostaddr][:service|port]


The digit 4 or 6 represents an IPv4 or IPv6 connection, the protocol is the protocol type (TCP or UDP), the hostname or hostaddr is the computer hostname or IP address associated with the remote system, the service is a service name (from /etc/services), and the port is the port number. For instance, suppose you want to verify that no FTP server is running on a computer. You can search for any connections associated with the FTP port:


# lsof -i :ftp


Alternatively, you can replace ftp with 21, because 21 is the port number associated with the FTP port. (Table 8.2 in Chapter 8 summarizes the common network port numbers.) In either case, this command returns a list of all processes associated with FTP connections, both incoming and outgoing. If no such connections exist, the command returns no output; the system simply produces a new command prompt. Be sure to note which output lines are linked with server as opposed to client processes. Even if you’re not running an FTP server locally, the preceding command may produce dozens of lines of output if users on the computer are making use of FTP clients.


To perform a general audit of your system’s network connections, you should type lsof -i by itself, without restricting the output. You’ll probably want to pipe the output through less or use a terminal’s scroll buffer to review the output. Piping the output through grep to search for the string LISTEN can be a shortcut to find active servers:


# lsof -i | grep LISTEN


Paging through the raw output (without using grep to search for LISTEN) will provide you with a better idea of your system’s overall network use. You could conceivably spot something suspicious, such as an outgoing network connection to a sensitive computer that the client shouldn’t be contacting. This network activity may indicate active cracking attempts by a user of the client, intrusion by an outsider, or the work of an automated worm or Trojan horse program.


If you identify programs that shouldn’t be running, such as unnecessary servers, you can use the command name, PID, and other information to help shut them down. The preceding section “Disabling Unused Servers” describes how to do this in more detail.


Another use of lsof is in identifying who’s accessing files. This might be handy if you need to unmount a filesystem (including a network filesystem) but can’t because of in-use files or if you suspect inappropriate activities involving file access.

nmap command

nmap is a network scanner that can scan for open ports on the local computer or on other computers.


Nmap is capable of performing a basic check for open ports. Pass the -sT parameter and the name of the target system to it, as shown here:


$ nmap -sT seeker.rodsbooks.com


The -sT option specifies a scan of TCP ports. A few servers, though, run on UDP ports, so you need to scan them by typing nmap -sUhostname. (This usage requires root privileges, unlike scanning TCP ports.)

Security and /etc/inittab

On computers using the SysV startup system, /etc/inittab deserves examination. This file, described in Chapter 5, controls some of the earliest stages of the startup process. Of greatest interest from a security point of view is the fact that older /etc/inittab installations started the processes used to accept text-mode logins, as well as similar processes used to accept logins via dial-up modems and RS-232 serial ports. These processes are called getty or some variant of this, such as mingetty. Ordinarily, a Linux machine must have at least one such process running, and it’s controlled via an /etc/inittab entry such as the following:


1:2345:respawn:/sbin/mingetty --noclear tty1


The first character of this line (1) specifies the virtual terminal (VT) it controls. Most Linux distributions include similar lines for the first six VTs, and there’s usually no need to adjust these lines. Lines that begin with S#, where # is a number, control login via RS-232 serial ports and modems:


S0:2345:respawn:/usr/sbin/mgetty -F -s 57600 /dev/ttyS0


If you want to use a modem with the computer but don’t want to enable remote logins via the modem, you should ensure that /etc/inittab does not have such lines.


Modern systems that lack /etc/inittab or have only very basic /etc/inittab files typically move these functions into other files, such as SysV startup scripts or files in /etc/init. You won’t ordinarily need to modify such configurations, but you may want to check to be sure your system isn’t listening for dial-up modem connections unnecessarily. Files called/etc/init/tty# (where # is a number) control local login access, whereas /etc/init/ttyS#files control RS-232 serial or modem access.

su command

The su command’s name stands forswitch user, and it’s used to change a user’s apparent identity. Typing su alone results in a prompt for the root password. If the user types that password correctly, the session effectively becomes a root session. You can also type a username after su to acquire that user’s privileges. When root does so, no password is required. (This is sometimes handy for investigating problems reported by a single user.) To run a single program with rootprivileges, use -c to specify the program name, as in su -c "lsof -i" to run lsof -i as root.

/etc/sudoers and sudo command

A method of acquiring root access that is somewhat more secure than either direct logins orsu is sudo. This program runs a single command as root; for instance, to run lsof -i as root, you type


$ sudo lsof -i [sudo] password for georgia:


In this example, the computer prompts for the user’s (georgia’s) password, not for the rootpassword. The idea behind sudo is that you first configure the computer to accept certain users as sudo users. Those users may then use their own passwords to perform superuser tasks, even if those users don’t have the root password. (Some sudo configurations require users to enter the superuser’s password rather than their own password, though.) You can even fine-tune what tasks users may perform. This is done via the /etc/sudoers configuration file. You must edit this configuration file via visudo, which is a variant of Vi (described in Chapter 5) that’s used only to edit /etc/sudoers.


The /etc/sudoers file consists of two types of entries: aliases and user specifications. Aliases are basically variables; you can use them to define groups of commands, groups of users, and so on. User specifications link users to machines and commands (possibly using aliases for some or all options). Thus, you can configure sudoers such that georgia can run network programs with root privileges but not account maintenance tools, whereas george can run account maintenance tools but not network programs.


Your default /etc/sudoers file probably includes several examples. Consider the following lines:


## Storage Cmnd_Alias STORAGE = /sbin/fdisk, /sbin/sfdisk, /sbin/parted, /sbin/partprobe, /bin/mount, /bin/umount ## Processes Cmnd_Alias PROCESSES = /bin/nice, /bin/kill, /usr/bin/kill, /usr/bin/killall %sys ALL = STORAGE, PROCESSES %disk ALL = STORAGE %wheel ALL=(ALL) ALL


This example defines two command aliases, STORAGE and PROCESSES, each of which stands in for a set of commands. Users who are members of the sys group may use both sets of commands; users who are members of the disk group may use the STORAGE commands but not the PROCESSES commands; and members of the wheel group may use all commands, whether or not they’re explicitly mentioned in /etc/sudoers.


Some distributions, such as Ubuntu, make heavy use of sudo; these distributions are designed to be administered exclusively via sudo, and they set up an /etc/sudoers file that provides at least one user with easy access to all system utilities. Other distributions don’t rely on sudothis way, although you can tweak your sudo configuration to enable administration via sudo if you like.

ulimit command

Another way to set limits on system resource use is via the ulimit command. This command is a bash built-in command, so it affects only bash and programs launched from it. The ulimitsyntax is as follows:


ulimit [options [limit]]


The options define what is being limited:


Core File Limits The -c option limits the size of core dumps, which are files created for debugging purposes in certain types of program crashes.


File Limits The -f option limits the size of files that may be created by the shell, and -nlimits the number of open file descriptors. (Most systems don’t honor the -n limits, though.)


Process Limits The -u option limits the number of processes a user may run, and -t limits the total CPU time in seconds.


Memory Limits The -v option sets the total amount of virtual memory available to the shell, -s sets the maximum stack size, -m sets the maximum resident set size, -d limits programs’ data set size, and -l sets the maximum size that may be locked into memory.


Hard and Soft Limits The -H and -S options modify other options, causing them to be set as hard or soft limits, respectively. Hard limits may not be subsequently increased, but soft limits may be. If neither option is provided, ulimit sets both the hard and soft limits for the feature specified.


Current Settings Passing -a causes ulimit to report its current settings.


The limit is typically a numeric value associated with the limit. The ulimit command is often found in system or user bash startup scripts, typically as ulimit -c 0, in order to prevent creation of core files, which can sometimes clutter a filesystem. If your users perform software development, you may want to ensure that you do not set this limit, or at least set it as a soft limit (as in ulimit -Sc 0) so users may override it when necessary.



Because ulimit is a bash built-in command, its utility as a system security tool is limited. If users have access to GUI login tools or can log into the system in any way that bypasses bash (such as via SSH, depending on how it’s configured), restrictions imposed by ulimit become meaningless. Thus, you should treat ulimit as a way to prevent problems because of accidental, rather than intentional, abuse of the system.

/etc/nologin

If this file is present, only root may log into the computer. Other users are shown the contents of this file when they attempt to log in. In many respects, this is like setting critical system limits to 0 for all other users. This file is most likely to be useful on dedicated server systems that have no regular console or remote shell users.

/etc/ssh/ssh_host_rsa_key and ssh_host_rsa_key.pub

Most OpenSSH server startup scripts include code that looks for stored public and private keys and, if they’re not present, generates them. In total, four to six keys are needed: public and private keys for two or three encryption tools SSH supports. These keys are normally stored in /etc/ssh and are called ssh_host_rsa_key and ssh_host_dsa_key for private keys, with .pub filename extensions added for public keys. Some systems add ssh_host_rsa1_keyand its associated public key. If your system doesn’t have these keys and you can’t get the SSH server to start up, you can try generating the keys with the ssh-keygen command:


# ssh-keygen -q -t rsa -f /etc/ssh/ssh_host_rsa_key -C '' -N ''


Each of these commands generates both a private key (named in the -f parameter) and a public key (with the same name but with .pub appended).


Don’t run these ssh-keygen commands if the SSH key files already exist. Replacing the working files will cause clients who’ve already connected to the SSH server to complain about the changed keys and possibly refuse to establish a connection.



Be sure the private keys are suitably protected; if an intruder obtains one of these keys, the intruder can impersonate your system. Typically, these files should have 0600 (-rw-------) permissions and be owned by root. The public key files (with .pub filename extensions) should be readable by all users, though.

/etc/ssh/ssh_host_dsa_key and ssh_host_dsa_key.pub

Most OpenSSH server startup scripts include code that looks for stored public and private keys and, if they’re not present, generates them. In total, four to six keys are needed: public and private keys for two or three encryption tools SSH supports. These keys are normally stored in /etc/ssh and are called ssh_host_rsa_key and ssh_host_dsa_key for private keys, with .pub filename extensions added for public keys. Some systems add ssh_host_rsa1_keyand its associated public key. If your system doesn’t have these keys and you can’t get the SSH server to start up, you can try generating the keys with the ssh-keygen command:


# ssh-keygen -q -t dsa -f /etc/ssh/ssh_host_dsa_key -C '' -N ''


Each of these commands generates both a private key (named in the -f parameter) and a public key (with the same name but with .pub appended).


Don’t run these ssh-keygen commands if the SSH key files already exist. Replacing the working files will cause clients who’ve already connected to the SSH server to complain about the changed keys and possibly refuse to establish a connection.



Be sure the private keys are suitably protected; if an intruder obtains one of these keys, the intruder can impersonate your system. Typically, these files should have 0600 (-rw-------) permissions and be owned by root. The public key files (with .pub filename extensions) should be readable by all users, though.

/etc/ssh_known_hosts

When you configure a client system, you may want to consider creating a global cache of host keys. As already noted, the ssh program records host keys for each individual user. (It stores these in the ~/.ssh/known_hosts file.) When you set up the client, you can populate the globalssh_known_hosts file, which is normally stored in /etc or /etc/ssh. Doing so ensures that the public key list is as accurate as the sources you use to populate the global file. It also eliminates confirmation messages when users connect to the hosts whose keys you’ve selected to include in the global file.

~/.ssh/id_rsa and id_rsa.pub


~/.ssh/id_dsa and id_dsa.pub

ssh-keygen -q -t rsa -f ~/.ssh/id_rsa -C '' -N ''


The line above generates a version 2 key. You can instead generate a version 1 key by typingssh-keygen -q -t dsa -f ~/.ssh/id_dsa -C '' -N ''. This generates id_dsa andid_dsa.pub files. This procedure is not recommended because SSH version 1 is not as secure as version 1; however, you may need to use version 1 to connect to some servers.


~/.ssh/authorized_keys

To configure SSH to not require a password, follow these steps:


1. Log into the SSH client system as the user who will be performing remote access.


2. Type the following command to generate a version 2 SSH key:


$ ssh-keygen -q -t rsa -f ~/.ssh/id_rsa -C '' -N ''



Step 2 generates a version 2 key. You can instead generate a version 1 key by typingssh-keygen -q -t dsa -f ~/.ssh/id_dsa -C '' -N ''. This generates id_dsa andid_dsa.pub files. This procedure is not recommended because SSH version 1 is not as secure as version 1; however, you may need to use version 1 to connect to some servers.


3. Step 2 generates two files: id_rsa and id_rsa.pub. Transfer the second of these files to the SSH server computer in any way that’s convenient—via a USB flash drive, by usingscp, or by any other means. Copy the file under a temporary name, such as temp.rsa.


4. Log into the SSH server system. If you use SSH, you’ll need to type your password.


5. Add the contents of the file you’ve just transferred to the end of the~/.ssh/authorized_keys file. (This file is sometimes called ~/.ssh/authorized_keys2, so you should check to see which is present. If neither is present, you may need to experiment.) Typing cat ~/temp.rsa >> ~/.ssh/authorized_keys should do this job, if you stored the original file as ~/temp.rsa.


6. On some systems, you may need to modify permissions on the~/.ssh/authorized_keys file and on the directories leading to it. The authorized_keys file may require 0600 permissions, and you may need to remove write permissions for any but the account’s owner on your home directory and on the ~/.ssh directory.

ssh-agent and ssh-add commands

Another SSH authentication option is to use the ssh-agent program. This program requires a password to initiate connections, so it’s more secure than configuring logins without passwords; however, ssh-agent remembers your password, so you need type it only once per local session. To use ssh-agent, follow these steps:


1. Follow the procedure for enabling no-password logins described in “Configuring Logins Without Passwords,” but with one change: Omit the -N '' option from the ssh-keygen command in step 2. You’ll be asked for a passphrase at this step. This passphrase will be your key for all SSH logins managed via ssh-agent.


2. On the SSH client system, type ssh-agent /bin/bash. This launches ssh-agent, which in turn launches bash. You’ll use this bash session for subsequent SSH logins.


3. In your new shell, type ssh-add ~/.ssh/id_rsa. This adds your RSA key to the set that’s managed by ssh-agent. You’ll be asked to type your SSH passphrase at this time.


From this point on, whenever you use SSH to connect to a remote system to which you’ve given your public key, you won’t need to type a password. You will, however, have to repeat steps 2 and 3 whenever you log out, and the benefits will accrue only to the shell launched in step 2 or any shells you launch from that one.


If you make heavy use of this facility, you can insert ssh-agent into your normal login procedure. For instance, you can edit /etc/passwd so that ssh-agent /bin/bash is your login shell. For a GUI login, you can rename your normal GUI login script (for instance, change~/.xsession to ~/.xsession-nossh) and create a new GUI login script that calls ssh-agentwith the renamed script as its parameter. Either action inserts ssh-agent at the root of your user process tree so that any call to SSH uses ssh-agent.

ssh command

The default configuration on the server enables tunneling; but to be sure, check the /etc/ssh/sshd_config file on the server for the following option:


AllowTcpForwarding no


If this line is present, change no to yes. If it’s not present or if it’s already set to yes, you shouldn’t need to change your SSH server configuration.


On the client side, you must establish a special SSH connection to the server computer. You do this with the normal ssh client program, but you must pass it several parameters. An example will help illustrate this use of ssh:


# ssh -N -f -L 142:mail.luna.edu:143 benf@mail.luna.edu


The -N and -f options tell ssh to not execute a remote command and to execute in the background after asking for a password, respectively. These options are necessary to create a tunnel. The -L option specifies the local port on which to listen, the remote computer to which to connect, and the port on the remote computer to which to connect. This example listens on the local port 142 and connects to port 143 on mail.luna.edu. (You’re likely to use the same port number on both ends; I changed the local port number in this example to more clearly distinguish between the local and remote port numbers.) The final parameter (benf@mail.luna.edu in this example) is the remote username and computer to which the tunnel goes. Note that this computer need not be the same as the target system specified via -L.



If you want SSH on the client system to listen to a privileged port (that is, one numbered below 1024), you must execute the ssh program as root, as shown in the preceding example. If listening to a non-privileged port is acceptable, the ssh client can be run as a normal user.


With the tunnel established, you can use the client program to connect to the local port specified by the first number in the -L parameter (port 142 in the preceding example). For instance, this example is intended to forward IMAP traffic, so you’d configure a mail reader on the client to retrieve IMAP email from port 142 on localhost. When the email reader does this, SSH kicks in and forwards traffic to the SSH server, which then passes the data on to the SSH server computer’s local port 143, which is presumably running the real IMAP server. All of this is hidden from the email reader program; as far as it’s concerned, it’s retrieving email from a local IMAP server.

gpg command

To generate keys, you use the gpg program with its --gen-key option:


$ gpg --gen-key


The program will ask you a series of questions. In most cases, answering with the defaults should work well, although you may have to type in your full name and email address. The keys are stored in a keyring (a file that holds keys) in the ~/.gnupg directory.


Once you’ve generated your keys, you can export your public key:


$ gpg --export name > gpg.pub


This command saves the public key associated with name in the file gpg.pub. You can use your email address as name. (If you create additional public keys or add others’ public keys to your keyring, you can specify their names to export those keys.) You can then make your public key available to others so that they may encrypt email messages sent to you or verify your signed messages. Adding the --armor option produces ASCII output, which may be preferable if you intend to email the key. You can make the file accessible on your Web site, transfer it as an email attachment, or distribute it in various other ways.


One important method of distributing your public key is via a keyserver. This is a network server that functions much like a keyring. To send your public key to a keyserver, you can use the --keyserver hostname and --send-keys keyname options to gpg, as follows:


$ gpg --keyserver pgp.mit.edu --send-keys jennie@luna.edu


This example sends the public key for jennie@luna.edu from your public keyring to the server at pgp.mit.edu. Thereafter, anybody who wants to can retrieve the key from that server. (pgp.mit.edu is a popular site for hosting PGP public keys.)


Importing Keys


To encrypt email you send to others, you must obtain their public keys. Ask your correspondents how to obtain them. Once you’ve done so, you can add their keys to yourkeyring (that is, the set of keys GPG maintains):


$ gpg --import filename


This command adds filename to your set of public keys belonging to other people.



Although public keys are, by definition, public, there are security concerns relating to them. Specifically, you should be sure you use a legitimate public key. Hypothetically, a miscreant could publish a fake public key in order to obtain sensitive communications or fake a signed email. For instance, George might distribute a fake GPG public key that claimed to be from Harold. George could then either sign messages claiming to be from Harold or intercept email sent to Harold that was encrypted using the fake key. Thus, you should use as secure a communication method as possible to distribute your public key and to receive public keys from others.


Once you’ve created your own key and, perhaps, imported keys from others, you can see what keys are available by using the --list-keys option to gpg:


$ gpg --list-keys /home/gjones/.gnupg/pubring.gpg --------------------------------- pub 1024D/190EDB2E 2008-09-05 uid George A. Jones <gjones@example.com> sub 2048g/0D657AC8 2008-09-05 pub 1024D/A8B2061A 2008-09-05 uid Jennie Martin <jennie@luna.edu> sub 2048g/4F33EF6B 2008-09-05


The uid lines contain identifiers you’ll use when encrypting or decrypting data, so you should pay particular attention to that information.


Revoking a Key


Sometimes, you might have cause to revoke a public key. For instance, suppose you’ve stored a copy of your private key on a laptop computer and that laptop is stolen, or perhaps some employees have left your organization and you no longer want those individuals to be able to use the keys associated with their employee accounts. To revoke a key, you use the --gen-revoke keyname option to gpg:


$ gpg --gen-revoke jennie@luna.edu


The program asks you to answer a few questions, such as the reason for revoking the key. It then generates a key block, such as the following:


-----BEGIN PGP PUBLIC KEY BLOCK-----Version: GnuPG v2.0.19 (GNU/Linux)Comment: A revocation certificate should follow iEwEIBECAAwFAlBPvbkFHQBG28bACgkQbBimvBMO2y4uzwCeQiLkZx8jl2jk+ hn0OKUl3EznmBQAn2WvtuQW+AP6wlvOvNU/qYi8a7t8=s0/s -----END PGP PUBLIC KEY BLOCK-----


You should copy this text into a file (say, revocation.gpg) and import the file to your keyring:


$ gpg --import revocation.gpg


If you’ve distributed public keys associated with the revoked key, you should distribute this revocation, too. If you’ve sent your public keys to a GPG keyserver, you can pass your revocation along in the same way you sent your original public key:


$ gpg --keyserver pgp.mit.edu --send-keys jennie@luna.edu


Once this is done, you can generate and distribute a new set of keys, if desired.


Encrypting and Decrypting Data


To encrypt data, you use gpg with its --out and --encrypt options and, optionally, --recipient and --armor:


$ gpg --out encrypted-file --recipient uid --armor --encrypt original-file


You can use the UID from a gpg --list-keys output, or just the email address portion, as theuid in this command. If you haven’t signed the recipient’s key, you’ll have to verify that you want to use that key. The result is a new file, encrypted-file, which holds an encrypted version of original-file. If you omit the --armor option, the resulting file is a binary file; if you send it as email, you’ll need to send it as an attachment or otherwise encode it for transmission over the text-based email system. If you include the --armor option, the output is ASCII, so you can cut and paste the encrypted message into an email or send it as an attachment.


If you receive a message or file that was encrypted with your public key, you can reverse the encryption by using the --decrypt option:


$ gpg --out decrypted-file --decrypt encrypted-file


You’ll be asked to enter your passphrase. The result should be a decrypted version of the original file.


In practice, GPG can be even easier to use than this description may make you think. GPG is primarily used to secure and verify email, so most Linux email clients provide GPG interfaces. These options call gpg with appropriate options to encrypt, sign, or decrypt messages. Details vary from one email client to another, so you should consult your email client’s documentation for details.


Signing Messages and Verifying Signatures


As noted earlier, GPG can be used to sign messages so that recipients know they come from you. To do so, use the --sign or --clearsign option to gpg:


$ gpg --clearsign original-file


The --sign option creates a new file with the same name as the original, but with .gpgappended to the filename. This file is encrypted using your private key so that it may be decrypted only with your public key. This means that anybody with your public key may read the message, but anybody who can read it knows it’s from you. The --clearsign option works similarly, but it leaves the message text unencrypted and only adds an encrypted signature that can be verified using your public key. The --clearsign option creates a file with a name that ends in .asc.


If you receive a signed message, you can verify the signature using the --verify option to gpg:


$ gpg --verify received-file


If any of the keys in your keyring can decode the message or verify the signature, gpg displays a Good signature message. To read a message that was encrypted via the --sign option, you must decrypt the message via the --decrypt option, as described earlier.

/etc/hosts.allow and /etc/hosts.deny

From: https://jamalahmed.wordpress.com/2010/03/19/using-etchosts-allow-and-etchosts-deny-to-secure-unix/


TCP wrapper based access List Rules can be included in the two files
/etc/hosts.allow and
/etc/hosts.deny .


Work precedence:


1. if allow will not check 2
2. if not found then go to 2
3. if not found allow access.


Points to remember


* You can have only one rule per service in hosts.allow and hosts.deny file.
* Any changes to hosts.allow and hosts.deny file takes immediate effect.
* The last line in the files hosts.allow and hosts.deny must be a new line character. Or else the rule will fail.
* ALL – Matches everything
* LOCAL – Matches any host that does not contain a dot (.) like localhost.
* KNOWN – Matches any host where the hostname and host addresses are known or where the user is known.
* UNKNOWN – Matches any host where the hostname or host address are unknown or where the user is unknown.
* PARANOID – Matches any host where the hostname does not match the host address.


Patterns


ALL : 123.12.


Matches all the hosts in the 123.12.0.0 network. Note the dot (.) in the end of the rule.


ALL : 192.168.0.1/255.255.255.0


IP address/Netmask can be used in the rule.


sshd : /etc/sshd.deny


If the client list begins with a slash (/), it is treated as a filename. In the above rule, TCP wrappers looks up the file sshd.deny for all SSH connections.


sshd : ALL EXCEPT 192.168.0.15


will allow ssh connection for only the machine with the IP address 192.168.0.15 and block all other connections.


You can use the options allow or deny to allow or restrict on a per client basis in either of the files hosts.allow and hosts.deny


in.telnetd : 192.168.5.5 : deny
in.telnetd : 192.168.5.6 : allow


Shell Commands


As mentioned above, you can couple the rules to certain shell commands by using the following two options.


spawn – This option launches a shell command as a child process. For example, look at the following rule:


sshd : 192.168.5.5 : spawn /bin/echo `/bin/date` from %h >> /var/log/ssh.log : deny


Each time the rule is satisfied, the current date and the clients hostname %h is appended to the ssh.log file.


twist – This is an option which replaces the request with the specified command. For example, if you want to send to the client trying to connect using ssh to your machine, that they are prohibited from accessing SSH, you can use this option.


sshd : client1.xyz.com : twist /bin/echo “You are prohibited from accessing this service!!” : deny


When using spawn and twist, you can use a set of expressions. They are as follows :
%a — The client’s IP address.
%A — The server’s IP address.


%c — Supplies a variety of client information, such as the username and hostname, or the username and IP address.


%d — The daemon process name.
%h — The client’s hostname (or IP address, if the hostname is unavailable).
%H — The server’s hostname (or IP address, if the hostname is unavailable).


%n — The client’s hostname. If unavailable, unknown is printed. If the client’s hostname and host address do not match, paranoid is printed.


%N — The server’s hostname. If unavailable, unknown is printed. If the server’s hostname and host address do not match, paranoid is printed.


%p — The daemon process ID.


%s — Various types of server information, such as the daemon process and the host or IP address of the server.


%u — The client’s username. If unavailable, unknown is printed.