Pages

Friday, January 27, 2017

RPC / Portmapper

What is Portmap

Portmap is a server that converts RPC program numbers into DARPA (Defense Advanced Research Projects Agency) protocol port numbers. It must be running in order to make RPC calls.

When an RPC server is started, it will tell portmap what port number it is listening to, and what RPC program numbers it is prepared to serve. When a client wishes to make an RPC call to a given program number, it will first contact portmap on the server machine to determine the port number where RPC packets should be sent.

Portmap must be started before any RPC servers are invoked. Portmap logs errors using syslog.

Commands

1) rpcinfo

-d (debug) prevents portmap from running as a daemon, and causes errors and debugging  information to be printed to the standard error output.

-l (localhost only) causes portmap to only bind to the loopback interface.

-v- (verbose) run portmap in verbose mode.
  
Portmap version is protected by the tcp_wrapper library. You have to give the clients access to portmap if they should be allowed to use it. To allow connects from clients of the .bar.com domain you could use the following line in /etc/hosts.allow:

The RPC portmapper is a server that converts RPC program numbers into TCP/IP (or UDP/IP) protocol port numbers. It must be running in order to make RPC calls to RPC servers (like a NIS or NIS+ server) on that machine. When an RPC server is started, it will tell portmap what port number it is listening to, and what RPC program numbers it is prepared to serve. When a client wishes to make an RPC call to a given program number, it will first contact portmap on the server machine to determine the port number where RPC packets should be sent.

Since RPC servers could be started by inetd, portmap should be running before inetd is started.

For secure RPC, the portmapper needs the Time service. Make sure, that the Time service is enabled in /etc/inetd.conf on all hosts:

Monday, January 23, 2017

Linux - List of Configuration file and its uses

/etc/default/useradd - User default configuration file

Package Management using YUM and RPM

List of Topics


1) What is YUM
2) List of configuration files
3) What is GPG key
4) Other rpm commands

1) What is YUM

YUM is the short form of Yellowdog Update Modifier. 
If you want to verify that a package has not been corrupted or tampered with, examine only the md5sum by typing the following command at a shell prompt (where <rpm_file> is the file 

2) List of configuration files

Yum Configurationf file – /etc/yum.conf
Repo file configuration path – /etc/yum.repos.d/

A Simple syntax of .repo file.

1) [name - unique value]
2) name=""
3) baseurl=""
4) enabled=""
5) gpgcheck=""
6) gpgkey=""

A small info about gpg key (Gnu Privacy Guard) 

If you want to verify that a package has not been corrupted or tampered with, examine only the md5sum by typing the following command at a shell prompt (where <rpm_file> is the file name of the RPM package):

rpm -K --nosignature <rpm_file>

The message <rpm_file>: rsa sha1 (md5) pgp md5 OK (specifically the OK part of it) is displayed. This brief message means that the file was not corrupted during download. To see a more verbose message, replace -K with -Kvv in the command.

On the other hand, how trustworthy is the developer who created the package? If the package is signed with the developer's GnuPG key, you know that the developer really is who they say they are.

An RPM package can be signed using GNU Privacy Guard (or GnuPG), to help you make certain your downloaded package is trustworthy.

GnuPG is a tool for secure communication; it is a complete and free replacement for the encryption technology of PGP, an electronic privacy program. With GnuPG, you can authenticate the validity of documents and encrypt/decrypt data to and from other recipients. GnuPG is capable of decrypting and verifying PGP 5.x files as well.

During installation, GnuPG is installed by default. That way you can immediately start using GnuPG to verify any packages that you receive from Red Hat. Before doing so, you must first import Red Hat's public key.

3.1. Importing Keys

#rpm --import /usr/share/rhn/RPM-GPG-KEY

To display a list of all keys installed for RPM verification, execute the command:
#rpm -qa gpg-pubkey*

For the Red Hat key, the output includes:
#gpg-pubkey-db42a60e-37ea5438

To display details about a specific key, use rpm -qi followed by the output from the previous command:

#rpm -qi gpg-pubkey-db42a60e-37ea5438

