Thursday, March 3, 2016

How to reset user accounts in Oracle 11g on Linux


# su - oracle

$ sqlplus /nolog

SQL> conn /as sysdba

SQL>select limit from dba_profiles where resource_name = 'PASSWORD_REUSE_MAX' AND profile = 'DEFAULT';       <--10...more secure
NOTE: Should be 10....If not, change 10 in the reset command to the output number.

----------------------------------------------------------------------

SQL>alter profile default limit password_reuse_max unlimited;

-----------------------------------------------------------------------
#To see locked or expired users;
SQL>select username, account_status from dba_users;

-----------------------
#To get their passwords;

SQL>select name, password from user$ where name = 'EGD_USER';
----------------------------------------------------------------------- 

#select name,password from user$ where name = 'EGD_USER';  <- Copy the output into the line below: 'ACTUALOUTPUT'

SQL>alter user EGD_USER identified by values '8467F6B603CA4542';   <---paste here
NOTE: This process can be repeated for additional accounts:
            IMINT, GISPROD, DCGS_USER, CMWREMOTE, GPT93


-------------------

SQL>select limit from dba_profiles where resource_name = 'PASSWORD_REUSE_MAX' AND

profile = 'DEFAULT';

NOTE: Should match what it was before you started.  This is a security feature and will be a finding

if not put back.


SQL> alter profile default limit password_reuse_max 10;

#verify the users were reset ;

SQL> select username, account_status from dba_users;


#if account is "locked" still, most times the password is just expired and the account will auto unlock once the password is changed. 

SQL> alter user EGD_USER account unlock;

 

#Exit disconnects you from Oracle DB.

SQL> exit

#One more “exit” takes you back to root prompt #

$ exit

Replace a String in Multiple Files in Linux Using Grep and Sed

I recently had to replace every occurrence of a certain word / string in a ton of files spanning multiple directories, and this is the quickest way I've found to do it. It uses grep to search for a certain word and if it find its it runs sed to replace the strings you want. Note: This will not work on windows systems

Basic Format

Search for a specific string to see if it exists;
grep -rl 'matchstring' /opt

to change the string;
grep -rl matchstring /opt | xargs sed -i 's/matchstring/matchstring2/g'

to verify strings have been changed run the first command;
grep -rl 'matchstring' /opt

Note: The forward slash '/' delimiter in the sed argument could also be a different delimiter (such as the pipe '|' character). The pipe delimiter might be useful when searching through a lot of html files if you didn't want to escape the forward slash, for instance.

matchstring is the string you want to match, e.g., "football" string1 would ideally be the same string as matchstring, as the matchstring in the grep command will pipe only files with matchstring in them to sed. string2 is the string that replace string1. There may be times when you want to use grep to find only files that have some matchstring and then replace on a different string in the file than matchstring. For example, maybe you have a lot of files and only want to only replace on files that have the matchstring of 'phonenumber' in them, and then replace '555-5555' with '555-1337'. Not that great of an example (you could just search files for that phone number instead of the string 'phonenumber'), but your imagination is probably better than mine.

Example
grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

This will search for the string 'windows' in all files relative to the current directory and replace 'windows' with 'linux' for each occurrence of the string in each file.

Monday, February 29, 2016

Linux Hardening Guide with OpenSCAP 1.2

