Tuesday, November 16, 2010

Change Prompt Color when logged in as Root

All security books will recommend you not to allow root SSH logins to your Linux machines. So most of us (administrators) commonly SSH with our regular user credentials and then use "su" to escalate our privileges in order to perform root tasks. If you do this frequently, sometimes it gets a little confusing to make out if you are currently root or regular user. To determine your current status you probably you end up looking at your prompt or type in "whoami".

In this article, I will show you how to change the color of your prompt when you escalate your privileges to a super-user. This technique is a good way to remind yourself that you are holding high privileges (so don’t do anything stupid). This tip is for administrator’s convenience and helps out more if you are managing large number of Linux servers.
Step 1: Login and escalate your privileges to a Super-User

I have a regular user account (username=param) on a Linux server. So in this step, I simply login to the server and then used “su” command to escalate my privileges to a Super-User.

Step 2: Modify /etc/bashrc file

Now using your favorite editor (I will be using vim), open the file /etc/bashrc and add the lines below at the end of /etc/bashrc file. Any shell commands that you want to be executed every time a user starts up a new shell is placed in the bashrc file. We are making the change to /etc/bashrc which runs for every user and not to user’s ~/.bashrc as it wont run when user will “su” to root.

function setprompt
{
local RED="\[$(tput setaf 1)\]"
local RESET="\[$(tput sgr0)\]"
if [ `id -u` = 0 ] # check if user is root
then
PS1="$RED[\u@\h:\W]$RESET "
else
PS1="[\u@\h:\W]$RESET "
fi
}
setprompt

In the code above:

* \u means current user name
* \h means hostname
* \W means trailing component of your current directory
* tput setaf 1 means, set foreground color to RED(1)
* PS1 is the prompt string setting

STEP 3: Test it

Now while you are logged in as regular user, execute “su” and provide the password. Once logged in as root you will see the prompt color is changed to red.

This is was a very simple trick, but it comes very handy. Hope you find it useful.

Colors
Submitted by Anonymous on Wed, 2008-05-07 17:37.

Thanks for this post.

To change the forecolor to another, look this table:

setaf n
0 = Black
1 = Red
2 = Green
3 = Yellow
4 = Blue
5 = Magenta
6 = Cyan
7 = White

Greetings!
»

* reply

Normal User
Submitted by Anonymous on Thu, 2009-06-25 18:54.

So if you are a user other than root would you just use this code to make them all blue?

function setprompt
{
local RED="\[$(tput setaf 4)\]"
local RESET="\[$(tput sgr0)\]"
if [ `id -u` != 0 ] # check if user is not root
then
PS1="$RED[\u@\h:\W]$RESET "
else
PS1="[\u@\h:\W]$RESET "
fi
}
setprompt
»

* reply

Normal users and root colors
Submitted by Anonymous on Tue, 2009-09-01 13:17.

To use blue for regular users and red for root you can do
the following. This also disables the coloring when no terminal
is used e.g. when you do a scp (secure copy).


function setprompt
{
if [ $TERM != "" ]
then
local RED="\[$(tput setaf 4)\]"
local BLUE="\[$(tput setaf 2)\]"
local RESET="\[$(tput sgr0)\]"
if [ `id -u` = 0 ] # check if user is not root
then
PS1="$RED[\u@\h:\W]$RESET "
else
PS1="$BLUE[\u@\h:\W]$RESET "
fi
fi
}
setprompt

Finding Hardware Details of your Linux Machine without Using Screw Driver

Many new Linux users have trouble determining the true specs of their Linux machine from command line. Linux GUI software's have evolved over past few years and provide the same details in very beautiful laid out manner; however an administrator/home-user may not have luxury of those tools on every machine.

So in this quick guide we will learn how to find specs of your Linux machine from command line. By the end of this guide you will be able to obtain full inventory of all components on your Linux machine within minutes. This should also help you in finding correct drivers and support for your hardware's chipset.
Part 1: Finding Hardware Details with lspci

