Wednesday, January 23, 2019

SFTP chroot

Issue

  • Restrict chroot users to sftp connections using ssh keys without affecting normal user's access.

Resolution

  • Configuring a SFTP server with chroot users and ssh keys

Server setup

  • Create the user on the server
    [root@server ~]# useradd user1
    [root@server ~]# passwd user1
    

Client setup

  • Copy the ssh key from the client to the server (The user does not have to exist on the client)
    [clientuser@client ~]$ ssh-copy-id user1@server
    
  • Verify the ssh key works correctly from the client
    [clientuser@client ~]$ ssh user1@server
    [user1@server ~]$ exit
    logout
    Connection to server closed.
    [clientuser@client ~]$ 
    
  • Verify that your sftp connection works without a password prompt
    [clientuser@client ~]$ sftp user1@server
    Connected to server
    sftp> quit
    [clientuser@client ~]$
    
Without making any changes, user1 has full access and can ssh or sftp and change to any directory. We'll now make the necessary changes
to chroot user1 and keep them jailed and locked down to a specified directory.

Server setup

  1. Create a new group to add all your jailed chroot users on the server
    [root@server ~]# groupadd sftpusers
    
  2. Create a common directory for all of your jailed chroot users
    [root@server ~]# mkdir /sftp
    
  3. Create a subdirectory for each individual user that you want to chroot
    [root@server ~]# mkdir /sftp/user1
    
  4. Create the "home" directory for the user
    [root@server ~]# mkdir /sftp/user1/home
    
  5. Modify the user to add them to the new group you created
    [root@server ~]# usermod -aG sftpusers user1
    
  6. Change permission for the users chrooted "home" directory only. It's important to leave everything else with the default root permissions.
    [root@server ~]# chown user1:sftpusers /sftp/user1/home/
    
  7. Modify the /etc/ssh/sshd_config file and add the following lines:
Subsystem   sftp    internal-sftp -d /home
Match Group sftpusers
ChrootDirectory /sftp/%u
  • Restart the sshd service
    • RHEL 7:
      [root@server ~]# systemctl restart sshd
      
    • RHEL 6
      [root@server ~]# service sshd restart
      

Client verification

  1. From the client, verify that everything is working now
    [clientuser@client ~]$ ssh user1@server
    Last login: Sat Jun 25 12:54:32 2016 from 192.168.122.1
    Could not chdir to home directory /home/user1: No such file or directory
    /bin/bash: No such file or directory
    Connection to server closed.
    [clientuser@client ~]$ 
    
    • The user can no longer connect via ssh. Let's try sftp
      [clientuser@client ~]$ sftp user1@server
      Connected to server.
      sftp> pwd
      Remote working directory: /home
      sftp> cd /etc
      Couldn't canonicalize: No such file or directory
      sftp> 
      
    • OK, the user can successfully connect via sftp and they are still restricted to their "home" directory
  2. Make sure a regular user can still log in via ssh without the chroot restrictions
    [clientuser@client ~]$ ssh user2@server
    Last login: Sat Jun 25 13:49:43 2016 from 192.168.122.1
    [user2@server ~]$ 

Tuesday, January 15, 2019

Docker quick note

How to access container outside..

# docker run -p 8080:8080 --name myjenkins --detach jenkins

-p : expose port
--name: custom name of container which is going to run
--detach: it will run in background


How to get into running container

# docker exec -it myjenkins /bin/bash

Friday, July 28, 2017

Ansible passwordstore

An unhandled exception occurred while running the lookup plugin 'passwordstore'.

yum nstall pass; will fix issue

Wednesday, July 26, 2017

Puppet facter variable

How to collect Puppet agent information and copy to file either localhost or remotely

file {'collect_facts':
  ensure  => file,
  path    => "/tmp/${fqdn}",
  mode    => 0644,
  content => "IP is ${ipaddress}\nhostname is ${fqdn}\n",
}


you can find file underneath /tmp/fqn-name

Monday, June 19, 2017

How to find parent id of pid in Shell script




#!/bin/bash

echo "-- ms1 => $$"
echo "-- ms => $PPID"

Linux Boot Process

