SSH to your Linux Server using Google Authenticator app

In this section, we will learn how to secure your ssh connection with MFA using Google authenticator app.

Before we start go ahead and download the google authenticator app to your mobile device.

After you successfully downloaded and install the google authenticator app on your mobile device go to your Linux server and install the google-authenticator PAM module by typing this command:

swarm@swarm3:~$ sudo apt install libpam-google-authenticator
Reading package lists... Done
Building dependency tree       
Reading state information... Done
libpam-google-authenticator is already the newest version (20191231-2).
0 upgraded, 0 newly installed, 0 to remove and 75 not upgraded

After the installation complete type following command:

swarm@swarm3:~$ google-authenticator

  • Follow the instructions and scan the bar-code by your google authenticator mobile app
  • You can type yes for every question that you encounter during the process of setting up the Google authentication app
  • After completion save the emergency scratch codes in a secure location, you will need it in case you lose your phone
  • You can do this process for every user on your Linux server.

Now we will need to enable “ChallengeResponseAuthentication” in the ssh config file.

swarm@swarm3:~$ sudo vi /etc/ssh/sshd_config

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication yes

Don’t forget to save the file by pressing :qw


Restart the SSH service:

swarm@swarm3:~$ sudo systemctl restart ssh


The final step is to add the google authentication module to the PAM ssh config file:

swarm@swarm3:~$ sudo vi /etc/pam.d/sshd

Add this line to the end of the config file and save the file:

auth required pam_google_authenticator.so

That’s it, now you can ssh to your server using google authentication

Verfication code: Enter the code that presented in your google authenticator app in your mobile device.

SSH Key-Pairs.

Remotely Connect to Linux Servers with SSH key-pairs

SSH: Authentication with Key-pairs

On your client machine:

  • Create ssh key pair by using the command ssh-keygen
    • It will create 2 files (Private key and Public key) in the .ssh folder.
[menit@fedora .ssh]$ ls 
id_rsa id_rsa.pub
  • It is recommended that you will use a passphrase to encrypt your private key