Install the latest version of openSCAP (v1.2 at the time of writing: http://scap.nist.gov/revision/1.2/index.html#xccdf)

#yum install openscap openscap-utils scap-security-guide

# oscap xccdf eval --profile stig-rhel6-server-upstream --results results.xml --report report.html \
  --cpe /usr/share/xml/scap/ssg/content/ssg-rhel6-cpe-dictionary.xml \
  /usr/share/xml/scap/ssg/content/ssg-rhel6-xccdf.xml

----To remediate some of the findings, use the results.xml file and rerun the scan with the remediate option.------

#oscap xccdf remediate --results results.xml results.xml

--------These are findings that had to be remediated manually.----------------------
## Item: Set Daemon Umask - Failed
# cp -p /etc/init.d/functions{,.preSTIG}
#  var_umask_for_daemons="027" \
   grep -q ^umask /etc/init.d/functions && \
   sed -i "s/umask.*/umask $var_umask_for_daemons/g" /etc/init.d/functions
# if ! [ $? -eq 0 ]; then \
  echo "umask $var_umask_for_daemons" >> /etc/init.d/functions \
  fi
## Note - still failed in a subsequent scan, so manually modified /etc/init.d/functions and set umask to 027

## Item: Enable ExecShield - Unknown (failed)
# if grep --silent ^kernel.exec-shield /etc/sysctl.conf ; then
    sed -i 's/^kernel.exec-shield.*/kernel.exec-shield = 1/g' /etc/sysctl.conf;
  else
    echo "" >> /etc/sysctl.conf;
    echo "# Set kernel.exec-shield to 1 per STIG security requirements" >> /etc/sysctl.conf;
    echo "kernel.exec-shield = 1" >> /etc/sysctl.conf;
  fi

## Item: Enable Randomized Layout of Virtual Address Space - Unknown (failed)
# if grep --silent ^kernel.randomize_va_space /etc/sysctl.conf ; then
    sed -i 's/^kernel.randomize_va_space.*/kernel.randomize_va_space = 2/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set kernel.randomize_va_space to 2 per STIG security requirements" >> /etc/sysctl.conf
    echo "kernel.randomize_va_space = 2" >> /etc/sysctl.conf
  fi

## Item: Ensure No Device Files are Unlabeled by SELinux - Fail (False Positive) Manually verified
# find /dev -context "*:*:unlabeled_t:*" -ls
# or run this command
# find /dev -context *:device_t:* \( -type c -o -type b \) -printf "%p %Z\n"

## Item: Ensure that System Accounts Do Not Run a Shell Upon Login - Failed (exceptions below)
# cat /etc/passwd |grep -v nologin
% The following exceptions are noted
sync:x:5:0:sync:/sbin:/bin/sync                [<- appropriate OS shell for this user]
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown   [<- appropriate OS shell for this user]
halt:x:7:0:halt:/sbin:/sbin/halt               [<- appropriate OS shell for this user]
postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql:/bin/bash  [<- appropriate OS shell for this user]
amandabackup:x:33:6:Amanda user:/var/lib/amanda:/bin/bash    [<- appropriate OS shell for this user]
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash          [<- appropriate OS shell for this user]
##Disable xguest account
# vi /etc/passwd
% set shell for xguest user to /sbin/nologin
## Item: Verify All Account Password Hashes are Shadowed - Fail (False Positive) Manually verified
# awk -F: '$2 !~ /^x$/ {print}' /etc/passwd
## Item: All GIDs referenced in /etc/passwd must be defined in /etc/group - notchecked (passed) Manually verified
# awk -F: '{print $4}' /etc/passwd |while read gid
  do
    getent group $gid > /dev/null || echo "GID: $gid not found - NEEDS FIX"
  done
## Alternate check - see if results mention bad or invalid group settings
# pwck -r
# grpck -r

## Item: Ensure All Accounts on the System Have Unique Names - notchecked (passed) Manually verify
# pwck -r

## Item: Assign Expiration Date to Temporary Accounts - notchecked (passed) Manually verify
# awk -F: '$2 !~/[!*]/ {print $1}' /etc/shadow | egrep -v root | while read user
  do
    echo "User: $user"
    chage -l $user; done
  done
# date -d "1 year"
# chage -E '2016-10-12' ciadmin

## Item: Set last Logon/Access Notification - fail (passed)
# vi /etc/pam.d/system-auth
#   session       required     pam_lastlog.so showfailed

## Item: Set Password to Maximum of Three Consecutive Repeating Characters - Failed (passed)
# cp -p /etc/pam.d/system-auth-ac{,.preSTIG}
# var_password_pam_maxrepeat="3"
if grep -q "maxrepeat=" /etc/pam.d/system-auth; then
    sed -i --follow-symlink "s/\(maxrepeat *= *\).*/\1$var_password_pam_maxrepeat/" /etc/pam.d/system-auth
else
    sed -i --follow-symlink "/pam_cracklib.so/ s/$/ maxrepeat=$var_password_pam_maxrepeat/" /etc/pam.d/system-auth
fi
# or manually set "/etc/pam.d/system-auth-ac"
password    requisite     pam_cracklib.so try_first_pass retry=3 type= maxrepeat=3

## Item: Ensure no world-writable files exist
# find / -perm -2 ! -type l -ls

## Item: Ensure All files are owned by a User - Failed (passes) Manually set user
# find / -nouser
# chown root /"directory or file to set"
## Item: Ensure All files are owned by a Group - Failed (passes) Manually set group
# find / -nogroup
# chgrp root /"directory or file to set"
## Item: Ensure World-Wide directories are owned by a system account
# find (/dev/sda1) -xdev -type d -perm 0002 -uid +500 -print  (partition to scan) - Failed (passes) Manually verify

## Item: Set Lockout Time For Failed Password Attempts - CCE-27110-6 - Failed (passed)
## Item: Set Interval For Counting Failed Password Attempts - CCE-27215-3 - Failed (passed)
# cp -p /etc/pam.d/password-auth-ac{,.preSTIG}
# vi /etc/pam.d/password-auth-ac  (<- add section for unlock_time and fail_interval)
--
auth        required      pam_faillock.so preauth silent deny=3 unlock_time=604800 fail_interval=900
auth        sufficient    pam_unix.so  try_first_pass
auth        [default=die] pam_faillock.so authfail deny=3 unlock_time=604800 fail_interval=900
--
# vi /etc/pam.d/system-auth-ac (<- add section for unlock_time and fail_interval)
--
auth        required      pam_faillock.so preauth silent deny=3 unlock_time=604800 fail_interval=900
auth        sufficient    pam_unix.so  try_first_pass
auth        [default=die] pam_faillock.so authfail deny=3 unlock_time=604800 fail_interval=900
--

## Item: Set Boot Loader Password - CCE-26911-8 - Failed (passed)
# grub-crypt --sha-512
#    Password:(<- use root password here)
# cp -p /etc/grub.conf{,.preSTIG}
# vi /etc/grub.conf
-----modify grub.conf by adding password line-----
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
password --encrypted $6$ZpeyOFUd2tSpcvW9$kK..<hash-stuff-here>...
--

## Item: Disable Ctrl-Alt-Del Reboot Activation - CCE-27567-7 - Failed (passed)
# vi /etc/init/control-alt-delete.conf
--
exec /usr/bin/logger -p security.info "Control-Alt-Delete pressed"
--

## Item: Result for Disable Interactive Boot - CCE-27043-9 - Failed (passed)
# cp -p /etc/sysconfig/init{,.preSTIG}
# grep -q ^PROMPT /etc/sysconfig/init && \
  sed -i "s/PROMPT.*/PROMPT=no/g" /etc/sysconfig/init
  if ! [ $? -eq 0 ]; then
    echo "PROMPT=no" >> /etc/sysconfig/init
  fi

## Item: Set GNOME Login Inactivity Timeout - CCE-26828-4 - Unknown (passed)
# inactivity_timeout_value="15"
# gconftool-2 --direct \
            --config-source "xml:readwrite:/etc/gconf/gconf.xml.mandatory" \
            --type int \
            --set /desktop/gnome/session/idle_delay ${inactivity_timeout_value}

## Item: GNOME Desktop Screensaver Mandatory Use - CCE-26600-7 - Unknown (passed)
# gconftool-2 --direct \
            --config-source "xml:readwrite:/etc/gconf/gconf.xml.mandatory" \
            --type bool \
            --set /apps/gnome-screensaver/idle_activation_enabled true

## Item: Enable Screen Lock Activation After Idle Period - CCE-26235-2 - Unknown (passed)
# gconftool-2 --direct \
            --config-source "xml:readwrite:/etc/gconf/gconf.xml.mandatory" \
            --type bool \
            --set /apps/gnome-screensaver/lock_enabled true

## Item: Implement Blank Screensaver - CCE-26638-7 - Unknown (passed)
# gconftool-2 --direct \
            --config-source "xml:readwrite:/etc/gconf/gconf.xml.mandatory" \
            --type string \
            --set /apps/gnome-screensaver/mode blank-only

## Item: Enable Smart Card Login - CCE-27440-7 - Failed (failed)
% Not resolved; no Smart Card readers on system

## Item: Enable GUI Warning Banner - CCE-27195-7 - Unknown (passed)
# gconftool-2 --direct \
            --config-source "xml:readwrite:/etc/gconf/gconf.xml.mandatory" \
            --type bool \
            --set /apps/gdm/simple-greeter/banner_message_enable true

## Item: Set GUI Warning Banner Text - CCE-27017-3 - Unknown (passed)
# login_banner_text="You[\s\n]+are[\s\n]+accessing[\s\n]+a[\s\n]+U.S.[\s\n]+Government[\s\n]+\(USG\)[\s\n]+Information[\s\n]+System[\s\n]+\(IS\)[\s\n]+that[\s\n]+is[\s\n]+provided[\s\n]+for[\s\n]+USG-authorized[\s\n]+use[\s\n]+only.[\s\n]*By[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+\(which[\s\n]+includes[\s\n]+any[\s\n]+device[\s\n]+attached[\s\n]+to[\s\n]+this[\s\n]+IS\),[\s\n]+you[\s\n]+consent[\s\n]+to[\s\n]+the[\s\n]+following[\s\n]+conditions\:[\s\n]*-[\s\n]*The[\s\n]+USG[\s\n]+routinely[\s\n]+intercepts[\s\n]+and[\s\n]+monitors[\s\n]+communications[\s\n]+on[\s\n]+this[\s\n]+IS[\s\n]+for[\s\n]+purposes[\s\n]+including,[\s\n]+but[\s\n]+not[\s\n]+limited[\s\n]+to,[\s\n]+penetration[\s\n]+testing,[\s\n]+COMSEC[\s\n]+monitoring,[\s\n]+network[\s\n]+operations[\s\n]+and[\s\n]+defense,[\s\n]+personnel[\s\n]+misconduct[\s\n]+\(PM\),[\s\n]+law[\s\n]+enforcement[\s\n]+\(LE\),[\s\n]+and[\s\n]+counterintelligence[\s\n]+\(CI\)[\s\n]+investigations.[\s\n]*-[\s\n]*At[\s\n]+any[\s\n]+time,[\s\n]+the[\s\n]+USG[\s\n]+may[\s\n]+inspect[\s\n]+and[\s\n]+seize[\s\n]+data[\s\n]+stored[\s\n]+on[\s\n]+this[\s\n]+IS.[\s\n]*-[\s\n]*Communications[\s\n]+using,[\s\n]+or[\s\n]+data[\s\n]+stored[\s\n]+on,[\s\n]+this[\s\n]+IS[\s\n]+are[\s\n]+not[\s\n]+private,[\s\n]+are[\s\n]+subject[\s\n]+to[\s\n]+routine[\s\n]+monitoring,[\s\n]+interception,[\s\n]+and[\s\n]+search,[\s\n]+and[\s\n]+may[\s\n]+be[\s\n]+disclosed[\s\n]+or[\s\n]+used[\s\n]+for[\s\n]+any[\s\n]+USG-authorized[\s\n]+purpose.[\s\n]*-[\s\n]*This[\s\n]+IS[\s\n]+includes[\s\n]+security[\s\n]+measures[\s\n]+\(e.g.,[\s\n]+authentication[\s\n]+and[\s\n]+access[\s\n]+controls\)[\s\n]+to[\s\n]+protect[\s\n]+USG[\s\n]+interests[\s\n]+--[\s\n]+not[\s\n]+for[\s\n]+your[\s\n]+personal[\s\n]+benefit[\s\n]+or[\s\n]+privacy.[\s\n]*-[\s\n]*Notwithstanding[\s\n]+the[\s\n]+above,[\s\n]+using[\s\n]+this[\s\n]+IS[\s\n]+does[\s\n]+not[\s\n]+constitute[\s\n]+consent[\s\n]+to[\s\n]+PM,[\s\n]+LE[\s\n]+or[\s\n]+CI[\s\n]+investigative[\s\n]+searching[\s\n]+or[\s\n]+monitoring[\s\n]+of[\s\n]+the[\s\n]+content[\s\n]+of[\s\n]+privileged[\s\n]+communications,[\s\n]+or[\s\n]+work[\s\n]+product,[\s\n]+related[\s\n]+to[\s\n]+personal[\s\n]+representation[\s\n]+or[\s\n]+services[\s\n]+by[\s\n]+attorneys,[\s\n]+psychotherapists,[\s\n]+or[\s\n]+clergy,[\s\n]+and[\s\n]+their[\s\n]+assistants.[\s\n]+Such[\s\n]+communications[\s\n]+and[\s\n]+work[\s\n]+product[\s\n]+are[\s\n]+private[\s\n]+and[\s\n]+confidential.[\s\n]+See[\s\n]+User[\s\n]+Agreement[\s\n]+for[\s\n]+details."
banner_expanded=$(echo "$login_banner_text" | sed 's/\[\\s\\n\][*+]/ /g;s/\\//g;')
# Set the text shown by the GNOME Display Manager in the login screen
gconftool-2 --direct \
            --config-source "xml:readwrite:/etc/gconf/gconf.xml.mandatory" \
            --type string \
            --set /apps/gdm/simple-greeter/banner_message_text "${banner_expanded}"

## Item: Disable Kernel Parameter for Sending ICMP Redirects by Default - CCE-27001-7 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.default.send_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.default.send_redirects.*/net.ipv4.conf.default.send_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.default.send_redirects to 0 per STIG security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.default.send_redirects = 0" >> /etc/sysctl.conf
  fi

## Item: Disable Kernel Parameter for Sending ICMP Redirects for All Interfaces - CCE-27004-1 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.all.send_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.all.send_redirects.*/net.ipv4.conf.all.send_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.all.send_redirects to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.all.send_redirects = 0" >> /etc/sysctl.conf
  fi

## Disable Kernel Parameter for IP Forwarding - CCE-26866-4 - Unknownn (passed)
% Note: no fix on this was needed
# if grep --silent ^net.ipv4.ip_forward /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.ip_forward.*/net.ipv4.ip_forward = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.ip_forward to 0 per STIG security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.ip_forward = 0" >> /etc/sysctl.conf
  fi
## Need to set sysctl as well as changing the sysctl.conf (only read at startup)
# sysctl -w net.ipv4.ip_forward=0

## Item: Disable Kernel Parameter for Accepting Source-Routed Packets for All Interfaces - CCE-27037-1 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.all.accept_source_route /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.all.accept_source_route.*/net.ipv4.conf.all.accept_source_route = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.all.accept_source_route to 0 per STIG security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.all.accept_source_route = 0" >> /etc/sysctl.conf
  fi

## Item: Disable Kernel Parameter for Accepting ICMP Redirects for All Interfaces - CCE-27027-2 - Unknownn (passed)
# if grep --silent ^net.ipv4.conf.all.accept_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.all.accept_redirects.*/net.ipv4.conf.all.accept_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.all.accept_redirects to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.all.accept_redirects = 0" >> /etc/sysctl.conf
  fi

## Item: Disable Kernel Parameter for Accepting Secure Redirects for All Interfaces - CCE-26854-0 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.all.secure_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.all.secure_redirects.*/net.ipv4.conf.all.secure_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.all.secure_redirects to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.all.secure_redirects = 0" >> /etc/sysctl.conf
  fi

## Item: Enable Kernel Parameter to Log Martian Packets - CCE-27066-0 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.all.log_martians /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.all.log_martians.*/net.ipv4.conf.all.log_martians = 1/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.all.log_martians to 1 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.all.log_martians = 1" >> /etc/sysctl.conf
  fi

## Item: Disable Kernel Parameter for Accepting Source-Routed Packets By Default - CCE-26983-7 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.default.accept_source_route /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.default.accept_source_route.*/net.ipv4.conf.default.accept_source_route = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.default.accept_source_route to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.default.accept_source_route = 0" >> /etc/sysctl.conf
  fi

## Item: Disable Kernel Parameter for Accepting ICMP Redirects By Default - CCE-27015-7 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.default.accept_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.default.accept_redirects.*/net.ipv4.conf.default.accept_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.default.accept_redirects to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.default.accept_redirects = 0" >> /etc/sysctl.conf
  fi

## Item: Disable Kernel Parameter for Accepting Secure Redirects By Default - CCE-26831-8 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.default.secure_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.default.secure_redirects.*/net.ipv4.conf.default.secure_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.default.secure_redirects to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.default.secure_redirects = 0" >> /etc/sysctl.conf
  fi

## Item: Enable Kernel Parameter to Ignore ICMP Broadcast Echo Requests - CCE-26883-9 - Unknown (passed)
# if grep --silent ^net.ipv4.icmp_echo_ignore_broadcasts /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.icmp_echo_ignore_broadcasts.*/net.ipv4.icmp_echo_ignore_broadcasts = 1/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.icmp_echo_ignore_broadcasts to 1 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.icmp_echo_ignore_broadcasts = 1" >> /etc/sysctl.conf
  fi

## Item:  Enable Kernel Parameter to Ignore Bogus ICMP Error Responses - CCE-26993-6 - Unknown (passed)
# if grep --silent ^net.ipv4.icmp_ignore_bogus_error_responses /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.icmp_ignore_bogus_error_responses.*/net.ipv4.icmp_ignore_bogus_error_responses = 1/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.icmp_ignore_bogus_error_responses to 1 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.icmp_ignore_bogus_error_responses = 1" >> /etc/sysctl.conf
  fi

## Item: Enable Kernel Parameter to Use TCP Syncookies - CCE-27053-8 - Unknown (passed)
# if grep --silent ^net.ipv4.tcp_syncookies /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.tcp_syncookies.*/net.ipv4.tcp_syncookies = 1/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.tcp_syncookies to 1 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_syncookies = 1" >> /etc/sysctl.conf
  fi

## Item: Enable Kernel Parameter to Use Reverse Path Filtering for All Interfaces - CCE-26979-5 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.all.rp_filter /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.all.rp_filter.*/net.ipv4.conf.all.rp_filter = 1/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.all.rp_filter to 1 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.all.rp_filter = 1" >> /etc/sysctl.conf
  fi

## Item: Enable Kernel Parameter to Use Reverse Path Filtering by Default - CCE-26915-9 - Unknown (passed)
# if grep --silent ^net.ipv4.conf.default.rp_filter /etc/sysctl.conf ; then
    sed -i 's/^net.ipv4.conf.default.rp_filter.*/net.ipv4.conf.default.rp_filter = 1/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv4.conf.default.rp_filter to 1 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv4.conf.default.rp_filter = 1" >> /etc/sysctl.conf
  fi

## Item: Disable Accepting IPv6 Redirects - CCE-27166-8 - Unknown (passed)
# if grep --silent ^net.ipv6.conf.default.accept_redirects /etc/sysctl.conf ; then
    sed -i 's/^net.ipv6.conf.default.accept_redirects.*/net.ipv6.conf.default.accept_redirects = 0/g' /etc/sysctl.conf
  else
    echo "" >> /etc/sysctl.conf
    echo "# Set net.ipv6.conf.default.accept_redirects to 0 per security requirements" >> /etc/sysctl.conf
    echo "net.ipv6.conf.default.accept_redirects = 0" >> /etc/sysctl.conf
  fi
## The above setting does not work - instead disable ipv6
# in /etc/sysconfig/network: NETWORKING_IPV6=no
# in /etc/sysconfig/network-scripts/ifcfg-eth#: IPV6INIT=no
# Disable ip6tables: chkconfig --level 345 ip6tables off
## Item: Disable DCCP Support - CCE-26448-1 - Failed (passed)
# echo "install dccp /bin/false" > /etc/modprobe.d/dccp.conf
## Item: Disable SCTP Support - CCE-26410-1 - Failed (passed)
# echo "install sctp /bin/false" > /etc/modprobe.d/sctp.conf
## Item: Disable RDS Support - CCE-26239-4 - Failed (passed)
# echo "install rds /bin/false" > /etc/modprobe.d/rds.conf
## Item:  Disable TIPC Support - CCE-26696-5 - Failed (passed)
# echo "install tipc /bin/false" > /etc/modprobe.d/tipc.conf
## Item: Ensure Log Files Are Owned By Appropriate User - CCE-26812-8 - Fail (passed)
# chown root /var/log/*
% The following exceptions are noted
ntpstats/ user = ntp      [<-- by default, ntpd runs as ntp:ntp, see /etc/sysconfig/ntpd]
radius/   user = radiusd  [<-- by default, radiusd runs as radiusd:radiusd, see /etc/raddb/radiusd.conf]
## Item: Ensure Log Files Are Owned By Appropriate Group - CCE-26821-9 - Fail (passed)
# chgrp root /var/log/*
% The following exceptions are noted
ntpstats/ group = ntp      [<-- by default, ntpd runs as ntp:ntp, see /etc/sysconfig/ntpd]
radius/   group = radiusd  [<-- by default, radiusd runs as radiusd:radiusd, see /etc/raddb/radiusd.conf]
btmp      group = utmp     [<-- by default, not rwx by group other]
gdm/      group = gdm      [<-- by default, not rwx by group other]
wtmp      group = utmp     [<-- by default, not wx by group other]
## Item: Ensure System Log Files Have Correct Permissions - CCE-27190-8 - Fail (passed)
# find /var/log -type d -exec chmod 700 {} \;
# find /var/log -type f -exec chmod 600 {} \;
## Item: Record attempts to alter time through adjtimex - CCE-26242-8 - Unknown (passed)
## Item: Record attempts to alter time through settimeofday - CCE-27203-9 - Unknown (passed)
## Item: Record Attempts to Alter Time Through stime - CCE-27169-2 - Unknown (passed)
## Item: Record Attempts to Alter Time Through clock_settime - CCE-27170-0 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - chmod - CCE-26280-8 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - chown - CCE-27173-4 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - fchmod - CCE-27174-2 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - fchmodat - CCE-27175-9 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - fchown - CCE-27177-5 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - fchownat - CCE-27178-3 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - fremovexattr - CCE-27179-1 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - fsetxattr - CCE-27180-9 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - lchown - CCE-27181-7 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - lremovexattr - CCE-27182-5 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - lsetxattr - CCE-27183-3 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - removexattr - CCE-27184-1 - Unknown (passed)
## Item: Record Events that Modify the System's Discretionary Access Controls - setxattr - CCE-27185-8 - Unknown (passed)
# cd /etc/audit
# rm {rules.d,}/audit.rules
# cp /usr/share/doc/audit-2.3.7/stig.rules audit.rules
# Item: Ensure auditd Collects Information on Kernel Module Loading and Unloading - CCE-26611-4 - Fail (passed)
# vi /etc/audit/audit.rules  (<- uncomment the lines below)
--
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
-a always,exit -F arch=b32 -S init_module -S delete_module -k modules
-a always,exit -F arch=b64 -S init_module -S delete_module -k modules
--
##
# vi /etc/audit/audit.rules (<- add rmdir to the lines below)
--
-a always,exit -F arch=b32 -S rmdir -S unlink -S unlinkat -S rename -S renameat -F auid>=500 -F auid!=4294967295 -k delete
-a always,exit -F arch=b64 -S rmdir -S unlink -S unlinkat -S rename -S renameat -F auid>=500 -F auid!=4294967295 -k delete
--
## Item: Ensure auditd Collects Information on the Use of Privileged Commands - CCE-26457-2 - Fail (passed)
# fs="/ /boot /export/home /tmp /usr /var /var/log /var/log/audit"
# find $fs -xdev -type f -perm -4000 -o -type f -perm -2000  > /tmp/suid-files.txt 2>/dev/null
# for i in $(cat /tmp/suid-files.txt)
  do
    echo "-a always,exit -F path=$i -F perm=x -F auid>=500 -F auid!=4294967295 -k privileged" >> /etc/audit/rules.d/suid-files.rules
  done

## Item: Uninstall Sendmail Package - CCE-27515-6 - Fail (passed)
# yum erase sendmail

## Item: Configure LDAP Client to Use TLS For All Transactions - CCE-26690-8 - Fail (passed)
# cp -p /etc/pam_ldap.conf{,.preSTIG}
# vi /etc/pam_ldap.conf
--
ssl start_tls  (<- uncomment line)
--
## Item: Configure Certificate Directives for LDAP Use of TLS - CCE-27189-0 - Fail (passed)
# vi /etc/pam_ldap.conf
--
tls_cacertdir /etc/ssl/certs (<- uncomment line)
--
## Item: Enable Logging of All FTP Transactions - CCE-27142-9 - Fail (passed)
# cp -p /etc/vsftpd/vsftpd.conf{,.preSTIG}
# vi /etc/vsftpd/vsftpd.conf
--
xferlog_std_format=NO  (<- changed from YES)
log_ftp_protocol=YES (<- added at end of file)
--
## Item:  Create Warning Banners for All FTP Users - CCE-27145-2 - Fail (passed)
# vi /etc/vsftpd/vsftpd.conf
--
banner_file=/etc/issue (<- added at end of file)
--
## Item: Configure SNMP Service to Use Only SNMPv3 or Newer - CCE-27365-6 - Fail (passed)
## Item: Ensure Default Password Is Not Used - CCE-27593-3 - Fail (passed)
# cp -p /etc/snmp/snmpd.conf{,.preSTIG}
# vi /etc/snmp/snmpd.conf
--
# com2sec notConfigUser  default       public (<- comment line out)
--
## Item: Add noexec Option to Removable Media Partitions - CCE-27196-5 - Fail (passed)
# vi /etc/fstab
/dev/cdrom         /media/cdrom         iso9660 noauto,owner,ro,noexec 0 0

# vi /etc/auto.misc
cd    -fstype=iso9660,ro,nosuid,nodev,noexec  :/dev/cdrom
--
## Item: Install Intrusion Detection Software - CCE-27409-2 - Not Checked (passed)
# yum install dialog.x86_64
# rpm -Uvh rsiide-for-linux-srv-9.1.0.0-1.0.noarch.rpm
##Add the following to /etc/audit/audit.rules
-w /sbin/shutdown -p x
-w /sbin/init -p x
##Fix selinux bug with log rotation
#semodule -i /etc/RSIIDE_Config/RSIIDE_SELINUX_RHEL6_NFS.pp
#semodule -i /etc/RSIIDE_Config/RSIIDE_SELINUX_RHEL6_DEFAULT.pp
## Add the following to /Audit/config/linux.systems.txt localhost
## Modify /Audit/config/rsiide.linux.conf
wh_starting_hour:5
wh_ending_hour:20
cli_INSTALL Clamav installed (yes or no):no
uvd_PATH to binary:/usr/local/uvscan
uvi_INSTALL Mcafee installed (yes or no):yes

## Item: Verify that System Executables Have Root Ownership - CCE-27623-8 - Fail (passed)
## cd to each directory (/bin, /usr/bin, /usr/local/bin, /sbin/usr/sbin, /usr/local/sbin) and run the following:
# find . \! -user root -print
% The following exceptions are noted
/usr/sbin RPMs owned by  amandabackup   [<-- by default, amandabackup is a service account with no password set]

## Item: Uninstall xinetd Package - CCE-27005-8 - Fail (mitigated)
## Verify xinetd is chkconfig off for all runlevels
# chkconfig --list |grep xinetd
## chkconfig xinetd for all runlevels
# chkconfig --level 0123456 xinetd off
# Verify all xinetd services (/etc/xinetd.d) have setting "disable = yes"

## Item: Uninstall tftp-server Package - CCE-26946-4 - Fail (mitigated)
## Verify /etc/xinetd.d/tftp has setting "disable = yes"

## Set the default run level to 3 (no X11)
# vi /etc/inittab
  id:3:initdefault:


## Disable X11 by setting the default run level to 3 (no X11)
# vi /etc/inittab
  id:3:initdefault:

## Run the following command to see what has changed
# rpm -Va |grep '^..5'

Monday, October 19, 2015

Bash Shell PS1: Examples to customize your Linux Prompt

1. Display username, hostname and current working directory in the prompt

The PS1 in this example displays the following three information in the prompt:
  • \u – Username
  • \h – Hostname
  • \w – Full path of the current working directory
-bash-3.2$ export PS1="\u@\h \w> "

user@hostname ~> cd /etc/mail

user@hostname /etc/mail>

2. Display current time in the prompt

In the PS1 environment variable, you can directly execute any Linux command, by specifying in the format $(linux_command). In the following example, the command $(date) is executed to display the current time inside the prompt.
user@hostname ~> export PS1="\u@\h [\$(date +%k:%M:%S)]> "

user@hostname [11:09:56]>

You can also use \t to display the current time in the hh:mm:ss format as shown below:
user@hostname ~> export PS1="\u@\h [\t]> "

user@hostname [12:42:55]>

You can also use \@ to display the current time in 12-hour am/pm format as shown below:
user@hostname ~> export PS1="[\@] \u@\h> "

[04:12 PM] user@hostname >

3. Display output of any Linux command in the prompt

You can display output of any Linux command in the prompt. The following example displays three items separated by | (pipe) in the command prompt:
  • \!: The history number of the command
  • \h: hostname
  • $kernel_version: The output of the uname -r command from $kernel_version variable
  • \$?: Status of the last command
user@hostname ~> kernel_version=$(uname -r)
user@hostname ~> export PS1="\!|\h|$kernel_version|\$?> "

473|hostname|2.6.25-14.fc9.i686|0>

4. Change foreground color of the prompt

Display prompt in blue color, along with username, host and current directory information.

$ export PS1="\e[0;34m\u@\h \w> \e[m"
[Note: For light blue prompt]

$ export PS1="\e[1;34m\u@\h \w> \e[m"
[Note: For dark blue prompt]
  • \e[ – Indicates the beginning of color prompt
  • x;ym – Indicates color code. Use the color code values mentioned below.
  • \e[m – indicates the end of color prompt
Color Code Table:
Black 0;30
Blue 0;34
Green 0;32
Cyan 0;36
Red 0;31
Purple 0;35
Brown 0;33
[Note: Replace 0 with 1 for dark color]

Make the color change permanent by adding the following lines to .bash_profile or .bashrc
STARTCOLOR='\e[0;34m';
ENDCOLOR="\e[0m"
export PS1="$STARTCOLOR\u@\h \w> $ENDCOLOR"

5. Change background color of the prompt

Change the background color by specifying \e[{code}m in the PS1 prompt as shown below.
$ export PS1="\e[47m\u@\h \w> \e[m"
[Note: For Light Gray background]

Combination of background and foreground
export PS1="\e[0;34m\e[47m\u@\h \w> \e[m"
[Note: For Light Blue foreground and Light Gray background]

Add the following to the .bash_profile or .bashrc to make the above background and foreground color permanent.
STARTFGCOLOR='\e[0;34m';
STARTBGCOLOR="\e[47m"
ENDCOLOR="\e[0m"
export PS1="$STARTFGCOLOR$STARTBGCOLOR\u@\h \w> $ENDCOLOR"
Play around by using the following background color and choose the one that suites your taste:
  • \e[40m
  • \e[41m
  • \e[42m
  • \e[43m
  • \e[44m
  • \e[45m
  • \e[46m
  • \e[47m

6. Display multiple colors in the prompt

You can also display multiple colors in the same prompt. Add the following function to .bash_profile
function prompt {
  local BLUE="\[\033[0;34m\]"
  local DARK_BLUE="\[\033[1;34m\]"
  local RED="\[\033[0;31m\]"
  local DARK_RED="\[\033[1;31m\]"
  local NO_COLOR="\[\033[0m\]"
  case $TERM in
    xterm*|rxvt*)
      TITLEBAR='\[\033]0;\u@\h:\w\007\]'
      ;;
    *)
      TITLEBAR=""
      ;;
  esac
  PS1="\u@\h [\t]> "
  PS1="${TITLEBAR}\
  $BLUE\u@\h $RED[\t]>$NO_COLOR "
  PS2='continue-> '
  PS4='$0.$LINENO+ '
}
You can re-login for the changes to take effect or source the .bash_profile as shown below.
$. ./.bash_profile
$ prompt

user@hostname [13:02:13]>

7. Change the prompt color using tput

You can also change color of the PS1 prompt using tput as shown below:
$ export PS1="\[$(tput bold)$(tput setb 4)$(tput setaf 7)\]\u@\h:\w $ \[$(tput sgr0)\]"
tput Color Capabilities:
  • tput setab [1-7] – Set a background color using ANSI escape
  • tput setb [1-7] – Set a background color
  • tput setaf [1-7] – Set a foreground color using ANSI escape
  • tput setf [1-7] – Set a foreground color
tput Text Mode Capabilities:
  • tput bold – Set bold mode
  • tput dim – turn on half-bright mode
  • tput smul – begin underline mode
  • tput rmul – exit underline mode
  • tput rev – Turn on reverse mode
  • tput smso – Enter standout mode (bold on rxvt)
  • tput rmso – Exit standout mode
  • tput sgr0 – Turn off all attributes
Color Code for tput:
  • 0 – Black
  • 1 – Red
  • 2 – Green
  • 3 – Yellow
  • 4 – Blue
  • 5 – Magenta
  • 6 – Cyan
  • 7 – White

8. Create your own prompt using the available codes for PS1 variable

Use the following codes and create your own personal PS1 Linux prompt that is functional and suites your taste. Which code from this list will be very helpful for daily use? Leave your comment and let me know what PS1 code you’ve used for your Linux prompt.
  • \a an ASCII bell character (07)
  • \d the date in “Weekday Month Date” format (e.g., “Tue May 26″)
  • \D{format} – the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required
  • \e an ASCII escape character (033)
  • \h the hostname up to the first part
  • \H the hostname
  • \j the number of jobs currently managed by the shell
  • \l the basename of the shell’s terminal device name
  • \n newline
  • \r carriage return
  • \s the name of the shell, the basename of $0 (the portion following the final slash)
  • \t the current time in 24-hour HH:MM:SS format
  • \T the current time in 12-hour HH:MM:SS format
  • \@ the current time in 12-hour am/pm format
  • \A the current time in 24-hour HH:MM format
  • \u the username of the current user
  • \v the version of bash (e.g., 2.00)
  • \V the release of bash, version + patch level (e.g., 2.00.0)
  • \w the current working directory, with $HOME abbreviated with a tilde
  • \W the basename of the current working directory, with $HOME abbreviated with a tilde
  • \! the history number of this command
  • \# the command number of this command
  • \$ if the effective UID is 0, a #, otherwise a $
  • \nnn the character corresponding to the octal number nnn
  • \\ a backslash
  • \[ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
  • \] end a sequence of non-printing character

9. Use bash shell function inside PS1 variable

You can also invoke a bash shell function in the PS1 as shown below.
user@hostname ~> function httpdcount {
>  ps aux | grep httpd | grep -v grep | wc -l
> }

user@hostname ~> export PS1="\u@\h [`httpdcount`]> "

user@hostname [12]> [Note: This displays the total number of running httpd processes]

You can add the following line to .bash_profile or .bashrc to make this change permanent:
function httpdcount {
  ps aux | grep httpd | grep -v grep | wc -l
}
export PS1='\u@\h [`httpdcount`]> '

10. Use shell script inside PS1 variable

You can also invoke a shell script inside the PS1 variable. In the example below, the ~/bin/totalfilesize.sh, which calculates the total filesize of the current directory, is invoked inside the PS1 variable.

user@hostname  ~> cat ~/bin/totalfilesize.sh

for filesize in $(ls -l . | grep "^-" | awk '{print $5}')
do
  let totalsize=$totalsize+$filesize
done
echo -n "$totalsize"

user@hostname  ~> export PATH=$PATH:~/bin
user@hostname ~> export PS1="\u@\h [\$(totalfilesize.sh) bytes]> "
user@hostname [534 bytes]> cd /etc/mail

user@hostname [167997 bytes]> [Note: This executes the totalfilesize.sh to display the total file size of the current directory in the PS1 prompt]

Friday, October 16, 2015

How to Increase the size of a Linux LVM by expanding the virtual machine disk

This post will cover how to increase the disk space for a VMware virtual machine running Linux that is using logical volume manager (LVM). Firstly we will be increasing the size of the actual disk on the VMware virtual machine, so at the hardware level – this is the VM’s .vmdk file. Once this is complete we will get into the virtual machine and make the necessary changes through the operating system in order to take advantage of the additional space that has been provided by the hard drive being extended. This will involve creating a new partition with the new space, expanding the volume group and logical group, then finally resizing the file system.

Throughout my examples I will be working with a VMware virtual machine running Red Hat 6, this was set up with a 20gb disk and we will be increasing it by 10gb for a total final size of 30gb.

Identifying the partition type

As this method focuses on working with LVM, we will first confirm that our partition type is actually Linux LVM by running the below command.
fdisk -l

fdisk
As you can see in the above image /dev/sda5 is listed as “Linux LVM” and it has the ID of 8e. The 8e hex code shows that it is a Linux LVM, while 83 shows a Linux native partition. Now that we have confirmed we are working with an LVM we can continue. For increasing the size of a Linux native partition (hex code 83).

Below is the disk information showing that our initial setup only has the one 20gb disk currently, which is under the logical volume named /dev/mapper/Mega-root – this is what we will be expanding with the new disk.

disk free

Note that /dev/mapper/Mega-root is the volume made up from /dev/sda5 currently – this is what we will be expanding.


Increasing the virtual hard disk

First off we increase the allocated disk space on the virtual machine itself. This is done by right clicking the virtual machine in vSphere, selecting edit settings, and then selecting the hard disk. In the below image I have changed the previously set hard disk of 20gb to 30gb while the virtual machine is up and running. Once complete click OK, this is all that needs to be done in VMware for this process.

vSphere settings

If you are not able to modify the size of the disk, the provisioned size setting is greyed out. This can happen if the virtual machine has a snapshot in place, these will need to be removed prior to making the changes to the disk. Alternatively you may need to shut down the virtual machine if it does not allow you to add or increase disks on the fly, if this is the case make the change then power it back on.

 

Detect the new disk space

Once the physical disk has been increased at the hardware level, we need to get into the operating system and create a new partition that makes use of this space to proceed.

Before we can do this we need to check that the new unallocated disk space is detected by the server, you can use “fdisk -l” to list the primary disk. You will most likely see that the disk space is still showing as the same original size, at this point you can either reboot the server and it will detect the changes on boot or you can rescan your devices to avoid rebooting by running the below command.

Note you may need to change host0 depending on your setup.
echo "- - -" > /sys/class/scsi_host/host0/scan

Below is an image after performing this and confirming that the new space is displaying.

fdisk

 

Partition the new disk space

As outlined in my previous images the disk in my example that I am working with is /dev/sda, so we use fdisk to create a new primary partition to make use of the new expanded disk space. Note that we do not have 4 primary partitions already in place, making this method possible.
fdisk /dev/sda

We are now using fdisk to create a new partition, the inputs I have entered in are shown below in bold. Note that you can press ‘m’ to get a full listing of the fdisk commands.
‘n’ was selected for adding a new partition.

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): n
‘p’ is then selected as we are making a primary partition.
Command action
   l   logical (5 or over)
   p   primary partition (1-4)
p

As I already have /dev/sda1 and /dev/sda2 as shown in previous images, I have gone with using ‘3’ for this new partition which will be created as /dev/sda3
Partition number (1-4): 3

We just press enter twice above as by default the first and last cylinders of the unallocated space should be correct. After this the partition is then ready.

First cylinder (2611-3916, default 2611): "enter"
Using default value 2611
Last cylinder, +cylinders or +size{K,M,G} (2611-3916, default 3916): "enter"
Using default value 3916
‘t’ is selected to change to a partition’s system ID, in this case we change to ‘3’ which is the one we just created.
Command (m for help): t
Partition number (1-5): 3

The hex code ‘8e’ was entered as this is the code for a Linux LVM which is what we want this partition to be, as we will be joining it with the original /dev/sda5 Linux LVM.
Hex code (type L to list codes): 8e
Changed system type of partition 3 to 8e (Linux LVM)

‘w’ is used to write the table to disk and exit, basically all the changes that have been done will be saved and then you will be exited from fdisk.
Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

You will see a warning which basically means in order to use the new table with the changes a system reboot is required. If you can not see the new partition using “fdisk -l” you may be able to run “partprobe -s” to rescan the partitions. In my test I did not require either of those things at this stage (I do a reboot later on), straight after pressing ‘w’ in fdisk I was able to see the new /dev/sda3 partition of my 10gb of space as displayed in the below image.

For CentOS/RHEL run a “partx -a /dev/sda3” to avoid rebooting later on.

fdisk
That’s all for partitioning, we now have a new partition which is making use of the previously unallocated disk space from the increase in VMware.

 

Increasing the logical volume

We use the pvcreate command which creates a physical volume for later use by the logical volume manager (LVM). In this case the physical volume will be our new /dev/sda3 partition.
root@Mega:~# pvcreate /dev/sda3
  Device /dev/sda3 not found (or ignored by filtering).

In order to get around this you can either reboot, or use partprobe/partx as previously mentioned to avoid a reboot, as in this instance the disk does not appear to be there correctly despite showing in “fdisk -l”. After a reboot or partprobe/partx use the same command which will succeed.
root@Mega:~# pvcreate /dev/sda3
  Physical volume "/dev/sda3" successfully created

Next we need to confirm the name of the current volume group using the vgdisplay command. The name will vary depending on your setup, for me it is the name of my test server. vgdisplay provides lots of information on the volume group, I have only shown the name and the current size of it for this example.

root@Mega:~# vgdisplay
  --- Volume group ---
  VG Name               Mega
...
VG Size               19.76 GiB

Now we extend the ‘Mega’ volume group by adding in the physical volume of /dev/sda3 which we created using the pvcreate command earlier.
root@Mega:~# vgextend Mega /dev/sda3
  Volume group "Mega" successfully extended

Using the pvscan command we scan all disks for physical volumes, this should confirm the original /dev/sda5 partition and the newly created physical volume /dev/sda3
root@Mega:~# pvscan
  PV /dev/sda5   VG Mega   lvm2 [19.76 GiB / 0    free]
  PV /dev/sda3   VG Mega   lvm2 [10.00 GiB / 10.00 GiB free]
  Total: 2 [29.75 GiB] / in use: 2 [29.75 GiB] / in no VG: 0 [0   ]

Next we need to increase the logical volume (rather than the physical volume) which basically means we will be taking our original logical volume and extending it over our new partition/physical volume of /dev/sda3.

Firstly confirm the name of the logical volume using lvdisplay. This name will vary depending on your setup.

root@Mega:~# lvdisplay
  --- Logical volume ---
  LV Name                /dev/Mega/root
The logical volume is then extended using the lvextend command.
root@Mega:~# lvextend /dev/Mega/root /dev/sda3
  Extending logical volume root to 28.90 GiB
  Logical volume root successfully resized

There is then one final step which is to resize the file system so that it can take advantage of this additional space, this is done using the resize2fs command for ext based file systems. Note that this may take some time to complete, it took about 30 seconds for my additional space.

root@Mega:~# resize2fs /dev/Mega/root
resize2fs 1.41.12 (17-May-2010)
Filesystem at /dev/Mega/root is mounted on /; on-line resizing required
old desc_blocks = 2, new_desc_blocks = 2
Performing an on-line resize of /dev/Mega/root to 7576576 (4k) blocks.
The filesystem on /dev/Mega/root is now 7576576 blocks long.

Alternatively if you’re running the XFS file system (default as of RedHat/CentOS 7) you can grow the file system with “xfs_growfs /dev/Mega/root”.

That’s it, now with the ‘df’ command we can see that the total available disk space has been increased.
disk free after expansion

Thursday, October 15, 2015

What does 2>/dev/null mean and 2>&1…?

What does this command actually do?

~]# grep -i 'abc' content 2>/dev/null

The > operator redirects the output usually to a file but it can be to a device. You can also use >> to append.
If you don't specify a number then the standard output stream is assumed but you can also redirect errors
> file redirects stdout to file
1> file redirects stdout to file
2> file redirects stderr to file
&> file redirects stdout and stderr to file
/dev/null is the null device it takes any input you want and throws it away. It can be used to suppress any output.


~]# ./executable_script.sh | tee 2>&1 /tmp/filename.log

Allows you to execute a script and view all errors on the console and output to  a log file for viewing afterwards. This helps to view any errors that scroll past your the console screen to fast.

How to Password Protect GRUB

STEP 1: Create a password for GRUB, be a root user and open command prompt, type below command. When prompted type grub password twice and press enter. This will return MD5 hash password. Please copy or note it down.
[root@tecmint ~]#  grub-md5-crypt
Sample Output:
[root@tecmint ~]# grub-md5-crypt
Password: 
Retype password: 
$1$19oD/1$NklcucLPshZVoo5LvUYEp1


Step 2: Now you need to open the /boot/grub/menu.lst or /boot/grub/grub.conf file and add the MD5 password. Both files are same and symbolic link to each other.
[root@tecmint ~]# vi /boot/grub/menu.lst

OR

[root@tecmint ~]# vi /boot/grub/grub.conf
Note : I advise you to take backup of the files before making any changes to it, if in case something goes wrong you can revert it.


STEP 3: Add the newly created MD5 password in GRUB configuration file. Please paste copied password below timeout line and save it and exit. For example, Enter the line password –md5 <add the copied md5 string from step 1> above.

# grub.conf generated by anaconda
#
# Note that you do not have to rerun grub after making changes to this file
# NOTICE:  You have a /boot partition.  This means that
#          all kernel and initrd paths are relative to /boot/, eg.
#          root (hd0,0)
#          kernel /vmlinuz-version ro root=/dev/sda3
#          initrd /initrd-[generic-]version.img
#boot=/dev/sda
default=0
timeout=5
password --md5 $1$TNUb/1$TwroGJn4eCd4xsYeGiBYq.
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title CentOS (2.6.32-279.5.2.el6.i686)
        root (hd0,0)
        kernel /vmlinuz-2.6.32-279.5.2.el6.i686 ro root=UUID=d06b9517-8bb3-44db-b8c5-7710e183edb7 rd_NO_LUKS rd_NO_LVM rd_NO_MD rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc KEYTABLE=us crashkernel=auto rhgb quiet
        initrd /initramfs-2.6.32-279.5.2.el6.i686.img
title centos (2.6.32-71.el6.i686)
        root (hd0,0)
        kernel /vmlinuz-2.6.32-71.el6.i686 ro root=UUID=d06b9517-8bb3-44db-b8c5-7710e183edb7 rd_NO_LUKS rd_NO_LVM rd_NO_MD rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc KEYTABLE=us crashkernel=auto rhgb quiet
        initrd /initramfs-2.6.32-71.el6.i686.img

STEP 4: Reboot system and try it pressing ‘p‘ to enter password to unlock and enable next features.