lspci is a utility for displaying information about all PCI buses in the system and all devices connected to them. By default, it shows a brief list of devices. However you can use the various lspci options to request either a more verbose output or output intended for parsing by other programs.

[root@localhost ~]# lspci
00:00.0 Host bridge: Intel Corporation 82865G/PE/P DRAM Controller/Host-Hub Interface (rev 02)
00:02.0 VGA compatible controller: Intel Corporation 82865G Integrated Graphics Controller (rev 02)
00:1d.0 USB Controller: Intel Corporation 82801EB/ER (ICH5/ICH5R) USB UHCI Controller #1 (rev 02)
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev c2)
00:1f.1 IDE interface: Intel Corporation 82801EB/ER (ICH5/ICH5R) IDE Controller (rev 02)
03:08.0 Ethernet controller: Intel Corporation 82562EZ 10/100 Ethernet Controller (rev 02)
....

So now I know that my Graphics chip is “Intel Corporation 82865G Integrated Graphics Controller" and would take me a minute to search for drivers for that by searching the fine web. Here is the description of the line :

You may also use -v or -vv flags to display more information. When I used lspci -v, I get more details for my Graphic Chip

00:02.0 VGA compatible controller: Intel Corporation 82865G Integrated Graphics Controller (rev 02) (prog-if 00 [VGA])
Subsystem: IBM Unknown device 0285
Flags: bus master, fast devsel, latency 0, IRQ 185
Memory at f0000000 (32-bit, prefetchable) [size=128M]
Memory at e8000000 (32-bit, non-prefetchable) [size=512K]
I/O ports at 1800 [size=8]
Capabilities: [d0] Power Management version 1

Lspci utility reads some information from the PCI bus, and then collects additional information from its own database of hardware id's. This additional information is stored at /usr/share/misc/pci.ids and it contains information such as hardware-id, vendor, devices, classes and subclasses. Let's find our device in this file:

[root@localhost ~]# cat /usr/share/hwdata/pci.ids | grep "82865G Integrated Graphics Controller"
82865G Integrated Graphics Controller

As you can see our device is also listed in the hardware list. This hardware list is maintained at http://pciids.sourceforge.net, and you can use the update-pciids utility to download the most recent version.
Part 2: Finding Hardware Details with dmesg

dmesg is Linux command that is used to examine or control the kernel ring buffer. The program helps users to print out their boot-up messages.

Lspci worked well to discover our PCI devices but we want inventory of all devices on the system. Using dmesg we can view hardware details of everything detected by our operating system.

[root@localhost ~]# dmesg | less
Normal zone: 59248 pages, LIFO batch:15
DMI present.
Allocating PCI resources starting at 20000000 (gap: 10000000:eec00000)
Detected 2793.055 MHz processor.
Built 1 zonelists. Total pages: 63344
Kernel command line: ro root=/dev/VolGroup00/LogVol00 rhgb quiet
Enabling fast FPU save and restore... done.
Initializing CPU#0
CPU 0 irqstacks, hard=c07ae000 soft=c078e000
Memory: 244136k/253376k available (2139k kernel code, 8732k reserved, 866k data, 240k init, 0k highmem)
.....

As you can see dmesg gives you a lot of details, so we will use grep to restrict information to what we want. Let's say, we are interested in memory installed in the system.

[root@localhost ~]# dmesg | grep -i memory
Memory: 244136k/253376k available (2139k kernel code, 8732k reserved, 866k data, 240k init, 0k highmem)
Freeing initrd memory: 2124k freed
Total HugeTLB memory allocated, 0
Non-volatile memory driver v1.2
agpgart: Detected 8060K stolen memory.
Freeing unused kernel memory: 240k freed
.....

Similarly you can grep for whatever hardware you are trying to troubleshoot, for example CPU, USB etc.
Part 3: Finding Hardware Details from /proc

Sometimes you will want to monitor physical memory and CPU information on a running system in real time. For doing this, you will have to read the /proc file system. You might be thinking about `top` utility, but that utility also reads information from /proc file system. Make sure you only use `cat` command to view the information and do not change any of the files in /proc.