[menit@fedora .ssh]$ ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/home/menit/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/menit/.ssh/id_rsa
Your public key has been saved in /home/menit/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:E+n8J9Sjbdbi5A7uyu7LVAm2Y8fNBtSawvCyoR7l3Y4 menit@fedora
The key's randomart image is:
+---[RSA 3072]----+
|          ..     |
|      .  o  .    |
|       += .o     |
|      +++=o*     |
|     + =So* *    |
|    o o..B.+ o   |
|   . .  .o= B .  |
|    .  +E..X .   |
|       oB+o.+    |
+----[SHA256]-----+
```

How to Deploy your public key to your manage servers.

  • To connect to your Linux servers using ssh keys you will need to transfer the public key to your remote servers

There are 2 methods to transfer the public key to your server

The first method is to install the public key from your own host to your remote server using this command:

  • This command will create on the remote host .ssh folder and a file named authorized_keys and he will copy-paste the public key to this file.
ssh-copy-id -i /home/menit/.ssh/id_rsa.pub username@192.168.122.235

  • The second method is to copy your public key and paste it to your remote server under the .ssh folder to file named authorized_keys (if you can’t find such file you just need to create it.

Now you can connect to your machine using this command

[menit@fedora .ssh]$ ssh swarm@192.168.122.235

Connect to your remote server without the passphrase

To avoid the need to enter a passphrase every time you ssh to a remote host you can use sshagent to Cache your Authentication Credentials into the host memory.

[menit@fedora .ssh]$ ssh-agent bash
[menit@fedora .ssh]$ ssh-add id_rsa
Enter passphrase for id_rsa: ***********
Identity added: id_rsa (menit@fedora)

How to ssh to a remote host using the Root User account.

  1. On the remote host, you will need first to enable the login as root option: To enable it to remove # from the line “PermitRootLogin prohibit-password”
swarm@swarm3:/etc/ssh$ vim /etc/ssh/sshd_config

#LoginGraceTime 2m
PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

Exit and Save the file by pressing :wq

  1. Switch to you root account in the remote server and pass the Public ssh key to the authorized_keys file under the .ssh folder.
root@swarm3:~/.ssh# ls
authorized_keys

How to type sudo command with a password

To grant you user sudo permissions you will need to edit this config file:

[menit@fedora .ssh]$ sudo visudo

Under Allow people in group wheel paste this command

#Allow users to run all commands
menit ALL=(ALL) NOPASSWD: ALL

This is how it’s should be looked like in the config file:

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

#Allow users to run all commands
menit ALL=(ALL) NOPASSWD: ALL

It’s important you enter your new line entry at the bottom of the config file because the visudo file is processed from the top to bottom.

Setup Snipe-IT on Ubuntu.

Snipe-IT Open Source Asset Management

Installation Details

  • Infrastructure: AWS
  • AMI ID: RHEL-8.2.0_HVM-20200423-x86_64-0-Hourly2-GP2 (ami-07dfba995513840b5)
  • Instance type : t2.medium
  • Instance Hardware: 2vcpu , 4G Memory.

What is it Snipe-IT

Snipe-IT was made for IT asset management, to enable IT departments to track who has which laptop, when it was purchased, which software licenses and accessories are available, and so on.


Lets Start:

Update Ubuntu:

sudo apt update
sudo apt upgrade

Install Apache2 HTTP:

sudo apt install apache2 -y

To find out if Apache2 HTTP server is installed, simply open your web browser and type in the server’s IP or hostname.

When you see the page similar to the one below, then Apache2 is installed and working.

apache2 ubuntu install

Install PHP:

sudo apt install php -y
sudo apt install php7.2-mbstring php7.2-curl php7.2-mysql php7.2-ldap php7.2-zip php7.2-bcmath php7.2-xml php7.2-gd -y

Install MySQL:

sudo apt install mysql-server -y

Create the database:

sudo mysql -u root

You should now have the mysql prompt mysql>

Create the database and the user and grant permissions to the user.

mysql> create database snipeit;
mysql> create user snipe_user;
mysql> grant all on snipeit.* to 'snipe_user'@'localhost' identified by 'YOUR_DB_PASSWORD';
mysql> exit (to leave the mysql shell)
sudo apt install git vim -y

Download Snipe-IT into the web server directory:

sudo mkdir /var/www/html/snipe-it
sudo chown yourusername:yourusername /var/www/html/snipe-it

cd to the new directory and download

cd /var/www/html/snipe-it
git clone https://github.com/snipe/snipe-it .

Set up Snipe-IT config file:

Copy the .env.example file to a new .env file and open it in your text editor.

cp .env.example .env
vim .env

Make sure APP_ENV is set to production and APP_DEBUG is set to false

APP_ENV=production
APP_DEBUG=false

Setup APP_URL:

This is the url to your application, beginning with http:// or https:// (if you’re running Snipe-IT over SSL). This should not have a trailing slash, and you should not have public in the URL.Images and javascript will not load correctly if this is not set to EXACTLY the URL you access your Snipe-IT app from.

You can set APP_URL to an IP address for setup or testing and change it to another domain name later.

APP_URL=your.domain.name

Set the timezone. Use one of the PHP supported time zone strings from https://www.php.net/manual/en/timezones.php

APP_TIMEZONE='YOURTIMEZONE'

Set your language. Default is English (en). See https://snipe-it.readme.io/docs/configuration#section-setting-a-language:

APP_LOCALE=en

Fill in the database settings with the database name, database user name and password you created in the mysql setup step:

DB_DATABASE=snipeit
DB_USERNAME=snipe_user
DB_PASSWORD=YOUR_DB_PASSWORD

Install snipe-IT dependencies

Make sure you are still in the snipe-it directory. If you are following this guide it will be /var/www/html/snipe-it

cd /var/www/html/snipe-it

Snipe-IT uses a PHP dependency manager called Composer to manage its dependencies so install it and then install the dependencies: (This might take a few minutes)

curl -sS https://getcomposer.org/installer | php
php composer.phar install --no-dev --prefer-source

Generate your app key

php artisan key:generate

This will generate an encryption key and set APP_KEY in your .env file. Copy the key and save it in secure location.

Grant appropriate filesystem permissions so apache can access the files:

sudo chown -R yourusername:www-data /var/www/html/snipe-it

Now remove group write permission from the files. There’s no reason for apache to be able to write to all these files:

sudo chmod -R g-w /var/www/html/snipe-it

Now add back write permission for the areas we want Snipe-IT to be able to write to:

sudo chmod -R g+w /var/www/html/snipe-it/storage
sudo chmod -R g+w /var/www/html/snipe-it/public/uploads

Configure the server

Copy the default vhost file and open the copy in your text editor.

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/snipe-it.conf
sudo vim /etc/apache2/sites-available/snipe-it.conf

Edit the file to look like this:

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port 
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html/snipe-it/public

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn
        ServerName 10.64.118.91

        <Directory /var/www/html/snipe-it/public>
                Allow From All
                AllowOverride All
                Options -Indexes
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

Save the file and close your text editor

Disable the old default vhost and enable your new vhost

sudo a2dissite 000-default.conf
sudo a2ensite snipe-it.conf

Also enable mod_rewrite

sudo a2enmod rewrite
sudo systemctl reload apache2

And we finish! you can now point your web browser at the address of your web server.You should get the Snipe-IT Pre-Flight and your Pre-Flight check should be all green check mark.

[AWS] Deploy Ansible for linux and Windows Domain Joined

Installation Details

  • Infrastructure: AWS
  • AMI ID: RHEL-8.2.0_HVM-20200423-x86_64-0-Hourly2-GP2 (ami-07dfba995513840b5)
  • Instance type : t2.medium
  • Instance Hardware: 2vcpu , 4G Memory.

Before we start

Install Vim:

sudo yum install vim

Update Packages

sudo yum update

Prepare For Installation

Change the Hostname:

sudo vim /etc/hostname

Add DNS in hosts file.

sudo vim /etc/hosts

Install epel Repo:

yum -y install [<https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm>](<https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm>)

Install Ansible:

sudo yum install ansible

General Configuration Ansible

Create user:

sudo useradd ansible

Generate password:

passwd ansible 

Login with ansible user:

sudo su - ansible

Give Sudo Permissions:

  1. Change user to root
sudo su -
  1. Give ansible sudo privileges (Centos)
[root@itansible ~]# usermod -aG wheel ansible
[root@itansible ~]# sudo su - ansible
[ansible@itansible ~]$ id ansible
uid=1001(ansible) gid=1001(ansible) groups=1001(ansible),10(wheel)

[ansible@itansible ~]$ sudo visudo
## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
ansible         ALL=(ALL)       NOPASSWD: ALL
ec2-user        ALL=(ALL)       NOPASSWD: ALL


login back to you ansible user and Create SSH key pair.

[ansible@itansible ~]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ansible/.ssh/id_rsa):
/home/ansible/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): ******


Configure Linux Managed Hosts:

  1. Create user and password name ansible
  2. Copy the ssh public key from ansible master to to the managed hosts.
# On the managed host, switch to ansible user
Type the command  =  cd .ssh/
# Create authorized_keys file
vim authorized_keys
# Go to ansible master and copy the public key:
cat ~/.ssh/id_rsa.pub [select and copy to your clipboard]
# ssh into ansible managed hosts, and append the contents of that to the authorized_keys file:
[paste your clipboard contents to the authorized_keys file:]
  • Give sudo permissions (Ubuntu)
ansible@ip-10-64-118-34:~$ sudo visudo

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d
ansible     ALL=(ALL) NOPASSWD:ALL


Configure Ansible for Linux

  1. log in to the Ansible Master with the user ansible
  2. Create a linux project directory in ansible home folder
mkdir linux
  1. in the linux directory create 2 file.
[ansible@itansible linux]$ ls
ansible.cfg  inventory
  1. Configure ansible.cfg file like this:
[defaults]
remote_user = ansible
host_key_checking = false
inventory = inventory
[privilege_escalation]
become = true
become_method = sudo
become_user = root
become_ask_pass = false
  1. Configure inventory file like this:
[linux]
itansible-slave

  1. Test the connection examples:
[ansible@itansible linux]$ ansible all -m command -a "id ansible"
itansible-slave | CHANGED | rc=0 >>
uid=1001(ansible) gid=1001(ansible) groups=1001(ansible),27(sudo)

[ansible@itansible linux]$ ansible all -m user -a name=test
itansible-slave | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": true,
    "comment": "",
    "create_home": true,
    "group": 1002,
    "home": "/home/test",
    "name": "test",
    "shell": "/bin/sh",
    "state": "present",
    "system": false,
    "uid": 1002
}


Configure Ansible for Windows

  1. log in to the Ansible Master with the user ansible
  2. Create a windows project directory in ansible home folder
mkdir windows

Installing the Kerberos Library

# via Yum (RHEL/Centos/Fedora)
sudo yum -y install gcc python-devel krb5-devel krb5-libs krb5-workstation
sudo yum -y pip3 install "pywinrm>=0.2.2"

Configuring Kerberos

Edit your /etc/krb5.conf (which should be installed as a result of installing packages above) and add the following information for each domain you need to connect to:

ansible@ip-10-64-118-34:~$ cat /etc/krb5.conf
[libdefaults]
default_realm = mydomain.com (Enter your domain)
dns_lookup_realm = true
dns_lookup_kdc = true

Testing a kerberos connection

If you have installed krb5-workstation (yum) or krb5-user (apt-get) you can use the following command to test that you can be authorised by your domain controller.

kinit user@MY.DOMAIN.COM

To see what tickets if any you have acquired, use the command klist

klist

Create Inventory,Config,Variables file

[ansible@itansible windows]$ ls
ansible.cfg group_vars inventory winvars winvars.yml

Create Inventory file

[ansible@itansible windows]$ vim inventory

[windows]
mt-n.argus.local

Create config file

[ansible@itansible windows]$ vim ansible.cfg

[defaults]
host_key_checking = false
inventory = inventory

Create Group_vars directory and variables file

mkdir group_vars
[ansible@itansible group_vars]$ vim windows
ansible_user: user@ARGUS-LOCAL
ansible_password: password
ansible_connection: winrm
ansible_winrm_transport: kerberos
ansible_winrm_server_cert_validation: ignore


Configure Windows Managed Hosts

To configure the Windows Server for remote management by Ansible requires a bit of work. Luckily the Ansible team has created a PowerShell script for this. Download this script from [here] to each Windows Server to manage and run this script as Administrator.

Log into WinServer1 as Administrator, download ConfigureRemotingForAnsible.ps1 and run this PowerShell script without any parameters.

Once this command has been run on the windows 10 , return to the Ansible master Controller host.

Test Connectivity to the Windows Server

If all has gone well, we should be able to perform an Ansible PING test command. This command will simply connect to the remote WinServer1 server and report success or failure.

Type: ansible windows -m win_ping

https://argonsys.com/wp-content/uploads/2018/02/kb32-ansible-etcansiblehosts.png

Join Linux CENTOS-7 to Microsoft Active Directory Domain.

First lets check our network interfaces by using this command:

[root@cetnos /]# ip addr

We can see that we get IP address 192.168.10.6 on interface ens33

So lets change this from DHCP to static IP and add the DNS servers, we do it by changing the interface config file.


[root@cetnos /]# vi /etc/sysconfig/network-scripts/ifcfg-ens33

Please add the Marked lines to your network interface config file.

Now save it by using this command :qw!

Please reboot the server for changes will take effect.

After the system has finish to reboot we need to change one last thing before we join this machine to the domain, please open resolve.conf file by using this command:

[root@cetnos /]# vi /etc/resolv.conf

Make sure that you add your Domain name here and you have the IP address of your DNS servers, don’t forget to save it by using this command :qw!

Now after we finish, we can go on and join this machine to the Domain, we doing it by using this commands.

[root@cetnos /]# yum install sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-python -y
[root@centos ~]# realm join --user=administrator example.com
Password for administrator:

Once this has completed successfully, a computer object will be created in Active Directory in the default computers container as shown below.

Now that our Linux server is a member of the Active Directory domain we can perform some tests. we need to specify the domain name. For example with the ‘id’ command below,

[root@centos ~]# id administrator@example.com
uid=1829600500(administrator@example.com) gid=1829600513(domain users@example.com) groups=1829600513(domain users@example.com),1829600512(domain admins@example.com),1829600572(denied rodc password replication group@example.com),1829600519(enterprise admins@example.com),1829600518(schema admins@example.com),1829600520(group policy creator owners@example.com)

We can also SSH in as any domain user from Active Directory with default settings.

Leaving The Domain

If you want to reverse the process and remove yourself from the domain, simply run the ‘realm leave’ command followed by the domain name, as shown below.

[root@centos ~]# realm leave example.com
%d bloggers like this: