Tuesday, 22 November 2016

PAM modification required for AD integration in Linux

A centralized authentication mechanism is essential in any medium to large environments. In Linux, we can integrate client servers with Active Directory such that users logging into the systems will be authenticated via their AD credentials provided they have privileges to log into the system. For doing the client side AD integration we can use winbind or SSSD. This article is written using the SSSD method.
In this article I won't dwell into the complete setup for client side configuration for centralized AD authentication but instead focus on a subset of the process which in this case is the PAM part.

In order to configure active directory authentication on Linux client servers, we basically need to modify three PAM related files under /etc/pam.d. They are:

  1. password-auth
  2. system-auth
  3. sshd

Given below are the three files with the required modifications in place:

[root@localhost pam.d]# cat password-auth
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=5 type= minlen=8 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     optional      pam_oddjob_mkhomedir.so umask=0077
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so
[root@localhost pam.d]#

[root@localhost pam.d]# cat system-auth
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_listfile.so onerr=fail item=group sense=allow file=/etc/login.group.allowed
auth        required      pam_env.so
auth        sufficient    pam_fprintd.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=5 type= minlen=8 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     optional      pam_oddjob_mkhomedir.so umask=0077
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so
session     optional      pam_sss.so
[root@localhost pam.d]#
[root@localhost pam.d]#

[root@localhost pam.d]# cat sshd
#%PAM-1.0
auth        required      pam_listfile.so onerr=fail item=group sense=allow file=/etc/login.group.allowed
auth       required     pam_sepermit.so
auth       include      password-auth
account    required     pam_nologin.so
account    include      password-auth
password   include      password-auth
# pam_selinux.so close should be the first session rule
session    required     pam_selinux.so close
session    required     pam_loginuid.so
# pam_selinux.so open should only be followed by sessions to be executed in the user context
session    required     pam_selinux.so open env_params
session    optional     pam_keyinit.so force revoke
session    include      password-auth
[root@localhost pam.d]#


To summarize, we've used two more PAM modules in addition to the default ones already in the files at install time which are pam_listfile.so & pam_sss.so.

Now, let's dive in to the details of these two modules:

pam_sss.so:

This is the PAM interface to the System Security Services daemon (SSSD). 
Given below is a description of the options available with this module:

quiet
Suppress log messages for unknown users.

forward_pass
If forward_pass is set the entered password is put on the stack for other PAM modules to use.

use_first_pass
The argument use_first_pass forces the module to use a previous stacked modules password and will never prompt the user - if no password is available or the password is not appropriate, the user will be denied access.

use_authtok
When password changing enforce the module to set the new password to the one provided by a previously stacked password module.

retry=N
If specified the user is asked another N times for a password if authentication fails. Default is 0.
Please note that this option might not work as expected if the application calling PAM handles the user dialog on its own. A typical example is sshd with PasswordAuthentication.


pam_listfile.so:

This module is used to determine which users will be allowed access to the servers. We can use it without in conjunction with an AD integration setup as well as it's function is to determine which users will be allowed access based on entries in a file. Given below is a description of the options available with this module:

item=[tty|user|rhost|ruser|group|shell]
What is listed in the file and should be checked for.

sense=[allow|deny]
Action to take if found in file, if the item is NOT found in the file, then the opposite action is requested.

file=/path/filename
File containing one item per line. The file needs to be a plain file and not world writable.

onerr=[succeed|fail]
What to do if something weird happens like being unable to open the file.

apply=[user|@group]
Restrict the user class for which the restriction apply. Note that with item=[user|ruser|group] this does not make sense, but for item=[tty|rhost|shell] it have a meaning.

quiet
Do not treat service refusals or missing list files as errors that need to be logged.


With this understood I'll just elaborate on the statement we've used in the above example files for password-auth & system-auth files:

auth        required      pam_listfile.so onerr=fail item=group sense=allow file=/etc/login.group.allowed

The pam_listfile.so module will check for user group entries in the file /etc/login.group.allowed. If a user is a member of a group mentioned in the file, the user will be allowed to access the server. If the user is not a member of a group mentioned in the file, the user is denied access.

Here's a sample login.group.allowed file:

cat /etc/login.group.allowed
root
opcgrp
unixadmin
oinstall
SG-INFRA-HPOV-L2
SG-INFRA-Unix-L2

In the above file, the groups SG-INFRA-HPOV-L2 & SG-INFRA-Unix-L2 are created on Active Directory & members of these groups will be allowed login access to the server. The remaining groups are created locally on the OS & users belong to these groups will also be allowed access to the server.

Assuming that the SG-INFRA-HPOV-L2 & SG-INFRA-Unix-L2 group members are HP-OV & UNIX admin team members respectively, we'll make the below additions in /etc/sudoers file:

%SG-INFRA-Unix-L2 ALL=(ALL) NOPASSWD: ALL
%SG-INFRA-HPOV-L2 ALL=(ALL) NOPASSWD: /bin/su - hpov_user


The effect of these modifications is instantaneous & does not require any service restart or a system reboot.


Just a couple of gotchas:
  • If a user is not member of a group mentioned in the file but has ssh keys exchanged, the user will be granted access based on key exchange authentication.
  • In my experience if we use the pam_sss.so module in conjunction with the failllock or tally2 modules keeping all other parameters the same, then no users are able to login to the system.

Sunday, 20 November 2016

Disabling password aging in HP-UX

Disabling password aging in any operating system is a security risk but if the concerned system is intended for some sort of file transfer use like automated sftp file transfers then dealing with disabled passwords every couple of months can cause some issues.
This article describes the process to to disable password aging policy globally for all users in HP-UX.

We'll be using SAM for this. So, as root user type sam on the command line & the SAM TUI menu will open.

From there navigate to Auditing & security > System security policies


At the System security policies menu press the space bar to edit the policies.


From here you can see that password aging is currently enabled. You can disable it & press ok to save changes.


Working with tasksel on Ubuntu 16.04 LTS


tasksel is a neat utility installed in ubuntu 16.04 by default which allows the user to install groups of software packages & associated dependencies together as a single task.
This can be useful for example if we want to deploy the LAMP stack or if we have a scheduled activity coming up, we can pro-actively write a taskel task to suit our requirements & execute the task during the change time window.

To view a list of currently available tasks, type taskel to view the TUI or taskel --list-tasks for pure CLI output.




Creating custom tasksel tasks:


Got to the directory /usr/share/tasksel/descs. This contains the task descriptions which we saw when we executed the tasksel/tasksel --list-tasks commands.

root@buntu:/usr/share/tasksel/descs# pwd
/usr/share/tasksel/descs
root@buntu:/usr/share/tasksel/descs# ls
debian-tasks.desc  ubuntu-tasks.descs

We can edit one of these descriptions or write our own description.

So, without any further ado let's write ourselves a description.
We'll be writing it under /usr/share/tasksel/descs as the system will gather descriptions from files with .desc extension from this directory alone.
Here is a task file named my.desc I wrote for demonstration purposes.

Task: testing-tasksel
Relevance: 3
Description: A tasksel task to test out tasksel
 A tasksel task to test out tasksel
Key:
Packages: list
 tree
 apache2

The task directive is the title of the task.
The relevance defines how far up the tasksel menu we would like the task to appear.
Description is the information about the task which we'll view in the tasksel menu.
The key attribute would consist of any dependent packages which should already be installed in ordfer for this task to work.
Finally in the packages directive we list the packages that need to be installed as a part of our task.

Now if we type tasksel we would be able to see the task description of our newly created task in the menu.



To run this task type #taskel install <task-title> from the command line or use the space bar to select the task from the menu & press ok to run.



Removing the packages installed under a task is just as easy as installing them.
Just type #tasksel remove <task-title>

Script to report number of characters, words & lines in a file

While browsing through a shell scripting forum I came across a problem statement stating that someone wanted to write a script to report number of characters, words & lines in a file without using the wc command which would have been well very straight forward. 

So I decided to give it a try & after a while to some hits & misses I got a working script ready. 
Here is the script:

[root@cclient1 ~]# cat filecheck.sh
#!/bin/bash

case $2 in

-h) echo -e "The number of letters in file are: \n"

        b=0
        for i in `cat $1 | tr -d " "`
        do
        a=$(expr length $i)
        let b+=$a
        done
        echo $b
        ;;

-k) echo -e "The number of words in the file are: \n"

    awk  '{total=total+NF}; END {print total  }' $1
        ;;

-s) echo -e "The number of lines in file are: \n"
    awk  ' END {print NR }' $1
        ;;

*) echo "Incorrect usage"
    ;;

esac


Below is a description of what's happening.
  • In the first part, the for loop iterates through each line of the file. I used tr to remove spaces so that the entire line is treated as a single string. Then I used expr built in to calculate the length of the string & finally used let to add the values for string lengths of the individual lines.
  • In the second part, I used the number of fields built in variable in awk to sum up the number of fields in each line & print the final result.
  • In the final part, I used the number of records built in from awk to display the number of lines in the file.

Here's a demo of the script in action:

[root@cclient1 ~]# cat test
sa hi l su ri
un ix li n ux
hp ux


[root@cclient1 ~]# ./filecheck.sh test -h
The number of letters in file are:

22
[root@cclient1 ~]# ./filecheck.sh test -k
The number of words in the file are:

12

[root@cclient1 ~]# ./filecheck.sh test -s
The number of lines in file are:

3

Friday, 18 November 2016

Quick one liner to get swap usage in Solaris 10

Calculating swap usage is Solaris without top or prstat isn't easy since the output of 'swap -s' doesn't exactly paint an easily decipherable picture.

So what do we do?

We do some piping, some translation with tr & finally awk!

Take this example of the 'swap -s' output from a Solaris 10 server.

root@localhost:/# swap -s
total: 11454880k bytes allocated + 0k reserved = 11454880k used, 55653984k available
root@localhost:/#

To make it really easy to interpret, I did this:

root@localhost:/# swap -s | tr -d "k$" | awk '{total= $9 + $11;} {print 100 * $9 / total, "% swap is used"}'
17.0699 % swap is used
root@localhost:/#

That's it!

Embedding some HTML in a shell script


Shell scripts are awesome & another awesome trick I came across recently is the ability to wrap our shell commands around some basic html tags & redirect the content to a html file. Then we can view the output of our shell commands in a web page. This can be pretty useful when we need to share some command outputs as reports within other internal teams or to upper management. A web page output may be more easy to read as compared to a text file.

Here is the script I wrote:

[root@centdb DB]# cat web.sh
#!/bin/bash

echo "<html>
<body text="blue">

<h1> $(hostname) </h1>
<h2> script ran at $(date) </h2>

<font face="verdana" size="4">

<pre>
<font color="red"> system uptime is</font>
$(uptime)
</pre>

<pre>
<font color="red"> system disk utilization is</font>
$(iostat -xt)
</pre>

<pre>
<font color="red">File system utilization is</font>
$(df -h)
</pre>

</font>

</body>
</html>" > web.html


It's some basic stuff. I echoed the content of the entire script body to the output html file web.html. I used basic commands like uptime, iostat & df to illustrate the usage. You can do more complex commands or even use functions if you'd like. 
As far as the html part is concerned, that too is basic stuff with some usage of the font tag to add some color here n there.

When you open the resultant web.html file in a browser, it looks like this:



Thursday, 17 November 2016

AWK cheat sheet


Similar to the sed cheat sheet I shared in the previous article here, this article will be an awk cheat sheet. All the examples illustrated here may not be entirely original as this is something I've compiled over the years while using awk. Without any further ado, here it goes:



AWK ExpressionDescription
awk '/l.c/{print}' /etc/hosts [do a regex match with string containing 1 cahrector b/w l & c]
awk '/l*c/{print}' /etc/hosts [regex match everything b/w charectors l & c]
awk '/[al1]/{print}' /etc/hosts [a regex match with strings containing charectors a,l or l in a line]
awk '/[0-9]/{print}' /etc/hosts [prints all lines with numbers in them]
awk '/^10./ {print}' /etc/hosts [print all lines beginning with number 10]
awk '/rs$/{print}' /etc/hosts [print all lines ending with rs]
awk '/\$25.00/{print}' somedta.txt [escaping the $ character]
awk '//{print $1, $2, $3; }' somedta.txt [print columns 1,2 & 3 with fields separated by a space]
awk '//{printf "%-10s %s\n",$2, $3 }' my_shopping.txt [imporves spacial formatting between fields]
awk '/ *\$[2-9]\.[0-9][0-9] */ { print $1, $2, $3, $4, "*" ; } / *\$[0-1]\.[0-9][0-9] */ { print ; }' food_prices.list[multiple pattern matches & awk commands separateed by ;]
"awk '/ *\$[2-9]\.[0-9][0-9] */ { printf ""%-10s %-10s %-10s %-10s\n"", $1, $2, $3, $4 ""*"" ; } / *\$[0-1]\.[0-9][0-9] */ { printf ""%-10s %-10s %-10s %-10s\n"", $1, $2, $3, $4; }' somedta.txt
"[use printf for improved formatting]
awk '/ *\$[2-9]\.[0-9][0-9] */ { print $0 "*" ; } / *\$[0-1]\.[0-9][0-9] */ { print ; }' somedta.txt [value $0 denotes entire line with awk]
awk '$3 <= 30 { printf "%s\t%s\n", $0,"**" ; } $3 > 30 { print $0 ;}' somedta.txt[match value of 3rd column & print result accordingly]
awk '($3 ~ /^\$[2-9][0-9]*\.[0-9][0-9]$/) && ($4=="Tech") { printf "%s\t%s\n",$0,"*"; } ' somedta.txt[example of using multiple conditions in single awk command]
awk '$4 <= 20 { printf "%s\t%s\n", $0,"*" ; next; } {print $0 ;}' somedta.txt[add a * at the end of the line if value in 4th column is less than or euqal to 20]
ls -l | awk '$3 != "sahil" {print}' [print files not owned by user sahil]
uname -a | awk 'hostname = $2 {print hostname}' [using variables. assigned value of 2nd field to a variable named hostname]
awk '/^example.com/ { counter=counter+1 ; printf "%s\n", counter ; }' somedta.txt [use numeric variable in a for loop to count occurrances of lines beginning with techmint.com]
awk '/^example.com/ { counter=counter+1 ;} END {printf "%s\n", counter ; }'somedta.txt [print only total number of times example.com occurs in file]
awk 'BEGIN {count=0} /^example.com/ {count+=1} END {printf "%s\n", count ;}'somedta.txt [result is same as above example but here we've used begin & end both]
ls -l | grep ^- | awk 'BEGIN {total=0} {total+=$5} END {print total/1024/1024}' [print the total size of files in current directory in MB]
awk 'BEGIN {print "this is a begin Test"} /^example.com/ { counter=counter+1 ;} END { printf "%s\n", counter ; }'somedta.txt [using begin & end. begin is executed before input lines are read. END is executed after all input lines are read]
awk '{print FILENAME}'somedta.txt [FILENAME is a built in which stores the file name. This awk command will print the file name as many times as the number of lines in the file]
awk '{print NR, "has", NF, "fields" $1}'somedta.txt [NR is number of records/rows. NF is the number of fields/columns]
awk ' END { print "Number of records in file is: ", NR } 'somedta.txt [print total number of rows]
awk -F':' '{ print $1, $4 ;}' /etc/passwd [change input filed separater]
awk -F':' '$1 == "sahil" {print}' /etc/passwd [match user sahil in passwd file & print the matching line]
awk -F':' '/sahil/ {print "user", $1,"has shell", $7}' /etc/passwd [search for user sahil in passwd file & print user name & shell]
awk -F':' '{if($1 == "sahil") print ;}' passwd [does the same as above example but using if condition]
awk -F';' '{if ($1 == "12345") {$6 = 5000;} {OFS = ";"} {print $0;}}' file.txt[if 1st column has value 12345 then change value of 6th column to 5000]
awk ' BEGIN { FS=":" ; } { print $1, $4 ; } ' /etc/passwd [change input field separater 2nd method]
awk -F':' ' BEGIN { OFS="==>" ;} { print $1, $4 ;}' /etc/passwd [change input & output field separater]
user=root ; awk "/$user/ {print}" /etc/passwd [use shell variable in an awk statement]
awk 'BEGIN{ for(count=0;count<=5;count++){ print "sometext"} }' [for loop in awk. This prints the string sometext 5 times to stdout]
awk 'IGNORECASE = 1; /SaHil/ {print ;}' somedata.txt [do a case insensitive search with AWK]
echo "sahil" | awk '{print substr ($1,1,2)}' [use substring function in awk to chop off part of a string]
awk 'sub ("example.com", "test.com",$1)'somedta.txt [replace all occurances of example.com in 1st column with sahil.com]
"awk 'BEGIN {count=0}
{ if($1 == ""example.com"")
{count++}
if(count == 3)
{ sub(""example.com"",""UNIX"",$1)}}
{ print $0}' somedta.txt
"[replace 3rd occurance of example.com with UNIX]
awk '{if ($NR%2 ==0) {print $0, "\n TESTLINE"} else {print $0}}' somedta.txt [insert the word TESTLINE in a newline after every line]
awk 'NR >3 && NR < 6 {print}' somedta.txt[print line number 4 & 5 from the file]
awk '!/^$/' somedta.txt [remove blank lines from a file]
awk 'NR%2{printf "%s ",$0;next;}1' somedta.txt[join 2 line. replace newline with a space]
awk '{printf $0;printf " "}NR % 2 ==0 {print " "}' somedta.txt[join 2 line. replace newline with a space]
awk '{printf $0;printf " "}NR % 3 ==0 {print " "}' somedta.txt[join 3 line. replace newline with a space]
awk '{ print $NF }' somedta.txt [print last column in a file]
df -hTP | awk '{gsub(/%/,"")}1 {print $1,$6}' [Replace the % character with a space from df -h output]
df -hTP | awk '{gsub(/%/,"",$6)}1 {print $1,$6}' [Replace the % character with a space from df -h output limited to 6th column]

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...