Press the power button on your system, and after few moments you see the Linux login prompt.
Have you ever wondered what happens behind the scenes from the time you press the power button until the Linux login prompt appears?
The following are the 6 high level stages of a typical Linux boot process.

1. BIOS

  • BIOS stands for Basic Input/Output System
  • Performs some system integrity checks
  • Searches, loads, and executes the boot loader program.
  • It looks for boot loader in floppy, cd-rom, or hard drive. You can press a key (typically F12 of F2, but it depends on your system) during the BIOS startup to change the boot sequence.
  • Once the boot loader program is detected and loaded into the memory, BIOS gives the control to it.
  • So, in simple terms BIOS loads and executes the MBR boot loader.

2. MBR

  • MBR stands for Master Boot Record.
  • It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
  • MBR is less than 512 bytes in size. This has three components 1) primary boot loader info in 1st 446 bytes 2) partition table info in next 64 bytes 3) mbr validation check in last 2 bytes.
  • It contains information about GRUB (or LILO in old systems).
  • So, in simple terms MBR loads and executes the GRUB boot loader.

3. GRUB

  • GRUB stands for Grand Unified Bootloader.
  • If you have multiple kernel images installed on your system, you can choose which one to be executed.
  • GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it loads the default kernel image as specified in the grub configuration file.
  • GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t understand filesystem).
  • Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The following is sample grub.conf of CentOS.
  • #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
  • As you notice from the above info, it contains kernel and initrd image.
  • So, in simple terms GRUB just loads and executes Kernel and initrd images.

4. Kernel

  • Mounts the root file system as specified in the “root=” in grub.conf
  • Kernel executes the /sbin/init program
  • Since init was the 1st program to be executed by Linux Kernel, it has the process id (PID) of 1. Do a ‘ps -ef | grep init’ and check the pid.
  • 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 it to access the hard drive partitions, and other hardware.

5. Init

  • Looks at the /etc/inittab file to decide the Linux 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
  • Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate program.
  • Execute ‘grep initdefault /etc/inittab’ on your system to identify the default run level
  • If you want to get into trouble, you can set the default run level to 0 or 6. Since you know what 0 and 6 means, probably you might not do that.
  • Typically you would set the default run level to either 3 or 5.

6. Runlevel programs

  • When the Linux system is booting up, you might see various services getting started. For example, it might say “starting sendmail …. OK”. Those are the runlevel programs, executed from the run level directory as defined by your run level.
  • 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/rc0.d/
    • Run level 1 – /etc/rc.d/rc1.d/
    • Run level 2 – /etc/rc.d/rc2.d/
    • Run level 3 – /etc/rc.d/rc3.d/
    • Run level 4 – /etc/rc.d/rc4.d/
    • Run level 5 – /etc/rc.d/rc5.d/
    • Run level 6 – /etc/rc.d/rc6.d/
  • 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.

CPU Stats

The 7 cpu statistics explained

There are several different ways to see the various CPU statistics. The most common is probably using the top command.
To start the top command you just type top at the command line:
The output from top is divided into two sections. The first few lines give a summary of the system resources including a breakdown of the number of tasks, the CPU statistics, and the current memory usage. Beneath these stats is a live list of the current running processes. This list can be sorted by PID, CPU usage, memory usage, and so on.
The CPU line will look something like this:
%Cpu(s): 24.8 us,  0.5 sy,  0.0 ni, 73.6 id,  0.4 wa,  0.0 hi,  0.2 si,  0.0 st
24.8 us - This tells us that the processor is spending 24.8% of its time running user space processes. A user space program is any process that doesn't belong to the kernel. Shells, compilers, databases, web servers, and the programs associated with the desktop are all user space processes. If the processor isn't idle, it is quite normal that the majority of the CPU time should be spent running user space processes.
73.6 id - Skipping over a few of the other statistics, just for a moment, the id statistic tell us that the processor was idle just over 73% of the time during the last sampling period. The total of the user space percentage - us, the niced percentage - ni, and the idle percentage - id, should be close to 100%. Which it is in this case. If the CPU is spending a more time in the other states then something is probably awry - see the Troubleshooting section below.
0.5 sy - This is the amount of time that the CPU spent running the kernel. All the processes and system resources are handled by the Linux kernel. When a user space process needs something from the system, for example when it needs to allocate memory, perform some I/O, or it needs to create a child process, then the kernel is running. In fact the scheduler itself which determines which process runs next is part of the kernel. The amount of time spent in the kernel should be as low as possible. In this case, just 0.5% of the time given to the different processes was spent in the kernel. This number can peak much higher, especially when there is a lot of I/O happening.
0.0 ni - As mentioned above, the priority level a user space process can be tweaked by adjusting its niceness. The ni stat shows how much time the CPU spent running user space processes that have been niced. On a system where no processes have been niced then the number will be 0.
0.4 wa - Input and output operations, like reading or writing to a disk, are slow compared to the speed of a CPU. Although this operations happen very fast compared to everyday human activities, they are still slow when compared to the performance of a CPU. There are times when the processor has initiated a read or write operation and then it has to wait for the result, but has nothing else to do. In other words it is idle while waiting for an I/O operation to complete. The time the CPU spends in this state is shown by the wa statistic.
0.0 hi & 0.2 si - These two statistics show how much time the processor has spent servicing interruptshi is for hardware interrupts, and si is for software interrupts. Hardware interrupts are physical interrupts sent to the CPU from various peripherals like disks and network interfaces. Software interrupts come from processes running on the system. A hardware interrupt will actually cause the CPU to stop what it is doing and go handle the interrupt. A software interrupt doesn't occur at the CPU level, but rather at the kernel level.
0.0 st - This last number only applies to virtual machines. When Linux is running as a virtual machine on a hypervisor, the st (short for stolen) statistic shows how long the virtual CPU has spent waiting for the hypervisor to service another virtual CPU running on a different virtual machine. Since in the real-world these virtual processors are sharing the same physical processor(s) then there will be times when the virtual machine wanted to run but the hypervisor scheduled another virtual machine instead.

Monday, February 20, 2017

Nagios plugin for Docker Container Https monitoring

#!/bin/bash
CONTAINER=my_ubuntu
ENV=`hostname -d | cut -f2 -d.`
PORT=$(docker inspect --format '{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' $CONTAINER  | awk -F '[>]' '{print $2}' )
HOST=$(hostname)

#you can specify env like qa,stage,prod

while [ $ENV = qa ];
 do
        if [ $PORT == 443 ] && [ `curl -LIk  https://${HOST} -o /dev/null -w '%{http_code}\n' -s` = 200 ];
     
        then
            echo "OK - $CONTAINER port 443 is up"
            exit 0
        else
            echo "CRITICAL - $CONTAINER port 443 is down"
            exit 2
        fi
 done

Monday, February 6, 2017

Docker container monitoring script for Nagios

#!/bin/bash

CONTAINER=ubuntu

RUNNING=$(docker inspect --format="{{ .State.Running }}" $CONTAINER 2> /dev/null)

if [ "$RUNNING" == "false" ]; then
  echo "CRITICAL - $CONTAINER is not running."
  exit 2
else
echo "OK - $CONTAINER is running."
exit  0

fi

Docker service failed to start

I  installed docker-engine on RHEL 7 and  when i tried to run docker service i got following error

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

Solution:
#systemctl stop docker.service
#rm -rf /var/lib/docker
#systemctl start docker.service

Monday, January 2, 2017

Exclude a file from a git commit

?
1
2
3
4
5
git update-index --assume-unchanged path/to/file.txt
 
git commit -a -m "updated some files but excluded this"
 
git update-index --no-assume-unchanged path/to/file.txt

Tuesday, August 30, 2016

Git: Squash your latests commits into one