Doing an `ls` on /proc folder you will see various files and folders which contain information about your system.

Now let's start looking at what these files contain, starting with cpuinfo.

[root@localhost ~]# cat /proc/cpuinfo
processor : 0
vendor_id : GenuineIntel
cpu family : 15
model : 2
model name : Intel(R) Pentium(R) 4 CPU 2.80GHz
stepping : 9
cpu MHz : 2793.055
cache size : 512 KB
..

Now let's dig deeper and go inside a folder, I am going inside the `ide` folder and reading details for my hard disk.

[root@localhost ~]# cat /proc/ide/ide0/hda/driver
ide-disk version 1.18
[root@localhost ~]# cat /proc/ide/ide0/hda/capacity
78156288
[root@localhost ~]# cat /proc/ide/ide0/hda/model
IC35L060AVV207-0
Part 4: Getting More Information about your HDD using fdisk

In our last step using /proc, we obtained very basic information about our Hard Disk Settings. Now lets dig deeper by using `fdisk` command available in Linux. We will now try to obtain information about partitions, space available, space allocated, swap and more.

`fdisk` is the partition table manipulator tool for Linux. Generally hard disks are divided into one of more logical disks, also known as partitions. This partition information is stored in partition table found on sector 0 of the disk.

To display all partitions on your system, just type:

[root@localhost ~]# fdisk -l
Disk /dev/hda: 40.0 GB, 40016019456 bytes
255 heads, 63 sectors/track, 4865 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
/dev/hda1 * 1 13 104391 83 Linux
/dev/hda2 14 4865 38973690 8e Linux LVM

And to view details of a particular drive, let say you have hda and hdb drives then type fdisk -l /dev/hda
Part 5 (UPDATE) : Reading BIOS information using dmidecode command

dmidecode tool dumps your system's DMI (Desktop Management Interface) table contents in a human-readable format. This table contains information regarding system's hardware components, as well as BIOS revisions etc. dmidecode output not only describes system current configuration, but also reports the BIOS limitations on supported CPU speed, Maximum Memory allowed and more.

Now lets say I want to restrict information to certain areas of DMI, I can do that by using the option -t and specifying what type of information I am interested in. For example, Processor Information is DMI type 4 and Memory Device is DMI type 17.

I hope this tutorial helps you as much as it helped my friend who was installing MythTV on Fedora and kept on opening his box for hardware details :)

Pod Web Server

Most Perl developers use CPAN or PerlDoc from command line interface for viewing documentation of Perl modules. Only a few are aware of Pod::Webserver module which creates a minimal web server to serve local Perl documentation. I found this really handy when I am coding Perl during flights or at airports without wireless connectivity.

Pod::WebServer module runs as an application that works as a minimal web server to serve local Perl documentation. This module provides podwebserver command which is equivalent to PerlDoc-to-HTML-over-HTTP.
Step 1: Install Pod::Webserver

If podwebserver isn't on your system, install the Pod::Webserver module from CPAN. On my Cygwin environment, the installation goes like this:

cpan> install Pod::Webserver
Running install for module Pod::Webserver
Running make for A/AR/ARANDAL/Pod-Webserver-3.04.tar.gz
Fetching with LWP:
ftp://cpan-du.viaverio.com/pub/CPAN/authors/id/A/AR/ARANDAL/Pod-Webserver-3.04.tar.gz
CPAN: Digest::SHA loaded ok
Fetching with LWP:
ftp://cpan-du.viaverio.com/pub/CPAN/authors/id/A/AR/ARANDAL/CHECKSUMS
Checksum for /cygdrive/d/cygwin/download/.cpan/sources/authors/id/A/AR/ARANDAL/Pod-Webserver-3.04.tar.gz ok
Scanning cache /cygdrive/d/cygwin/download/.cpan/build for sizes
Pod-Webserver-3.04/
Pod-Webserver-3.04/t/
Pod-Webserver-3.04/t/03_daemon.t
Pod-Webserver-3.04/t/01_about_verbose.t
Pod-Webserver-3.04/t/02_pod_webserver.t
Pod-Webserver-3.04/podwebserver
Pod-Webserver-3.04/lib/
Pod-Webserver-3.04/lib/Pod/
Pod-Webserver-3.04/lib/Pod/Webserver.pm
Pod-Webserver-3.04/META.yml
Pod-Webserver-3.04/MANIFEST
Pod-Webserver-3.04/ChangeLog
Pod-Webserver-3.04/MANIFEST.SKIP
Pod-Webserver-3.04/Makefile.PL
Pod-Webserver-3.04/README
CPAN.pm: Going to build A/AR/ARANDAL/Pod-Webserver-3.04.tar.gz
Checking if your kit is complete...
Looks good
Writing Makefile for Pod::Webserver
CPAN: YAML loaded ok
cp lib/Pod/Webserver.pm blib/lib/Pod/Webserver.pm
cp podwebserver blib/script/podwebserver
/usr/bin/perl.exe "-MExtUtils::MY" -e "MY->fixin(shift)" blib/script/podwebserver
/usr/bin/make -- OK
Running make test
/usr/bin/perl.exe "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/01_about_verbose....ok
t/02_pod_webserver....ok
t/03_daemon...........ok
All tests successful.
Files=3, Tests=24, 35 wallclock secs ( 2.59 cusr + 1.59 csys = 4.18 CPU)
/usr/bin/make test -- OK
Running make install
Installing /usr/lib/perl5/site_perl/5.8/Pod/Webserver.pm
Installing /usr/bin/podwebserver
Writing /usr/lib/perl5/site_perl/5.8/cygwin/auto/Pod/Webserver/.packlist
Appending installation info to /usr/lib/perl5/5.8/cygwin/perllocal.pod
/usr/bin/make install -- OK
Step 2: Once Installed Start your PodWebServer

Open Cygwin window and type in `podwebserver &`

podwebserver

Now Open your web browser and point it to localhost and port specified by podwebserver command. You can also change the default port number by using ""-p options.

For Example: podwebserver "-p" 8020

podwebserver

So now even when I am on flights or traveling, I can run my own Perl documentation server to aid me while I am coding.

Hope this helps you too.

Five Best BSD Linux Security Tools

Over the course of recent years, some people have found the quality of most out-of-the-store firewall appliances either lacking functionality or worse, set at a price that has made them generally out of reach. Because of this issue, I thought it would be beneficial to write an article to better highlight what works and what does not with regard to turning an older PC into a standalone router/firewall appliance.

1. IPCop

At its very core, IPCop is in fact a firewall appliance before all else. And as many of you might suspect, IPCop happens to be a Linux distribution with the sole function of acting as a hardware firewall, thus protecting your network from threats outside and from within. IPCop can be installed via CD, Flash Drive, HTTP/FTP network setups and is fairly straight forward to setup.

Considering the offering of multiple language support and the fact that this little Linux distribution will run on pretty much anything, it is a proven homegrown firewall. Speaking of support, I should also point out that IPCop has a number of very cool add-ons as well. My two favorites are Banish and Copfilter, which is used to filter out malware and viruses in real time.

2. M0n0wall

Regardless of a fantastic effort by IPCop, there is just something to be said about rocking solid BSD solutions. The first that comes to mind is that from m0n0wall. It's small, 12 MBs small! That is the single biggest distinguishing thing to note about m0n0wall. Its size and portability, that is. Designed to be a replacement for those expensive firewall appliances used today, m0n0wall works on embedded machines, in addition to being quite useful on older x86 PCs as well.

Definitely a little more advanced from a usability standpoint than other solutions out there, but do not let this fool you, because m0n0wall is VERY powerful in all of its BSD goodness. This being said, it should be noted that even though m0n0wall is workable on a older PC, it shines best on embedded systems being used by more advanced administrators. Therefore, this is not a really good solution for new Windows converts looking to convert their old PC into something cool.