a) In Case of File Conflicts to replace the files

rpm -ivh --replacefiles jpackage-utils-1.7.5-3.16.el6.noarch.rpm

b)  Download a package without installing it


To download a package without installing it, we need yumdownloader command which is part of yum-utils. So, Install the yum-utils package:

# yum install yum-utils

Then run the following command with argument as the desired package to download

# yumdownloader <package>

c) how  to install obsolete pacakages

Sometimes, we may need to install obsolete package due to application dependency. For that we need to use below option.

#yum --setopt=obsoletes=0 install openoffice*

d) List the configuration files

To list the configuration installed by a package

# rpm -qc <package name>

/etc/httpd/conf.d/autoindex.conf
/etc/httpd/conf.d/userdir.conf
/etc/httpd/conf.d/welcome.conf
/etc/httpd/conf.modules.d/00-base.conf
/etc/httpd/conf/httpd.conf
/etc/sysconfig/httpd

e) List the associated document and License as:

Similar to the option "c", option d is used to list the documents installed by the respective package.

# rpm -qd <package name>

# rpm -qd httpd
/usr/share/doc/httpd/ABOUT_APACHE
/usr/share/doc/httpd/CHANGES
/usr/share/doc/httpd/LICENSE 

# rpm -qL <package name>
# rpm -qL openssh

Saturday, January 21, 2017

BOOT Process and recovery

List of Topics

1) Steps involved in Linux Booting
2) List of process in Booting

    a) BIOS
    b) Boot Loader
    c) Kernel
    d) Init
    e) Runlevel
3) Sample Boot (GRUB) Configuration file
4) Boot loader restoration


1) Steps involved in Linux Booting

Linux Booting involves following five steps. BIOS, BOOT LOADER, KERNEL, INIT and RUNLEVEL. Below diagram is the exact procedure how Linux OS is booting. In the following sections we will see about  the below processes the in detail.




When a boot device is found, the first-stage boot loader is loaded into RAM and executed. This boot loader is less than 512 bytes in length (a single sector), and its job is to load the second-stage boot loader.

When the second-stage boot loader is in RAM and executing, a splash screen is commonly displayed, and Linux and an optional initial RAM disk (temporary root file system) are loaded into memory. When the images are loaded, the second-stage boot loader passes control to the kernel image and the kernel is decompressed and initialized. At this stage, the second-stage boot loader checks the system hardware, enumerates the attached hardware devices, mounts the root device, and then loads the necessary kernel modules. When complete, the first user-space program (init) starts, and high-level system initialization is performed.

2) List of process in Detail

a) BIOS

BIOS stands for Basic Input/Output System. BIOS is the 1st step of booting process and it performs Power-On Self-Test (POST). POST performs some integrity test and checks the status of hardware status and its functionality. After POST, then BIOS Searches, loads, and executes the boot loader program. It looks for boot loader in the selected bootable media eg:  floppy, cd-rom, or hard drive. Once the boot loader program is detected and loaded into the memory, BIOS gives the control to it. So, in simple BIOS loads and executes the boot loader which resides in MBR.

a.2)  MBR

MBR stands for Master Boot Record. It is located in the 1st sector of the bootable disk. (eg /dev/hda, or /dev/sda ). MBR is less than 512 bytes in size. This has three components
  a) primary boot loader info in 1st 446 bytes
  b) partition table info in next 64 bytes
  c) mbr validation check in last 2 bytes.


Located in the final two bytes of the MBR (511-512), this section must contain the hex value AA55, which officially classifies this as a valid MBR. An invalid magic number indicates a corrupt or missing MBR, therefore these bytes are critical to booting or using the disk.


Also, please keep in mind that the Magic Number is a hexadecimal number and is often represented as 0xAA55 or AA55h, but when viewed in a hex or disk editor it would be displayed as: "55 AA"

So, in simple terms MBR loads and executes the boot loader.

b) Boot Loader (GRUB)

In Linux We have two types of Boot loader LILO and GRUB. LILO is the old one. At present GRUB is used majorly in the field. GRUB means Grand Unified Boot Loader. Grub will display the list of kernels which is installed in your system. The screen which shows the list of installed kernels is called as splash image. From the displaying list we can choose anyone of the kernel which has to be executed. If nothing is selected then it will select the default one. All these parameter's are configured in /boot/grub/grub.conf and can be changed as per the requirement.

As per the image in the first section GRUB has three stages Stage 1, Stage 1.5 and Stage 2. We can check the stage 1.5 files just by listing under /boot/grub/ directory. If there are files with name 1_5 (eg: jfs_stage1_5) then stage 1.5 is there if no files with 1_5 then there is no stage 1.5 

Let us see what will happen in the stages of GRUB

Stage 1 - Primary boot loader is read into memory by the BIOS from the MBR. The primary boot loader exists on less than 512 bytes of disk space within the MBR and is capable of loading either the Stage 1.5 or Stage 2 boot loader.

Stage 1.5 - Boot loader is read into memory by the Stage 1 boot loader, if necessary. Some hardware requires an intermediate step to get to the Stage 2 boot loader. This is sometimes true when the /boot/ partition is above the 1024 cylinder head of the hard drive or when using LBA mode. The Stage 1.5 boot loader is found either on the /boot/ partition or on a small part of the MBR and the /boot/ partition.

Stage 2 - Secondary boot loader is read into memory. The secondary boot loader displays the GRUB menu and command environment. This interface allows selection of the kernel or operating system to boot, pass arguments to the kernel, or look at system parameters.

The secondary boot loader reads the operating system or kernel and initrd into memory. Once GRUB determines which operating system to start, it loads it into memory and transfers control of the machine to that operating system.

The secondary, or second-stage, boot loader could be more aptly called the kernel loader. The task at this stage is to load the Linux kernel and optional initial RAM disk.

Why GRUB uses three stage Boot Loader

GRUB uses three stage boot loader to load the kernel from either ext2, 3 or 4 filesystem Instead of using raw sectors on the disk, as LILO. For this purpose it makes the two-stage boot loader into a three-stage boot loader. Stage 1 (MBR) boots a stage 1.5 boot loader that understands the particular file system containing the Linux kernel image. Examples include reiserfs_stage1_5 (to load from a Reiser journaling file system) or e2fs_stage1_5 (to load from an ext2 or ext3 file system). When the stage 1.5 boot loader is loaded and running, the stage 2 boot loader can be loaded.

With stage 2 loaded, GRUB can, upon request, display a list of available kernels (defined in /etc/grub.conf, with soft links from /etc/grub/menu.lst and /etc/grub.conf). You can select a kernel and even amend it with additional kernel parameters. Optionally, you can use a command-line shell for greater manual control over the boot process.


With the second-stage boot loader in memory, the file system is consulted, and the default kernel image and initrd image are loaded into memory. With the images ready, the stage 2 boot loader invokes the kernel image.



c) Kernel


Mounts the root file system as specfied in grub.conf root=" ".  Then executes /sbin/init   program. initrd stands for initial RAM disk. initrd is used by kernel as temporary root file system until kernel is booted and the real root file system is mounted.  It also contains necessary drivers compiled inside which helps to access the hard drive partitions and other hardware. 

With the kernel image in memory and control given from the stage 2 boot loader, the kernel stage begins. The kernel image isn't so much an executable kernel, but a compressed kernel image. Typically this is a zImage (compressed image, less than 512KB) or a bzImage (big compressed image, greater than 512KB), that has been previously compressed with zlib. At the head of this kernel image is a routine that does some minimal amount of hardware setup and then decompresses the kernel contained within the kernel image and places it into high memory. 

If an initial RAM disk image is present, this routine moves it into memory and notes it for later use. The routine then calls the kernel and the kernel boot begins.

When the bzImage (for an i386 image) is invoked, you begin at ./arch/i386/boot/head.S in the start assembly routine (see Figure 3 for the major flow). This routine does some basic hardware setup and invokes the startup_32 routine in ./arch/i386/boot/compressed/head.S. This routine sets up a basic environment (stack, etc.) and clears the Block Started by Symbol (BSS). The kernel is then decompressed through a call to a C function called decompress_kernel (located in ./arch/i386/boot/compressed/misc.c). When the kernel is decompressed into memory, it is called. This is yet another startup_32 function, but this function is in ./arch/i386/kernel/head.S.

In the new startup_32 function (also called the swapper or process 0), the page tables are initialized and memory paging is enabled. The type of CPU is detected along with any optional floating-point unit (FPU) and stored away for later use. The start_kernel function is then invoked (init/main.c), which takes you to the non-architecture specific Linux kernel. This is, in essence, the main function for the Linux kernel.

Figure 3. Major functions flow for the Linux kernel i386 boot

With the call to start_kernel, a long list of initialization functions are called to set up interrupts, perform further memory configuration, and load the initial RAM disk. In the end, a call is made to kernel_thread (in arch/i386/kernel/process.c) to start the init function, which is the first user-space process. Finally, the idle task is started and the scheduler can now take control (after the call to cpu_idle). With interrupts enabled, the pre-emptive scheduler periodically takes control to provide multitasking.

During the boot of the kernel, the initial-RAM disk (initrd) that was loaded into memory by the stage 2 boot loader is copied into RAM and mounted. This initrd serves as a temporary root file system in RAM and allows the kernel to fully boot without having to mount any physical disks. Since the necessary modules needed to interface with peripherals can be part of the initrd, the kernel can be very small, but still support a large number of possible hardware configurations. After the kernel is booted, the root file system is pivoted (via pivot_root) where the initrd root file system is unmounted and the real root file system is mounted.
decompress_kernel output

The decompress_kernel function is where you see the usual decompression messages emitted to the display:
Uncompressing Linux... Ok, booting the kernel.

The initrd function allows you to create a small Linux kernel with drivers compiled as loadable modules. These loadable modules give the kernel the means to access disks and the file systems on those disks, as well as drivers for other hardware assets. Because the root file system is a file system on a disk, the initrd function provides a means of bootstrapping to gain access to the disk and mount the real root file system. In an embedded target without a hard disk, the initrd can be the final root file system, or the final root file system can be mounted via the Network File System (NFS).

https://www.ibm.com/developerworks/library/l-linuxboot/index.html

d) Init

Init is the first process to be started and it is the parent process for all the process in linux. PID of init process is 1.  Then it looks for the default runlevel configured in /etc/inittab. Post identifying the default run level it starts the respective program for that particular run level. Following are the available run levels

0 – halt
1 – Single user mode
2 – Multiuser, without NFS
3 – Full multiuser mode
4 – unused
5 – X11
6 – reboot

e) Runlevel programs

When the Linux system is booting, you can see various services getting started. For example, it might show “starting SSHD …. OK”. Those are the programs, executed from the run level directory as defined by you.

/etc/rc.d/init.d  - has the scripts which will be used by the files /etc/rc.d/rc[0-6].d/

Depending on your default init level setting, the system will execute the programs from one of the following directories. Run level 0 – /etc/rc.d/rc*.d/ . [* -Run level - 0- 6 ]

Please note that there are also symbolic links available for these directory under /etc directly. So, /etc/rc0.d is linked to /etc/rc.d/rc0.d.

Under the /etc/rc.d/rc*.d/ directories, you would see programs that start with S and K.

Programs starts with S are used during startup. S for startup. Programs starts with K are used during shutdown. K for kill.

There are numbers right next to S and K in the program names. Those are the sequence number in which the programs should be started or killed. For example, S12syslog is to start the syslog deamon, which has the sequence number of 12. S80sendmail is to start the sendmail daemon, which has the sequence number of 80. So, syslog program will be started before sendmail.

3) Sample Boot (GRUB) Configuration file

########################################################

#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.18-194.el5PAE)
          root (hd0,0)
          kernel /boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/

          initrd /boot/initrd-2.6.18-194.el5PAE.img

########################################################

4) Boot Loader restoration

Case 1) Steps to re-install grub

install grub stage 1 
grub> setup 

Case 2) Steps executed for /boot recovery if deleted

install grub stage 1 grub> setup command
reinstall kernel package.

first remove it then re-install it
rpm -e --justdb --nodeps <Kernel Package> 
rpm -ivh <Kernel Package>

Then create grub.conf file

Reboot the server and check it

https://www.ibm.com/developerworks/library/l-initrd/


The boot loader is responsible for loading both the kernel image and the initrd image into memory. They both will be in memory, before the boot loader hands control over to the kernel.


The kernel will receive the address where the initrd is in memory; it will just "interpret" it as if it were a full filesystem, in RAM. (The kernel does actually decompress it first. CPIO is used, because it is simple and robust to implement, requires not too much code, and has all the features needed.

Friday, January 20, 2017

AWK Syntax and Examples

1) What is AWK

awk is command used for processing files. With the help of awk we can print a particular field of a file or command output. Syntax of awk command is,

Syntax:  awk 'BEGIN {awk-commands} {Action} END {awk-commands}'

To understand more about awk will see some examples.

2) Print function

As mentioned above, with the help of awk we can print a particular field of a file or command.

eg 2. To print the first field of a file. (considering field separator as space )

# cat /etc/services | awk -F" " '{print $1}' 

This will print the first field of the file named services. Where -F" " means field separator is space. We can mention other values also to field separator like F"," (Coma as the field separator). 

Note : If you don't mention any field separator awk will consider space as default field separator. 

3) Inbuilt  Variable's

AWK has some inbuilt variables. Here is some of the list.

FILENAME - It represents the current file name.
FS
NR
FNR

OFS

NF - Number of fields.


When awk reads from the multiple input file, awk NR variable will give the total number of records relative to all the input file. Awk FNR will give you number of records for each input file.
3) sub and gsub function [ for Search and replace ]

In awk we have syntax called sub and gsub function to search for a partial string and perform the action. Below is the detailed explanation of gsub and gsub with examples.


gsub stands for global substitution. It replaces every occurrence of sub with regex. The third parameter is optional. If it is omitted, then $0 is used.

3.a) sub(regexpreplacement [, target])

The 'sub' function alters the value of TARGET.  It searches this value, which should be a string, for the leftmost substring matched by the regular expression, REGEXP, extending this match as far as possible.  Then the entire string      is changed by replacing the matched text with REPLACEMENT. The modified string becomes the new value of TARGET. This function is peculiar because TARGET is not simply used to compute a value, and not just any expression will do: it      must be a variable, field or array reference, so that `sub' can store a modified value there.  If this argument is omitted, then the default is to use and alter `$0'.

eg 3.a):

#echo "water, water, everywhere" | awk '{sub(/at/,"ith")}1'
output = "wither, water, everywhere" - 

Sub will only replace the leftmost occurrence of the regex with replacement(in this case `at'   with `ith') . 'sub' function returns the number of substitutions made (either one or zero).
   
3.b) : Now let's see what happens if the special character `&' appears in REPLACEMENT, it stands for the precise substring that matches the REGEXP. Below is the example for & string.


eg 3.b):

# echo "tommy,tom,water,tomboy" | awk '{ sub(/tom/, "& and his wife"); print }'
tom and his wifemy,tom,water,tomboy

Awk append the regexp instead of replacing it if we use & symbol. and this changes only the first occurance.

Here is another example:

          awk 'BEGIN {
                  str = "daabaaa"
                  sub(/a*/, "c&c", str)
                  print str
          }'

prints `dcaacbaaa'.  This show how `&' can represent a non-constant string, and also illustrates the leftmost rule.

3.c) Turning off Special character's 

Special character's can be turned off by putting a backslash before it in the string. As usual, to insert one backslash in the string, you must write two backslashes. Therefore, write '\\&' in string to include a literal `&' in the replacement.

eg 3.c): Here is how to replace the first `|' on each line with an `&':

          awk '{ sub(/\|/, "\\&"); print }'

Note : as mentioned above, the third argument to `sub' must be an value.  Some versions of `awk' allow the third argument to be an expression which is not an value.  In such a case, `sub' would still search for the pattern and return 0 or 1. 

4) Awk gsub function

List of all examples for gsub

[user@test ~]$ echo "water, water, everywhere" | awk '{gsub(/at/,"&ith");print}'
watither, watither, everywhere
[user@test ~]$ echo "water, water, everywhere" | awk '{gsub(/at/,"ith");print}'
wither, wither, everywhere
[user@test ~]$ echo "water, water, everywhere" | awk '{gsub(/at/,"bd\\&ith");print}'
wbd&ither, wbd&ither, everywhere
[user@test ~]$ echo "water, water, everywhere" | awk '{sub(/at/,"ith");print}'
wither, water, everywhere
[user@test ~]$ echo "water, water, everywhere" | awk '{gsub(/at/,"bd&ith");print}'
wbdatither, wbdatither, everywhere

4.a) Print the count of matched regex then use print before gsub function

eg 4.a):  To search in a file and print the count with line number. 


[user@test ~]$ echo "water, wattter, everywhere" | awk  -F, '{print gsub(/at/,"")}'
2

in the above example "at" occurs twice , so the count is printed as 2.

eg 4.a.2):

[user@test awkregex]$ grep -i NFS passwd_M
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin

[user@test awkregex]$ grep -i NFS passwd_M | awk -F:  '{print NR "\t" gsub(/rpc/,"")}'
1       1
2       0

in the above example NR is line number and \t represent print in tab space. rpc occurs one time and none in 1st and 2nd line respectively and the same count has been printed.

4.b) to search and print the count on particular field

[user@test awkrgex]$ grep -i NFS passwd_M
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin

to search in field 1 only we are creating a variable name col and using it in regex syntax and in similar way for column 2

[user@test awkrgex]$ grep -i NFS passwd_M |  awk -F: -v col=1 '{print NR "\t" gsub(/rpc/,"",$col)}'
1       1
2       0

[user@test awkrgex]$ grep -i NFS passwd_M |  awk -F: -v col=2 '{print NR "\t" gsub(/rpc/,"",$col)}'
1       0
2       0

5) Search and print  the lines which matches the recommended count

With the help of awk also we can do search and print lines like sed. Here fldcount is the sample file name. and we will print the lines which has 2nd field length 15 or 16 digit,and 1st field length 12 or 15 digit.

[user@test awkregex]$ cat fldcount
123710337783,351898014413150,123028040249634
123710337785,352934028758390,123028040109275
000123710337785,352934028758390,123028040109275
3710337785,352934028758390,123028040109275

[user@test awkregex]$ cat fldcount | awk -F, '{ if (((length($2) == 15 ) || length($2) == 16) && (length($1) == 12 && length($3) == 15)) print }'
123710337783,351898014413150,123028040249634
123710337785,352934028758390,123028040109275

6) awk printf function example



Printf is similar to #cat passwd

#cat passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

# awk -F":" '{printf("username=%s,userdid= %d\n", $1, $3)}' passwd | head -n 5

username=root,userdid= 0
username= bin,userdid= 1
username=daemon,userdid= 2
username=adm,userdid= 3
username=lp,userdid= 4

7) next and getline statement

The next statement forces awk to immediately stop processing the current record and go on to the next record. This means that no further rules are executed for the current record, and the rest of the current rule’s action isn’t executed.


Contrast this with the effect of the getline function (see Getline). That also causes awk to read the next record immediately, but it does not alter the flow of control in any way (i.e., the rest of the current action executes with a new input record).


Is there any way to cat a file that has something like:
field1,field2,field number 3,field4,field5
field1,field2,field3,field4,field5

(Some fields have spaces, some fields do not)

I want to print using awk $1 and $3, but only lines that do not have a space in field 3.
I don't know if there is any way to make awk print something only if it starts with , and ends with ,
Lines don't have the space in Field 3

awk -F, '{n=split($3,a," ");if(n==1){print $1,$3}}' filename