With git it’s possible to squash previous commits into one. This is a great way to group certain changes together before sharing them with others. ~ Here’s how to squash some commits into one. Let’s say this is your current git log.
* df71a27 - (HEAD feature_x) Updated CSS for new elements (4 minutes ago)
* ba9dd9a - Added new elements to page design (15 minutes ago)
* f392171 - Added new feature X (1 day ago)
* d7322aa - (origin/feature_x) Proof of concept for feature X (3 days ago)
You have a branch feature_x here. You’ve already pushed d7322aa with the proof of concept of the new feature X. After that you’ve been working to add new element to the feature, including some changes in CSS. Now, you want to squash your last three commits in one to make your history look pretty.
The command to accomplish that is:
git rebase -i HEAD~3
This will open up your editor with the following:
pick f392171 Added new feature X
pick ba9dd9a Added new elements to page design
pick df71a27 Updated CSS for new elements
Now you can tell git what to do with each commit. Let’s keep the commit f392171, the one were we added our feature. We’ll squash the following two commits into the first one - leaving us with one clean commit with features X in it, including the added element and CSS.
Change your file to this:
pick f392171 Added new feature X
squash ba9dd9a Added new elements to page design
squash df71a27 Updated CSS for new elements
When done, save and quit your editor. Git will now squash the commits into one. All done!
Note: do not squash commits that you’ve already shared with others. You’re changing history and it will cause trouble for others.

Monday, April 25, 2016

AWS CLI install on Linux

Getting started with AWS CLI

Step 1: Download setuptools
wget https://pypi.python.org/packages/source/s/setuptools/setuptools-7.0.tar.gz

Step 2: Extract it
tar xvf setuptools-7.0.tar.gz
cd setuptools-7.0/

Step 3: Install
python setup.py install

Step 4: Download pip
wget https://bootstrap.pypa.io/get-pip.py

Step 5: install pip
python get-pip.py

Step 6: install awscli
pip install awscli

Step : verify awscli
aws --version

Monday, March 14, 2016

Linux Buffer Cache Resident Memory

# free -m
         total      used     free   shared     buffers     cached
Mem:      4049      3982       67        0          16       3530
-/+ buffers/cache:   435     3614
Swap:     6142        53     6088

and it turns out that it is NOT really what I was looking for. A more accurate representation of the memory being used by your applications and available for new processes is displayed in theSECOND line.

In addition to the memory that is actually being USED by the kernel and processes resident in memory - Linux also reserves memory to allocate to processes as 'buffers' AND uses pretty much any left over memory to hold "cached" files.

Looking only at the top line...
total = all memory in the system (4GB on this server)
used = all memory currently in use/reserved by running processes and the OS
free = total - used
shared = memory being shared by multiple processes (deprecated?)
buffers = memory reserved by the OS to alloc as buffers when process need them (aka the 'heap')
cached = recently used files being stored in ram.

Here's a simple example I found to show off the power of 'caching':
for i in 1 2 ; do free -o; time grep -r foo /usr/bin >/dev/null 2>/dev/null; done
So really the buffers would be allocated to a running process if it asked for them anyway, and the memory being used to cache copies of recently used files would be released immediately if it makes sense to allocate the RAM elsewhere. So all that memory is 'available'.

Using these definitions:

When thinking about 'how much memory is really being used' - I want to calculate:
'used' - ('buffers' + 'cached')

When thinking about 'how much memory is really free' - I want to calculate:
'free' + ('buffers' + 'cached')

With this in mind, the meaning of the second row header form the output of the Linux command "free" (-/+ buffers/cache:) makes more sense...

Free is doing some light lifting for us, using the formula's above to display:
"minus buffers and cache" for the used column
and
"plus buffers and cache" for the free colum
Overview of memory management

Traditional Unix tools like 'top' often report a surprisingly small amount of free memory after a system has been running for a while. For instance, after about 3 hours of uptime, the machine I'm writing this on reports under 60 MB of free memory, even though I have 512 MB of RAM on the system. Where does it all go?
The biggest place it's being used is in the disk cache, which is currently over 290 MB. This is reported by top as "cached". Cached memory is essentially free, in that it can be replaced quickly if a running (or newly starting) program needs the memory.

The reason Linux uses so much memory for disk cache is because the RAM is wasted if it isn't used. Keeping the cache means that if something needs the same data again, there's a good chance it will still be in the cache in memory. Fetching the information from there is around 1,000 times quicker than getting it from the hard disk. If it's not found in the cache, the hard disk needs to be read anyway, but in that case nothing has been lost in time.
To see a better estimation of how much memory is really free for applications to use, run the command:
 $ free -m 



The -m option stands for megabytes, and the output will look something like this:
              total    used     free   shared  buffers   cached 
 Mem:           503     451       52        0       14      293 
 -/+ buffers/cache:     143      360 
 Swap:         1027       0     1027


The -/+ buffers/cache line shows how much memory is used and free from the perspective of the applications. Generally speaking, if little swap is being used, memory usage isn't impacting performance at all.
Notice that I have 512 MB of memory in my machine, but only 503 is listed as available by free. This is mainly because the kernel can't be swapped out, so the memory it occupies could never be freed.
There may also be regions of memory reserved for/by the hardware for other purposes as well, depending on the system architecture.

The mysterious 880 MB limit on x86

By default, the Linux kernel runs in and manages only low memory.This makes managing the page tables slightly easier, which in turn makes memory accesses slightly faster. The downside is that it can't use all of the memory once the amount of total RAM reaches the neighborhood of 880 MB. This has historically not been a problem, especially for desktop machines.
To be able to use all the RAM on a 1GB machine or better, the kernel needs recompiled. Go into 'make menuconfig' (or whichever config is preferred) and set the following option:
Code: 
  Processor Type and Features ----> 
  High Memory Support ----> 
   (X) 4GB 



This applies both to 2.4 and 2.6 kernels. Turning on high memorysupport theoretically slows down accesses slightly, but according to Joseph_sys and log, there is no practical difference.

The difference among VIRT, RES, and SHR in top output

VIRT stands for the virtual size of a process, which is the sum of memory it is actually using, memory it has mapped into itself (for instance the video card's RAM for the X server), files on disk that have been mapped into it (most notably shared libraries), and memory shared with other processes. VIRT represents how much memory the program is able to access at the present moment.

RES stands for the resident size, which is an accurate representation of how much actual physical memory a process is consuming. (This also corresponds directly to the %MEM column.) This will virtually always be less than the VIRT size, since most programs depend on the C library.

SHR indicates how much of the VIRT size is actually sharable memory or libraries). In the case of libraries, it does not necessarily mean that the entire library is resident. For example, if a program only uses a few functions in a library, the whole library is mapped and will be counted in VIRT and SHR, but only the parts of the library file containing the functions being used will actually be loaded in and be counted under RES.

The difference between buffers and cache

Buffers are associated with a specific block device, and cover caching of filesystem metadata as well as tracking in-flight pages. The cache only contains parked file data. That is, the buffers remember what's in directories, what file permissions are, and keep track of what memory is being written from or read to for a particular block device. The cache only contains the contents of the files themselves.

Corrections and additions to this section welcome; I've done a bit of guesswork based on tracing how /proc/meminfo is produced to arrive at these conclusions.

Swappiness (2.6 kernels)

Since 2.6, there has been a way to tune how much Linux favors swapping out to disk compared to shrinking the caches when memory gets full.
ghoti adds: When an application needs memory and all the RAM is fully occupied, the kernel has two ways to free some memory at its disposal: it can either reduce the disk cache in the RAM by eliminating the oldest data or it may swap some less used portions (pages) of programs out to the swap partition on disk. It is not easy to predict which method would be more efficient. The kernel makes a choice by roughly guessing the effectiveness of the two methods at a given instant, based on the recent history of activity.
Before the 2.6 kernels, the user had no possible means to influence the calculations and there could happen situations where the kernel often made the wrong choice, leading to thrashing and slow performance. The addition of swappiness in 2.6 changes this. Thanks, ghoti!
Swappiness takes a value between 0 and 100 to change the balance between swapping applications and freeing cache. At 100, the kernel will always prefer to find inactive pages and swap them out; in other cases, whether a swapout occurs depends on how much application memory is in use and how poorly the cache is doing at finding and releasing inactive items.
The default swappiness is 60. A value of 0 gives something close to the old behavior where applications that wanted memory could shrink the cache to a tiny fraction of RAM. For laptops which would prefer to let their disk spin down, a value of 20 or less is recommended.
As a sysctl, the swappiness can be set at runtime with either of the following commands:
 # sysctl -w vm.swappiness=30 
 # echo 30 >/proc/sys/vm/swappiness
The default when linux boots can also be set in /etc/sysctl.conf:
File: /etc/sysctl.conf 
# Control how much the kernel should
#favor swapping out applications (0-100) 
vm.swappiness = 30