3. pfSense

From what I have been told, the pfSense project was started by the same people as m0n0wall. Those looking to revamp an older PC might be better off going with pfSense. Plenty of features to speak of. Most notable among them include:

# Redundancy -- By creating a fallover group, the network will remain secure even in the event of interfaces that go offline for some reason.

# Load Balancing -- Provides both inbound and outbound balancing between WAN connections or multiple servers, depending on which way the traffic happens to be going.

# Captive Portal -- Force the user to authenticate or simply find themselves redirected to wherever you wish.

For those who have tried IPCop in the past but are still hungry for more control over their firewall installation, then I highly suggest going with pfSense as a great BSD option.

4. SmoothWall

If you have any level of involvement with IT, then the chances are good that you have experienced a SmoothWall protected network at least once in your life. Often times, you may have not even been aware of it.

For many newbies totally unfamiliar with Linux or BSD, SmoothWall serves as a "gateway drug" for self-built firewall appliances, as it a provides for just about anyone with a blank CD and an older PC to create a ready-to-roll firewall appliance for their home office or small business. Just like other more complicated solutions, SmoothWall provides amazingly simple installation. Once installed, the administrator can setup their firewall settings, QoS, Web filter, anti-spam protection, and manage outgoing/incoming instant message conversations.

At its core, SmoothWall is a firewall with heavily content filtering abilities. If you have never tried turning an old PC into a firewall appliance, this is what I would suggest starting with. And yes, SmoothWall also has enterprise level support and offerings for those needing to go this route, as well.

5. Linux LiveCD Router

At first I hesitated to even bother highlighting this particular solution, as it bothered me on two fronts.

1. One, it is difficult to gauge just how well supported this Linux distro actually is. It appears to have dropped off the face of the planet around 2007?

2. It is a relative unknown to me. I know nothing of this option at all, other than the fact that it provides LiveCD functionality.

Those concerns aside, the fact that I am able to get a clear idea what this little LiveCD provides with regard to support does make me feel a lot better.

# Remote SSH administration.

# Load balancing between two ISP connections.

# Boot from a CD or a USB Flash Drive.

Each of these features mean something to the casual home user. Especially one that is not totally sure about taking the time to install something that might very well not be a good for their needs. Speaking for myself, I have gone both ways for awhile and finally ended up settling on a Draytek Vigor2820n Security Router. I decided to go this way due to hardware-heat headaches rather than me wanting something self-built.

At the end of the day, it is important to recognize that for some users, going with a build-your-own hardware firewall appliance is the way to go. But for many others, sometimes is just makes sense to buy something pre-built. And that is where trying out the various options out there comes into play.

Speaking for myself, I am thrilled that I first took the time to really understand the roll-your-own solutions first. It enabled me to better work through what I was looking for from a hardware firewall and what turned out to be mostly fluff

About SUID, SGID and Sticky bit

Set user ID, set group ID, sticky bit

In addition to the basic permissions discussed above, there are also three bits of information defined for files in Linux:

* SUID or setuid: change user ID on execution. If setuid bit is set, when the file will be executed by a user, the process will have the same rights as the owner of the file being executed.
* SGID or setgid: change group ID on execution. Same as above, but inherits rights of the group of the owner of the file on execution. For directories it also may mean that when a new file is created in the directory it will inherit the group of the directory (and not of the user who created the file).
* Sticky bit: It was used to trigger process to "stick" in memory after it is finished, now this usage is obsolete. Currently its use is system dependent and it is mostly used to suppress deletion of the files that belong to other users in the folder where you have "write" access to.

Numeric representation

Octal digit Binary value Meaning
0 000 setuid, setgid, sticky bits are cleared
1 001 sticky bit is set
2 010 setgid bit is set
3 011 setgid and sticky bits are set
4 100 setuid bit is set
5 101 setuid and sticky bits are set
6 110 setuid and setgid bits are set
7 111 setuid, setgid, sticky bits are set

Textual representation

