Linux Server and Network Security
The most dangerous threat to internal networks are Internet gateways. Gateways are systems (or other hardware devices) with a minimum of two network interfaces where one interface is connected to the Internet (via an ISP connection) and at least one interface is connected to an internal LAN segment. Just as a gateway allows traffic to go out from your LAN onto the Internet, it also allows traffic from the Internet onto your LAN. The trick is to only let the traffic you want onto your LAN, and it's no easy feat.
You could be legally liable if someone hacks their way into your LAN and steals confidential data (social security numbers, credit card numbers, etc) that you maintain on your clients or customers. Worms or trojans could be planted that send passwords or other sensitive information out onto the Internet to a waiting sniffer. The risks are many and the consequences could threaten the very existance of your company. It's not uncommon for large institutions like banks and insurance firms to decline pressing charges against a hacker simply because they don't want the negative press and loss of confidence they would suffer as the result of a public prosecution by a district attorney.
"Multi-homed" (multi-connection) systems such as gateways are not the only security risk. A server that is only connected to the Internet, such as a Web server, is also at risk of being hacked. You may not care if some hacker cracks his way in and defaces your Web pages. You just reload the pages. But there are other, more hideous, attacks that are not uncommon:
- Your server can be used as a base from which attacks on other systems can be launched.
- Your e-mail server could be used as a relay for spammers.
- Your system can be surreptitiously used as an IRC (chat) server or for some other band-width intensive application that steals performance from both your server and your Internet connection.
- Your could be the target of DoS (Denial of Service) attacks which renders your servers (e-mail or Web), and your Internet connection, useless.
- Internet servers that use SSL to collect sensitive information such as credit card numbers or account numbers and passwords can be targets of hackers in order to try and gain access to the devices where this data is stored. (SSL only protects in-transit HTTP traffic. It does nothing for operating system or server security.)
Addressing security issues is one of those cases where "an ounce of prevention is worth a pound of cure". A hacker could do untold damage if they get into your system or network. And because hackers learn their trade in underground electronic communities, if one finds a way into your system you can bet that they'll let everyone else know about it.
If your company has public address space with an available IP you may want to try a little test just for grins. Do a full-boat install of Debian (including all Internet-related apps you can think of) and put the system on the Internet. It doesn't need a domain name with a DNS record, just a static public IP address. Set it up with the Apache, Sendmail, wu_ftpd, telnet, and any other services running and just leave it sit there. Check the /var/log/messages file every week or so and see how long it takes for the hackers to find it and start playing around with it. When I tried this they took all of two weeks. Since there's no way of telling what they did during their visits, you'd be wise to totally wack the partitions on the hard-drive and do an install from scratch when you do want to re-use the system as a production server.
Setting up a system like this is actually a new security tool that's emerging. It's called setting up a "honey-pot". The hackers are drawn to the the honey-pot because it's the most responsive, and are drawn away from your production servers. Before you deploy your honey-pot you may want to hang a tape drive on the system and do a full backup so you can go back to square one once it gets compromised. Again, thre's no way to really know everything that a hacker may have done to your system once they get in so the only safe thing to do is start over. Monitoring your honey-pot on a regular basis will let you know when things are happening so you can keep an even closer eye on your production servers.
Don't always assume that the "untrusted" network you're trying to protect yourself from is the Internet. If you have VPNs or other types of network connectivity established with business partners or even other divisions within the same company, you must be watchful for unauthorized access attempts from these networks as well. "Trust no one" is a good rule to follow when it comes to system and network security.
Do Your Homework
Along with the benefits of having your own Internet servers comes the responsibility of being knowledgable on how to secure those servers. Covering this subject beyond anything other than a superficial manner is beyond the scope of any single Web page. Here we only present an overview of some of the common tools used to help secure an Internet-connected server. It is by no means comprehensive and should only serve as an introduction to the topic.
Security measures can be categorized into the following four broad classifications:
Different publications may categorize things differently but that's of little consequence. The important thing is that doing so allows you to take a "divide and conquer" approach to addressing all of the various aspects involved in securing a network, its servers, and the information contained on them.
- OS configuration - "hardening" the operating system
- Application configuration - making sure the server applications you do make available do only what they're supposed to do
- Perimeter security - configuring your network infrastructure with firewalls and DMZs
- Physical security - only authorized users and systems should have access to the network infrastructure
Hardening the operating system involves many things are are not only operating system-specific, but may often vary from one "flavor" of an operating system to another. Typical steps include:
- Disabling all default accounts and groups that are not needed. When an operating system is installed it sets up quite a few user accounts and groups by default. (Try logging into your Debian system using the username news and see how far you can navigate around your system's file system and what files you can cat to the screen.) There's a line in the /etc/passwd file for each user. Each line contains different pieces of info separated by colons (:) with the last item being the user's default shell (typically the Bash shell). To disable user accounts, just change the default shell to /bin/false so they can't log in.
- Change your startup configuration so that only necessary services are running. Many services open TCP/IP "ports" which hackers find when running port scans against systems. (Many applications are responsible for starting services also.) Closing all unnecessary ports is a common practice. You can run a port scanner from another system against your server to see which ports are open.
- Configure file system security (using the chmod and chown commands) so that only the bare minimum of access to files and directories is allowed.
- Utilize strong (mixed case, alpha-numberic, long) passwords on accounts that are necessary.
- Don't use common names for groups that are given high levels access
- Use TCP wrappers (tcpd) to run Internet-related daemons and properly configure the hosts.allow and hosts.deny files to restrict access.
- Don't run a GUI if you don't need one and never leave a GUI running while the server isn't being used for an interactive console session.
- Log off of server consoles when they're not being used. This is especially important for Internet-connected systems.
There is a HOWTO on securing the OS on the Debian Web site at:
The installation routines for many Linux distributions set things wide open by default to reduce the number of technical support calls and e-mails they get. (The more wide open a system is the less likely it is that someone - or an application - will run into problems trying to perform a specific task or function.) As a result, most Linux systems are inherently insecure. Once you do make security-related changes, check to make sure that all functions of your applications still run the way they should.
Where to learn more - The best of our bookshelves:
Maximum Linux Security is the best security book I've found for those who do not have a lot of Linux experience. The first four chapters cover some of the basics of Linux from a security perspective, including the fundamentals of server administration. If you are going to set up an Internet server, get this book. The book not only covers what to do, but covers the theory behind why you are doing it. It also shows you how hackers work and provides links to the tools they use to break in. You would think that a book on server security would be pretty dry, but this book is an easy read.
Some applications are insecure due to the defaults used during their installations and some are just inherently insecure. Telnet and ftp are two inherently insecure applications because passwords are transmitted over the wire as clear text.
The biggest threat to many applications is their vulnerability to "buffer overflow" attacks which usually results in the hacker having access to the system with the rights of whatever user account the application was running under.
The following are some general guidelines related to applications:
- Use more secure equivalents for insecure applications (ex: ssh instead of telnet, sudo in place of su, etc).
- Keep your applications up-to-date with the latest versions. Many releases are specifically developed to address security issues.
- Determine which ports an application opens up and see if they are absolutely necessary. If they aren't, shut them down.
- Check the application vendor's Web site for information on how to make the application more secure and for any news items and or patches that address newly-discovered security vulnerabilities.
- If you have a Web server, learn proper programming techniques to ensure that CGI scripts are secure and make sure the scripts you use utilize these techniques. Also acquaint yourself with the security issues related to Server Side Includes and any Web site interpreters you may be running (such as PHP or ASP).
- In the case of a Web server, if Web page updates are fairly infrequent, you could just edit the pages on the server using a text editor or use a floppy disk to "sneaker-net" the updated HTML files by mounting the floppy disk, copying the files into the DocumentRoot directory, and then unmounting the floppy. Either of these would eliminate the need to run an ftp server service and enabling an account for the person who maintains the pages.
- If you have an Apache Web server (or have a Web site that is hosted on a shared Apache Web server) and the US government's Titan Rain investigation has you considering blocking visitors from China (which we are now doing), you can configure Apache to deny access to your site from Chinese IP addresses (see my China blocking page for more information).
- Searching Google for the name of the application along with the word 'harden' will usually yield some helpful configuration information. For instance, Googling 'harden apache' will list some Web pages which tell you what modules you can rem out (in the /etc/apache/modules.conf file) to make your Apache installation more secure.
If all you want to do is set up a simple Web server (running Apache) then there are quite a few "applications" (OS utilities actually) that run by default that are not needed. They open ports and since each open port is a possible entry point into your server by a hacker, you don't want them open. I disable them by renaming their 'S' (startup) symlinks in the appropriate runlevel directory. Since Debian boots into runlevel 2 by default, we want to go into the runlevel 2 startup directory with the command:
There we'll find the symlink S20ssh which opens the port for secure remote console sessions. If you'll be physically at the console (keyboard and monitor), there is no need for remote access. To stop the SSH server service from needlessly opening a port we disable it by just renaming its symlink with the command:
mv S20ssh _S20ssh
You can do the same for S20exim4, S20lpd, and S21nfs-common. Now if you reboot your system and run the
netstat -acommand you'll see fewer open ports. One port that does remain open though is 'sunrpc'. That's the RPC portmap service and it is notorious for being the target of exploits. If you run the netstat -apcommand you'll see that '/sbin/portmap' is the application that has the sunrpc port (port 111) open. NFS and some other applications need the RPC service. Apache does not. So for our simple Web server we can disable portmap. However, this service is called from two places so we need to rename both symlinks with the commands:
mv /etc/rc2.d/S18portmap /etc/rc2.d/_S18portmap
mv /etc/rcS.d/S43portmap /etc/rcS.d/_S43portmap
Note that disabling RPC will cause the 'nfs-common' service to fail at boot-up but that's OK. You shouldn't be mounting any network drives on a Web server anyway.
Now if you again reboot your system and run the
netstat -acommand you'll see only port 80 open (and possibly port 25 listening on 127.0.0.1 which is internal only).
Other daemons and services don't open ports but they're not needed either and they just use up memory. Two examples in the default installation that you can also rename are S89atd and, if your system isn't connected directly to a cable or DSL modem that uses PPPoE, S14ppp.
Because applications interact with the operating system, start processes, and accept input they can affect operating system security. Likewise, operating system security can affect an application's ability to function properly. Achieving maximum OS security while still retaining full application functionality is a balancing act.
This balancing act is evident when using "jails" or chroot jails. You can put any program or daemon in it's own jail. A chroot jail is a way of configuring the operating system so that the directory the application is running from appears to be the root of the entire file system. As such, the only directories the application can "see" or has access to are the ones it needs to run. That way, if an application does have a security flaw, the hacker exploiting that flaw won't have access to the entire file system.
For example, if you want to set up a DNS server be advised that BIND runs as root. As such, if a hacker exploited a security flaw in BIND they would have root access to the entire file system. By running BIND in a jail, the hacker would only have access to the BIND application directory.
The problem with jails is that they can be a pain to set up. ALL files that an application needs (library files, config files, etc.) or generates (data files, log files) have to reside within the jail. So if you were going to set up a jail for BIND in /var/lib/named you'd have to create /var/lib/named/etc (for config files) and /var/lib/named/var (for log files) directories under that directory. You also then need to create a user for the application and change ownership of the directories to that user. It may be a pain but it does isolate your file system considerably.
This discussion of mod_security refers to mod_security 2.x on Apache 2.x.
mod_security 2.x only works with Apache 2.x. It is not backward compatible with Apache 1.x.
Back on our Internet Servers page we showed you how to change a couple security settings to reduce the amount of information about your server that is given out to potential hackers. However, this doesn't do anything for HTTP-targeted attacks.
If your firewall is properly configured to only allow port 80 traffic to your Web server there are still dangers that can come in on port 80, the most common being malformed URLs. There's an Apache IDS (Intrusion Detection System) module that can keep an eye out for suspicious and malformed requests and block them.
Depending on the version of Debian you have this module may already be installed and enabled. If it is, there is still one tweak you need to make. Check you enabled modules with the command:
and look for the security2.load file (along with the .conf file). If it's there you want to fully enable the modules capabilities with the command:
mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
Note that all you're doing is removing the '-recommended' from the file name so the file gets read when Apache loads. That's all you need to do (other than restarting Apache) if the module was already installed and enabled.
If you didn't have any 'security2' modules enabled above you'll need to install and enable the module manually. Enter the command:
apt-get install libapache2-mod-security2
This will not only add the module files to the /etc/apache2/mods-available directory but also adds the sym link to it in the /etc/apache2/mods-enabled directory and restarts Apache. Unfortunately that doesn't do us much good because there is no configuration file yet.
Below is a sample mod_security configuration file which you can use as is. The first part of the file configures the module's operation while the second part of the file adds the filtering rules it should use. You can copy/paste the following into a file with a name like "mod-security.conf" and then FTP that file (using ASCII mode) to your server.
Note that there are drastic differences between mod_security 1.x
configuration statements and mod_security 2.x configuration statements.
Most configuration examples available on the Web are for version 1.x.
The example below is for 2.x because that's the version available on
the package maintainer's site. If you want to customize your
configuration be sure to use the 2.x statements.
<IfModule security2_module> # *** MODULE CONFIG # Turn the filtering engine On SecRuleEngine On # Only log suspicious requests SecAuditEngine RelevantOnly # The name of the audit log file SecAuditLog /var/log/apache2/modsec_audit.log # Debug level set to a minimum (0) - 9 is max SecDebugLogLevel 0 SecDebugLog /var/log/apache2/modsec_debug.log # Should mod_security inspect POST payloads SecRequestBodyAccess On # By default log and deny suspicious requests # with HTTP status 403 SecDefaultAction deny,log,status:403,phase:2 # *** FILTER RULES SecRule REQUEST_URI /etc/passwd SecRule REQUEST_URI /bin/ls SecRule REQUEST_URI /bin/uname SecRule REQUEST_URI /usr/bin/whoami SecRule REQUEST_URI cd\x20/tmp SecRule REQUEST_URI wget\x20 # Make sure that URL encoding is valid SecRule ARGS "@validateUrlEncoding" # Unicode encoding check SecRule ARGS "@validateUtf8Encoding" # Only allow bytes from this range SecRule ARGS:text "@validateByteRange 0 255" # Block Santy.A worm SecRule ARGS:highlight %27 # Block drop table SQL injection attack SecRule REQUEST_URI "drop[[:space:]]table" # Only accept request encodings we know how to handle # we exclude GET requests from this because some (automated) # clients supply "text/html" as Content-Type SecRule REQUEST_METHOD "!^(GET|HEAD)$" chain SecRule REQUEST_HEADERS:Content-Type \ "!(^application/x-www-form-urlencoded$|^multipart/form-data;)" # Do not accept GET or HEAD requests with bodies SecRule REQUEST_METHOD "^(GET|HEAD)$" chain SecRule REQUEST_HEADERS:Content-Length "!^$" # Require browser headers from all user agents SecRule "REQUEST_HEADERS:USER_AGENT|HTTP_HOST" "^$" # Require Content-Length to be provided with every POST request SecRule REQUEST_METHOD "^POST$" chain SecRule REQUEST_HEADERS:Content-Length "^$" # Don't accept transfer encodings we know we don't handle SecRule REQUEST_HEADERS:Transfer-Encoding "!^$" </IfModule>Once you get the file FTPed up to your server copy it into the /etc/apache2/conf.d directory so that Apache reads it when it starts. Don't forget to restart Apache after getting this file in place with the command:
You can test it out to make sure it's working by entering a URL which contains the text of one of the
"SecRule REQUEST_URI"entries. For example, if your server's IP address is 192.168.1.80 enter the following in a browser's address bar:
You should get the Apache "Forbidden" error page.
You can write a lot of your own rules, including only allowing certain types of traffic from certain addresses. If you want to allow for special access and get granular with your access control, check out the documentation at modsecurity.org.
You can use mod_security to also block Web site traffic from specific countries such as China and Russia. This is a lot less resource-intenstive alternative than using a .htaccess file to block such traffic. Mod_security has built-in support for using a free GeoIP database from maxmind.com. Since you'll want to update this database monthly we'll put the commands in a shell script and run that rather than entering the commands at a shell prompt.
You should still be in the /etc/modsecurity directory. Assuming you're logged in as root type in:
and enter the following commands:
wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gzip -df GeoIP.dat.gz
Press Ctrl-X and 'y' to save the file and exit the editor. Then set the file as executable with the command:
chmod 700 geoipdb.sh
Later we'll show you how to run this shell script automatically to update the database on a monthly basis. For now run it manually with the command
and you should have the file GeoIP.dat in the /etc/modsecurity directory. Now we need to edit the mod_security configuration file with the command:
Arrow down to the bottom of the file and add the following commands:
# Test IP address and block by country code
SecRule REMOTE_ADDR "@geoLookup" "phase:1,chain,id:10,drop,log,msg:'Blocking Country IP Address'"
SecRule GEO:COUNTRY_CODE "@streq CN RU KP"
Again press Ctrl-X and 'y' to save the file and exit the editor. The
CN RU KPin the last statement represents China, Russia, and North Korea. You can enter the country codes for other contries as well. To activate the new mod_security configuration reload Apache with the command:
You can see if mod_security is active by looking at the log file with the command:
and you should see entries indicating that site access were blocked.
The most common means of protecting a network is using a firewall (or two in the case of a DMZ which was illustrated back on the Firewall page). The biggest problem with firewalls is that people think they're more than they actually are. A firewall's major strength is protecting against traffic-based attacks (DoS, etc). If you let people into your network from the outside, the firewall has no way of differentiating between a legitimate user and a hacker. A firewall is not a substitute for strong OS and application security.
If you're going to use a firewall package on a Debian system, keep in mind that the firewall is the application. As such, a system-based firewall won't offer much security if the underlying OS isn't hardened. (This is why the NetMax commercial firewall product includes the OS piece. It allows them to ensure the OS is properly configured.)
If you want to have Internet servers or provide remote access using a VPN server, be sure to use a DMZ configuration with two firewalls. In cases where critical or confidential business information is at risk, use stateful firewalls and IDS (Intrusion Detection System) software.
An IDS has been referred to as the burglar alarm of the network. See our Snort page on how to set one up.
Unauthorized access to your servers can occur just as easily from the inside as the outside. Perhaps even more so since the internal organization is seen as less of a threat. While that may be (somewhat) true from a user perspective, the unauthorized use of the organization's facilities and hardware is a very real threat.
To most people, physical security means locking up the server hardware and hubs/switches. However, it goes far beyond that. It involves the entire physical plant, the systems that connect to it, and the office space those systems are located in. It even extends to the notebooks carried by your company's road warriors. Notebooks and PDAs get stolen all the time. And there's no telling who has access to the computers of those who dial-in from home where users have a tendency to check the "Remember password" box on their dial-up connections.
I have seen countless instances of organizations that spend all kinds of money on fancy security systems surrounding the rooms that house servers and other IT equipment and at the same time have network jacks in locations that anyone can get to without breaking a sweat. Someone could hook up a pocket-sized packet sniffer and in less than a minute have all the IP address information and maybe even some IDs and passwords they need. With all of the foot traffic in large companies at quitting time, it wouldn't take much for someone with a notebook to slip into a secluded office or cubicle and spend hours on your network with no one but the cleaning people to bother them.
Networks, by their very nature, mean you don't need to be phsically at a server to administrate that server. While IT operations typically don't have a lot of clout with a facility's security people, there are some infrastructure-related steps you can take to try and lock things down. Unplugging unused or publically-accessible network jacks at the cross-connects is one measure. Restricting users to logging in only on certain systems, whether they be identified by MAC address or a hostname, and only during certain hours is a start. Security-minded organziations are also setting up VPNs on internal networks and requiring that all Intranet Web traffic be SSL to guard against unauthorized sniffing.
And how many users do you know have their passwords written down on Post-It Notes stuck to their monitor or on a piece of paper inside a desk drawer? Biometric devices have dropped dramatically in price in the last two years. You can buy a hardware device that reads a fingerprint in order to authenticate users for a little over $100 now (U.are.U Pro from Digital Persona). Setting up certificate servers helps ensure that only authorized systems have access to network resources. They're not just for remote systems anymore.
That's not to say physical security of the servers and wiring closets isn't important. Just don't overlook the obvious. One organization was so proud of their fire-proof file room for all of their personnel records until I pointed out the room had a wooden door. A chain is only as strong as its weakest link. Do the doors to your server room or wiring closets open out? If so, it's probably just a matter of popping the hinge pins out and a door comes right off. Crawling over the top of a wall by popping out the panels in a suspended ceiling isn't all that tough either.
There are many steps you can take to secure the physical environment. Some are electronic, some are mechanical, and others are procedural. But nothing substitutes for common sense.
Security is not a "set it and forget it" proposition. Because there are no absolutes, constant monitoring is essential. New attacks are being developed every day and if you're simply going to respond once an attack is discovered it's likely too late. Hackers will use DoS attacks, log alterations (provided they can gain access), and other means to disguise other, more intrusive, exploits. In many cases simply waiting for obvious evidence that you've been hacked means you'll never know you've been hacked. The hackers will sneak in, grab what they want, and sneak back out again covering their tracks as they go.
In short, any security plan that is reactive rather than proactive is pretty lame. In addition to the security measures mentioned above, there are several things you can do to be more proactive in ensuring security:
- Monitor log files - By routinely monitoring system and application log files you get to know what's "normal" which makes it easier to spot things that JDLR (just don't look right). If you can afford the disk real estate, set up applications where logging configurations are allowed (like Apache) to log as much information as possible.
- Set up an Intrusion Detection System like Snort and have it monitor your DMZ. If you have an e-mail enabled pager or cell phone you can configure the IDS software to send any alerts to it so you'll know immediately if someone is snooping around your systems.
- Hack your systems - Obtain, learn, and use some of the same tools the hackers do. By doing so you'll see what the hackers see, which could be an eye-opening experience.
- As mentioned earlier, if you've got an available public address, set up a honey-pot system and monitor it on a frequent basis. You can use the same hacker tools against it and compare the results with those you found on your production systems.
- Got to www.cert.org and subscribe to their e-mail notifications. They do a great job of getting the word out on newly discovered weaknesses in operating systems or applications, often before any exploits of those weaknesses have been reported. They also include information on what to do about the weakness.
- Because Debian is free and the hardware requirements are so light, set up a hardened system as a standby. That way if one of your firewall or application server systems takes a dump you can configure the standby to take it's place a lot quicker than trying to figure out what happened to the system that's down and trying to fix the problem. When you're in a rush to get a system back on line some security measures may be passed over for the sake of expediency. If all of your systems, including the standby, are the same, you can simply restore a backup from the failed system to the standby system to get the security and application-specific information applied and be up and running in a matter of minutes.
Where to learn more - The best of our bookshelves:
My first reaction to Hacking Linux Exposed was "Oh great, now there'll be a million more hackers trying to get into our systems". It's a veritable tutorial, including step-by-step commands, on how to use a gazillion different exploits to hack into systems. However, after further consideration we realized this book is a great resource. It not only tells you how to do things (so you can see if you can when going against your systems), but gives specific countermeasures to mitigate the risks. It also gives each exploit individual ratings for simplicity, popularity, and impact and then combines them into an overall "risk rating". Comprehensive is the one word that best describes this book. For instance, it doesn't just cover Web servers but gets into CGI and SSI threats as well. Information on how to obtain a lot of the hacking tools that are available is also given.
Patching Your System
Debian's package system makes it real easy to keep your system up-to-date. Once you get your system set up just the way you want it you'll want to apply security patches on a regular basis. We'll show you how to automate the security patching process later in this page.
The first thing you should do is check the sources.list file that apt uses to determine from where it should pull updates.
Open the sources.list file in the nano text editor with the command:As mentioned on the Installation page, many organizations don't allow their servers to be Internet-accessible for security reasons. If this is the case with your server, you have no choice but to do point-release updates using discs and should not follow this procedure.
You'll see a line like the following for each DVD in your set:
deb cdrom:[name of dvd-rom]
Look further down in the file for lines that start with the following:
If there are # characters in front of these lines remove them to un-comment the lines. Then exit the editor (by pressing Ctrl-X and then, if you had to un-comment that line, press 'y' and then Enter) saving the change to the file.
The first thing you need to do us update your package library database with information on what the current versions of packages are. Do that with the command:
You can apply the latest security patches to your system with the following command:
apt-get upgrade -u
The -u in the above command just makes the process a little more verbose, displaying package names as they're downloaded and installed.
Note: The above procedure only updates applications that were installed as a Debian package. If you installed applications that were not in Debian packages (such as when you download the source code files from a Web site and compile/install it yourself), it will have to be updated separately.
Automating Security Patching
Automatically applying security patches will help ensure you're protected against the latest worms and exploits. Automating the process of retreiving and applying security patches is not hard at all. The cron memory-resident scheduler is loaded by default when the system boots so it's just sitting there waiting for you to use it. Automating a process involves two steps; giving cron something to run (i.e. creating a shell script containing the commands you want to run), and then telling cron when to run it.
You create a shell script using a standard text editor. Create the new shell script with the command:
and enter the following commands:
Note: When cron jobs run they run as the cron user which has a very limited PATH in its environment. Be sure to preceed all commands with the paths to the commands. To find out the path to a command you can use the whereis command followed by the name of the command. For example:
Normally when you patch a daemon you'll want to restart that daemon to make sure the patches take effect. However, since you won't know which daemon got patched with this automated process there's no way to know which daemons to restart so simply restarting the system is the safest way to go.
Save the file (Ctrl-X, y, Enter) and then change the permissions to make it executable using the command:
chmod 755 /usr/local/security-patches.sh
This is a very basic script. You'll probably want to set up some 'if' statements which test to make sure you got connected and check the success of the apt-get command.
How can you check to see if apt-get executed successfully? DOS had an ERRORLEVEL environment variable you could check the value of to determine the success of a command. In Linux/UNIX it's called the "exit status" and the ? represents this environment variable. Entering the command:
will display the exit status of the most recently run command. (Remember that you have to put the $ in front of an environment variable when referring to its value as with the echo command or the when using an 'if' statement in a shell script.) A zero indicates success (just remember "zero errors") and anything greater than a zero represents some kind of problem.
Now we tell cron when to run it.
cron is the memory-resident scheduler daemon that can execute commands and scripts at regular intervals. The jobs it runs are listed in a crontab file which is edited using the crontab utility.
The following command will list, if there is one, the contents of your current crontab file:
You'll want to add an entry to the crontab file for the security-patches.sh shell script. The format of the file is basically:
<when-to-run values> <what to run>
The "when to run" is a field which consists of five space-delimited values in the following order:
You can use the asterisk (*) to specify all values for any given entry. For example, to run a job every Saturday at 11:15 pm you would use the following values:
- Minutes past the hour (0 to 59)
- Hour of the day (0 to 23)
- Day of the month (1 to 31)
- Month of the year (1 to 12)
- Day of the week (0=Sunday to 6=Saturday)
15 23 * * 6
Be careful with these values. You'd rarely want to enter a number for the "Day of the Month" and the "Day of the Week". For example, if you entered:
15 23 3 * 6
cron would only run the job when the 3rd falls on a Saturday.
You can enter multiple values for each entry by separating them with commas. We set up cron jobs to check the logs twice a day, every weekday, at noon and again at 5 pm. This required the following values:
0 12,17 * * 1,2,3,4,5
Remember that the space is the delimiter between the five entries.
The "what to run" is what you want to cron to execute and is basically anything you can enter at a shell prompt. Any command, including pipes and redirects, shell script, etc. Since we want to run the security-patches.sh shell script, which we saved to the /usr/local directory, our crontab entry ends up looking like this:
0 3 * * 0 /usr/local/security-patches.sh
Note that only a space separates the "what to run" value from the last of the "when to run" values. The "when to run values above will run the security-patches.sh shell script every Sunday morning at 3 a.m.
So now that we know what our entry will be, we have to use crontab to enter it into the crontab file. At the shell prompt, enter:
If you get prompted to choose an editor select nano. The current crontab file automatically gets loaded and is most likely empty. Simply enter your new crontab entry. If you want to also create a cron job to automatically update the GeoIP database that we downloaded earlier you'll also want to add this entry to your crontab file:
0 23 10 * * /root/geoipdb.sh
An updated version of the GeoIP database gets released during the first week of every month. This entry run the batch file we created above at 11pm on the 10th of every month.
Close the editor with Ctrl-X and 'y' saving the file. You can check to make sure your entry was added to the crontab file by entering the following command at the shell prompt:
Note that you do not have to be logged into the console for cron jobs to run.
Security has become an ever-growing aspect of network administration and this growth shows no signs of abating. Vigilance is as important a quality as technical expertise. Exercise it like your professional life depends on it, because it may.
Did you find this page helpful ?
If so, please help keep this site operating
by using our DVD or book pages.
Site, content, documents, original images Copyright © 2003-2016 Keith Parkansky All rights reserved
Duplication of any portion of this site or the material contained herein without
the express written consent of Keith Parkansky, USA is strictly prohibited.
This site is in no way affiliated with the Debian Project, the debian.org Web site, or
Software In The Public Interest, Inc. No endorsement of this site by the Debian Project
or Software In the Public Interest is expressed or implied. Debian and the Debian logo
are registered trademarks of Software In The Public Interest, Inc. Linux is a registered
trademark of Linus Torvalds. The Tux penguin graphic is the creation of Larry Ewing.
IN NO EVENT WILL KEITH PARKANSKY OR BLUEHOST INCORPORATED OR ANY OF ITS' SUBSIDIARIES BE LIABLE TO ANY PARTY (i) FOR ANY DIRECT, INDIRECT, SPECIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF PROGRAMS OR INFORMATION, AND THE LIKE), OR ANY OTHER DAMAGES ARISING IN ANY WAY OUT OF THE AVAILABILITY, USE, RELIANCE ON, OR INABILITY TO USE THE INFORMATION, METHODS, HTML OR COMPUTER CODE, OR "KNOWLEDGE" PROVIDED ON OR THROUGH THIS WEBSITE, COMMONLY REFERRED TO AS THE "ABOUT DEBIAN" WEBSITE, OR ANY OF ITS' ASSOCIATED DOCUMENTS, DIAGRAMS, IMAGES, REPRODUCTIONS, COMPUTER EXECUTED CODE, OR ELECTRONICALLY STORED OR TRANSMITTED FILES OR GENERATED COMMUNICATIONS OR DATA EVEN IF KEITH PARKANSKY OR BLUEHOST INCORPORATED OR ANY OF ITS' SUBSIDIARIES SHALL HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, AND REGARDLESS OF THE FORM OF ACTION, WHETHER IN CONTRACT, TORT, OR OTHERWISE; OR (ii) FOR ANY CLAIM ATTRIBUTABLE TO ERRORS, OMISSIONS, OR OTHER INACCURACIES IN, OR DESTRUCTIVE PROPERTIES OF ANY INFORMATION, METHODS, HTML OR COMPUTER CODE, OR "KNOWLEDGE" PROVIDED ON OR THROUGH THIS WEBSITE, COMMONLY REFERRED TO AS THE "ABOUT DEBIAN" WEBSITE, OR ANY OF ITS' ASSOCIATED DOCUMENTS, DIAGRAMS, IMAGES, REPRODUCTIONS, COMPUTER EXECUTED CODE, OR ELECTRONICALLY STORED, TRANSMITTED, OR GENERATED FILES, COMMUNICATIONS, OR DATA. ALL INFORMATION, METHODS, HTML OR COMPUTER CODE IS PROVIDED STRICTLY "AS IS" WITH NO GUARANTY OF ACCURACY AND/OR COMPLETENESS. USE OF THIS SITE CONSTITUTES ACCEPTANCE OF ALL STATED TERMS AND CONDITIONS.