SUID, If set, then replaces "x" in the owner permissions to "s", if owner has execute permissions, or to "S" otherwise.

Examples:
-rws------ both owner execute and SUID are set
-r-S------ SUID is set, but owner execute is not set

SGID, If set, then replaces "x" in the group permissions to "s", if group has execute permissions, or to "S" otherwise.

Examples:
-rwxrws--- both group execute and SGID are set
-rwxr-S--- SGID is set, but group execute is not set

Sticky, If set, then replaces "x" in the others permissions to "t", if others have execute permissions, or to "T" otherwise.

Examples:
-rwxrwxrwt both others execute and sticky bit are set
-rwxrwxr-T sticky bit is set, but others execute is not set

Setting the sticky bit on a directory : chmod +t

If you have a look at the /tmp permissions, in most GNU/Linux distributions, you'll see the following:

lokams@tempsrv# ls -l | grep tmp
drwxrwxrwt 10 root root 4096 2006-03-10 12:40 tmp

The "t" in the end of the permissions is called the "sticky bit". It replaces the "x" and indicates that in this directory, files can only be deleted by their owners, the owner of the directory or the root superuser. This way, it is not enough for a user to have write permission on /tmp, he also needs to be the owner of the file to be able to delete it.

In order to set or to remove the sticky bit, use the following commands:

# chmod +t tmp
# chmod -t tmp

Setting the SGID attribute on a directory : chmod g+s

If the SGID (Set Group Identification) attribute is set on a directory, files created in that directory inherit its group ownership. If the SGID is not set the file's group ownership corresponds to the user's default group.

In order to set the SGID on a directory or to remove it, use the following commands:

# chmod g+s directory
# chmod g-s directory

When set, the SGID attribute is represented by the letter "s" which replaces the "x" in the group permissions:

# ls -l directory
drwxrwsr-x 10 george administrators 4096 2006-03-10 12:50 directory

Setting SUID and SGID attributes on executable files : chmod u+s, chmod g+s

By default, when a user executes a file, the process which results in this execution has the same permissions as those of the user. In fact, the process inherits his default group and user identification.

If you set the SUID attribute on an executable file, the process resulting in its execution doesn't use the user's identification but the user identification of the file owner.

For instance, consider the script myscript.sh which tries to write things into mylog.log :

# ls -l
-rwxrwxrwx 10 george administrators 4096 2006-03-10 12:50 myscript.sh
-rwxrwx--- 10 george administrators 4096 2006-03-10 12:50 mylog.log

As you can see in this example, George gave full permissions to everybody on myscript.sh but he forgot to do so on mylog.log. When Robert executes myscript.sh, the process runs using Robert's user identification and Robert's default group (robert:senioradmin). As a consequence, myscript fails and reports that it can't write in mylog.log.

In order to fix this problem George could simply give full permissions to everybody on mylog.log. But this would make it possible for anybody to write in mylog.log, and George only wants this file to be updated by his myscript.sh program. For this he sets the SUID bit on myscript.sh:

# chmod u+s myscript.sh

As a consequence, when a user executes the script the resulting process uses George's user identification rather than the user's. If set on an executable file, the SUID makes the process inherit the owner's user identification rather than the one of the user who executed it. This fixes the problem, and even though nobody but George can write directly in mylog.log, anybody can execute myscript.sh which updates the file content.

Similarly, it is possible to set the SGID attribute on an executable file. This makes the process use the owner's default group instead of the user's one. This is done by:

# chmod g+s myscript.sh

By setting SUID and SGID attributes the owner makes it possible for other users to execute the file as if they were him or members of his default group.

The SUID and GUID are represented by a "s" which replaces the "x" character respectively in the user and group permissions:

# chmod u+s myscript.sh
# ls -l
-rwsrwxrwx 10 george administrators 4096 2006-03-10 12:50 myscript.sh
# chmod u-s myscript.sh
# chmod g+s myscript.sh
# ls -l
-rwxrwsrwx 10 george administrators 4096 2006-03-10 12:50 myscript.sh