How to run an install script after reboot – CentOS / RHEL

 

How to run an install script after reboot

 

Environment

  • Red Hat Enterprise Linux 5
  • Red Hat Enterprise Linux 6
  • Red Hat Enterprise Linux 7

Issue

  • Need to install Oracle after kickstart reboots the machine.
  • crontab with the @reboot schedule works but it runs before the network is started.

Resolution

Add the following to the post section of the kickstart configuration file:

touch /tmp/runonce

Prior to Red Hat Enterprise Linux 7:

The /etc/rc.local script is executed last in the boot sequence and can be used for this purpose by adding the following to the %post section in the kickstart file:

cat << EOF >> /etc/rc.local
if [ -e /tmp/runonce ]
then
   rm /tmp/runonce
   exec > /root/runonce.log 2>&1
   /path/to/my/script
fi
EOF

Red Hat Enterprise Linux 7 and later:

As of Red Hat Enterprise Linux 7, systemd services can be executed in parallel provided required dependencies have been satisfied. In the case of /etc/rc.local, there is a dependency on network.target (network has been enabled), however, the network may not yet be online. To ensure the network is online, create a new service to wait for the network to be online before executing our installation script by adding the following to the %post section in the kickstart file:

cat << EOF > /etc/systemd/system/runonce.service
[Unit]
Description=Run once
Requires=network-online.target
After=network-online.target

[Service]
ExecStart=/root/runonce.sh

[Install]
WantedBy=multi-user.target
EOF

chmod 664 /etc/systemd/system/runonce.service
systemctl enable runonce

The runonce.sh script would need to be placed on the newly installed system via the %post section in the kickstart file and would look something like this, adjusting accordingly to point to your particular install script:

#!/bin/bash

if [ -e /tmp/runonce ]
then
   rm /tmp/runonce
   exec > /root/runonce.log 2>&1
   /path/to/my/script
fi

exit

Additional information on systemd service configuration can be found in the System Administrators Guide:

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sect-Managing_Services_with_systemd-Unit_Files.html

OpenSSL Essentials: Working with SSL Certificates, Private Keys and CSRs

Introduction

OpenSSL is a versatile command line tool that can be used for a large variety of tasks related to Public Key Infrastructure (PKI) and HTTPS (HTTP over TLS). This cheat sheet style guide provides a quick reference to OpenSSL commands that are useful in common, everyday scenarios. This includes OpenSSL examples of generating private keys, certificate signing requests, and certificate format conversion. It does not cover all of the uses of OpenSSL.

How to Use This Guide:

  • If you are not familiar with certificate signing requests (CSRs), read the first section
  • Aside from the first section, this guide is in a simple, cheat sheet format–self-contained command line snippets
  • Jump to any section that is relevant to the task you are trying to complete (Hint: use the Contentsmenu on the bottom-left or your browser’s Find function)
  • Most of the commands are one-liners that have been expanded to multiple lines (using the \symbol) for clarity

About Certificate Signing Requests (CSRs)

If you would like to obtain an SSL certificate from a certificate authority (CA), you must generate a certificate signing request (CSR). A CSR consists mainly of the public key of a key pair, and some additional information. Both of these components are inserted into the certificate when it is signed.

Whenever you generate a CSR, you will be prompted to provide information regarding the certificate. This information is known as a Distinguised Name (DN). An important field in the DN is the Common Name(CN), which should be the exact Fully Qualified Domain Name (FQDN) of the host that you intend to use the certificate with. It is also possible to skip the interactive prompts when creating a CSR by passing the information via command line or from a file.

The other items in a DN provide additional information about your business or organization. If you are purchasing an SSL certificate from a certificate authority, it is often required that these additional fields, such as “Organization”, accurately reflect your organization’s details.

Here is an example of what the CSR information prompt will look like:

---
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:Brooklyn
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Brooklyn Company
Organizational Unit Name (eg, section) []:Technology Division
Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
Email Address []:

If you want to non-interactively answer the CSR information prompt, you can do so by adding the -subjoption to any OpenSSL commands that request CSR information. Here is an example of the option, using the same information displayed in the code block above:

-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"

Now that you understand CSRs, feel free to jump around to whichever section of this guide that covers your OpenSSL needs.

Generating CSRs

This section covers OpenSSL commands that are related to generating CSRs (and private keys, if they do not already exist). CSRs can be used to request SSL certificates from a certificate authority.

Keep in mind that you may add the CSR information non-interactively with the -subj option, mentioned in the previous section.

Generate a Private Key and a CSR

Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

This command creates a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:

openssl req \
       -newkey rsa:2048 -nodes -keyout domain.key \
       -out domain.csr

Answer the CSR information prompt to complete the process.

The -newkey rsa:2048 option specifies that the key should be 2048-bit, generated using the RSA algorithm. The -nodes option specifies that the private key should not be encrypted with a pass phrase. The -new option, which is not included here but implied, indicates that a CSR is being generated.

Generate a CSR from an Existing Private Key

Use this method if you already have a private key that you would like to use to request a certificate from a CA.

This command creates a new CSR (domain.csr) based on an existing private key (domain.key):

openssl req \
       -key domain.key \
       -new -out domain.csr

Answer the CSR information prompt to complete the process.

The -key option specifies an existing private key (domain.key) that will be used to generate a new CSR. The -new option indicates that a CSR is being generated.

Generate a CSR from an Existing Certificate and Private Key

Use this method if you want to renew an existing certificate but you or your CA do not have the original CSR for some reason. It basically saves you the trouble of re-entering the CSR information, as it extracts that information from the existing certificate.

This command creates a new CSR (domain.csr) based on an existing certificate (domain.crt) and private key (domain.key):

openssl x509 \
       -in domain.crt \
       -signkey domain.key \
       -x509toreq -out domain.csr

The -x509toreq option specifies that you are using an X509 certificate to make a CSR.

Generating SSL Certificates

If you would like to use an SSL certificate to secure a service but you do not require a CA-signed certificate, a valid (and free) solution is to sign your own certificates.

A common type of certificate that you can issue yourself is a self-signed certificate. A self-signed certificate is a certificate that is signed with its own private key. Self-signed certificates can be used to encrypt data just as well as CA-signed certificates, but your users will be displayed a warning that says that the certificate is not trusted by their computer or browser. Therefore, self-signed certificates should only be used if you do not need to prove your service’s identity to its users (e.g. non-production or non-public servers).

This section covers OpenSSL commands that are related to generating self-signed certificates.

Generate a Self-Signed Certificate

Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you do not require that your certificate is signed by a CA.

This command creates a 2048-bit private key (domain.key) and a self-signed certificate (domain.crt) from scratch:

openssl req \
       -newkey rsa:2048 -nodes -keyout domain.key \
       -x509 -days 365 -out domain.crt

Answer the CSR information prompt to complete the process.

The -x509 option tells req to create a self-signed cerificate. The -days 365 option specifies that the certificate will be valid for 365 days. A temporary CSR is generated to gather information to associate with the certificate.

Generate a Self-Signed Certificate from an Existing Private Key

Use this method if you already have a private key that you would like to generate a self-signed certificate with it.

This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key):

openssl req \
       -key domain.key \
       -new \
       -x509 -days 365 -out domain.crt

Answer the CSR information prompt to complete the process.

The -x509 option tells req to create a self-signed cerificate. The -days 365 option specifies that the certificate will be valid for 365 days. The -new option enables the CSR information prompt.

Generate a Self-Signed Certificate from an Existing Private Key and CSR

Use this method if you already have a private key and CSR, and you want to generate a self-signed certificate with them.

This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key) and (domain.csr):

openssl x509 \
       -signkey domain.key \
       -in domain.csr \
       -req -days 365 -out domain.crt

The -days 365 option specifies that the certificate will be valid for 365 days.

View Certificates

Certificate and CSR files are encoded in PEM format, which is not readily human-readable.

This section covers OpenSSL commands that will output the actual entries of PEM-encoded files.

View CSR Entries

This command allows you to view and verify the contents of a CSR (domain.csr) in plain text:

openssl req -text -noout -verify -in domain.csr

View Certificate Entries

This command allows you to view the contents of a certificate (domain.crt) in plain text:

openssl x509 -text -noout -in domain.crt

Verify a Certificate was Signed by a CA

Use this command to verify that a certificate (domain.crt) was signed by a specific CA certificate (ca.crt):

openssl verify -verbose -CAFile ca.crt domain.crt

Private Keys

This section covers OpenSSL commands that are specific to creating and verifying private keys.

Create a Private Key

Use this command to create a password-protected, 2048-bit private key (domain.key):

openssl genrsa -des3 -out domain.key 2048

Enter a password when prompted to complete the process.

Verify a Private Key

Use this command to check that a private key (domain.key) is a valid key:

openssl rsa -check -in domain.key

If your private key is encrypted, you will be prompted for its pass phrase. Upon success, the unencrypted key will be output on the terminal.

Verify a Private Key Matches a Certificate and CSR

Use these commands to verify if a private key (domain.key) matches a certificate (domain.crt) and CSR (domain.csr):

openssl rsa -noout -modulus -in domain.key | openssl md5
openssl x509 -noout -modulus -in domain.crt | openssl md5
openssl req -noout -modulus -in domain.csr | openssl md5

If the output of each command is identical there is an extremely high probability that the private key, certificate, and CSR are related.

Encrypt a Private Key

This takes an unencrypted private key (unencrypted.key) and outputs an encrypted version of it (encrypted.key):

openssl rsa -des3 \
       -in unencrypted.key \
       -out encrypted.key

Enter your desired pass phrase, to encrypt the private key with.

Decrypt a Private Key

This takes an encrypted private key (encrypted.key) and outputs a decrypted version of it (decrypted.key):

openssl rsa \
       -in encrypted.key \
       -out decrypted.key

Enter the pass phrase for the encrypted key when prompted.

Convert Certificate Formats

All of the certificates that we have been working with have been X.509 certificates that are ASCII PEM encoded. There are a variety of other certificate encoding and container types; some applications prefer certain formats over others. Also, many of these formats can contain multiple items, such as a private key, certificate, and CA certificate, in a single file.

OpenSSL can be used to convert certificates to and from a large variety of these formats. This section will cover a some of the possible conversions.

Convert PEM to DER

Use this command if you want to convert a PEM-encoded certificate (domain.crt) to a DER-encoded certificate (domain.der), a binary format:

openssl x509 \
       -in domain.crt \
       -outform der -out domain.der

The DER format is typically used with Java.

Convert DER to PEM

Use this command if you want to convert a DER-encoded certificate (domain.der) to a PEM-encoded certificate (domain.crt):

openssl x509 \
       -inform der -in domain.der \
       -out domain.crt

Convert PEM to PKCS7

Use this command if you want to add PEM certificates (domain.crt and ca-chain.crt) to a PKCS7 file (domain.p7b):

openssl crl2pkcs7 -nocrl \
       -certfile domain.crt \
       -certfile ca-chain.crt \
       -out domain.p7b

Note that you can use one or more -certfile options to specify which certificates to add to the PKCS7 file.

PKCS7 files, also known as P7B, are typically used in Java Keystores and Microsoft IIS (Windows). They are ASCII files which can contain certificates and CA certificates.

Convert PKCS7 to PEM

Use this command if you want to convert a PKCS7 file (domain.p7b) to a PEM file:

openssl pkcs7 \
       -in domain.p7b \
       -print_certs -out domain.crt

Note that if your PKCS7 file has multiple items in it (e.g. a certificate and a CA intermediate certificate), the PEM file that is created will contain all of the items in it.

Convert PEM to PKCS12

Use this command if you want to take a private key (domain.key) and a certificate (domain.crt), and combine them into a PKCS12 file (domain.pfx):

openssl pkcs12 \
       -inkey domain.key \
       -in domain.crt \
       -export -out domain.pfx

You will be prompted for export passwords, which you may leave blank. Note that you may add a chain of certificates to the PKCS12 file by concatenating the certificates together in a single PEM file (domain.crt) in this case.

PKCS12 files, also known as PFX files, are typically used for importing and exporting certificate chains in Micrsoft IIS (Windows).

Convert PKCS12 to PEM

Use this command if you want to convert a PKCS12 file (domain.pfx) and convert it to PEM format (domain.combined.crt):

openssl pkcs12 \
       -in domain.pfx \
       -nodes -out domain.combined.crt

Note that if your PKCS12 file has multiple items in it (e.g. a certificate and private key), the PEM file that is created will contain all of the items in it.

OpenSSL Version

The openssl version command can be used to check which version you are running. The version of OpenSSL that you are running, and the options it was compiled with affect the capabilities (and sometimes the command line options) that are available to you.

The following command displays the OpenSSL version that you are running, and all of the options that it was compiled with:

openssl version -a

This guide was written using an OpenSSL binary with the following details (the output of the previous command):

OpenSSL 1.0.1f 6 Jan 2014
built on: Mon Apr  7 21:22:23 UTC 2014
platform: debian-amd64
options:  bn(64,64) rc4(16x,int) des(idx,cisc,16,int) blowfish(idx)
compiler: cc -fPIC -DOPENSSL_PIC -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -m64 -DL_ENDIAN -DTERMIO -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -Wl,-Bsymbolic-functions -Wl,-z,relro -Wa,--noexecstack -Wall -DMD32_REG_T=int -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM
OPENSSLDIR: "/usr/lib/ssl"

Conclusion

That should cover how most people use OpenSSL to deal with SSL certs! It has many other uses that were not covered here, so feel free to ask or suggest other uses in the comments.

If you are having issues with any of the commands, be sure to comment (and include your OpenSSL version output).

OpenSSL CSR with Alternative Names one-line

 

Generating key with alternative names:

openssl req -new -nodes -out svn-new.csr -newkey rsa:2048 -keyout svn-new.key -config <( cat csr_details.txt )

========

[root@svn Ali-altername]# cat csr_details.txt
[req]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn

[ dn ]
C=US
ST=California
L=Foster City
O=Guidewire Software
OU=IT
emailAddress=ashaik@companyname.com
CN = http://www.svn.companyname.com

[ req_ext ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = svn.companyname.com
DNS.2 = http://www.svn.companyname.com
DNS.3 = svn
[root@svn Ali-altername]#

 

root@master ~]# openssl req -new -sha256 -nodes -subj ‘/C=US/ST=New York/L=New York/O=IT/OU=Hosting Team/CN=www.domain.com/emailAddress=alishaika@gmail.com/subjectAltName=DNS.1=domain.com’ > www.domain.com.csr
Generating a 1024 bit RSA private key
….++++++
………………………++++++
writing new private key to ‘privkey.pem’

[root@master ~]# openssl req -text -noout -verify -in www.domain.com.csr
verify OK
Certificate Request:
Data:
Version: 0 (0x0)
Subject: C=US, ST=New York, L=New York, O=IT, OU=Hosting Team, CN=www.domain.com/emailAddress=alishaika@gmail.com/subjectAltName=DNS.1=domain.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption

Preparing Linux Template VMs

 

Step 0: Stop logging services.

/sbin/service rsyslog stop
/sbin/service auditd stop

You’re going to all this trouble to clean, might as well stop writing new data. Otherwise all your deployed VMs will have a log of you shutting the VM down. 🙂

Step 1: Remove old kernels

/bin/package-cleanup --oldkernels --count=1

You need yum-utils installed to get package-cleanup. This has to go before the yum cleanup in Step 2, it needs your channel data. I usually let the post-deployment configuration management take care of this, but this is nice when we create a new template for a intermediate/point release, or to cover a security hole.

Step 2: Clean out yum.

/usr/bin/yum clean all

Yum keeps a cache in /var/cache/yum that can grow quite large, especially after applying patches to the template. For example, the host where my blog resides has 275 MB of stuff in yum’s cache right now, just from a few months of incremental patching. In the interest of keeping my template as small as possible I wipe this.

Step 3: Force the logs to rotate & remove old logs we don’t need.

/usr/sbin/logrotate –f /etc/logrotate.conf
/bin/rm –f /var/log/*-???????? /var/log/*.gz
/bin/rm -f /var/log/dmesg.old
/bin/rm -rf /var/log/anaconda

Starting fresh with the logs is nice. It means that you don’t have old, irrelevant log data on all your cloned VMs, and it also means that your template image is smaller. Change out the “rm” command for one that matches whatever your logrotate renames files as. Also, if you get really, really bored it’s fun to look at the old log data people leave on virtual appliances & in cloud templates. Lots of leaked information there.

Step 4: Truncate the audit logs (and other logs we want to keep placeholders for).

/bin/cat /dev/null > /var/log/audit/audit.log
/bin/cat /dev/null > /var/log/wtmp
/bin/cat /dev/null > /var/log/lastlog
/bin/cat /dev/null > /var/log/grubby

This whole /dev/null business is also a trick that lets you clear a file without restarting the process associated with it, useful in many more situations than just template-building.

Step 5: Remove the udev persistent device rules.

/bin/rm -f /etc/udev/rules.d/70*

 

Step 6: Remove the traces of the template MAC address and UUIDs.

/bin/sed -i ‘/^(HWADDR|UUID)=/d’ /etc/sysconfig/network-scripts/ifcfg-eth0

This is a corollary to step 4, just removing unique identifiers from the template so the cloned VM gets its own. Thanks to Ed in the comments for the reminder about sed. You can also change the “-i” to “-i.bak” if you wished to keep a backup copy of the file.

Step 7: Clean /tmp out.

/bin/rm –rf /tmp/*
/bin/rm –rf /var/tmp/*

Under normal, non-template circumstances you really don’t ever want to run rm on /tmp like this. Use tmpwatch or any manner of safer ways to do this, since there are attacks people can use by leaving symlinks and whatnot in /tmp that rm might traverse (“whoops, I don’t have an /etc/passwd anymore!”). Plus, users and processes might actually be using /tmp, and it’s impolite to delete their files. However, this is your template image, and if there are people attacking your template you should reconsider how you’re doing business. Really.

Step 8: Remove the SSH host keys.

/bin/rm –f /etc/ssh/*key*

If you don’t do this all your VMs will have all the same keys, which has negative security implications. It’s also annoying to fix later when you’ve realized you’ve deployed a couple of years of VMs and forgot to do this in your prep script. Not that I would know anything about that. Nope.

Step 9: Remove the root user’s shell history.

/bin/rm -f ~root/.bash_history
unset HISTFILE

This good idea is courtesy of Jonathan Barber, from the comments below. No sense in keeping this history around, it’s irrelevant to the cloned VM.

Step 10: Remove the root user’s SSH history & other cruft.

/bin/rm -rf ~root/.ssh/
/bin/rm -f ~root/anaconda-ks.cfg

You might choose to just remove ~root/.ssh/known_hosts if you have SSH keys you want to keep around.

Step 11: Zero out all free space, then use storage vMotion to re-thin the VM.

#!/bin/sh

# Determine the version of RHEL
COND=`grep -i Taroon /etc/redhat-release`
if [ "$COND" = "" ]; then
        export PREFIX="/usr/sbin"
else
        export PREFIX="/sbin"
fi

FileSystem=`grep ext /etc/mtab| awk -F" " '{ print $2 }'`

for i in $FileSystem
do
        echo $i
        number=`df -B 512 $i | awk -F" " '{print $3}' | grep -v Used`
        echo $number
        percent=$(echo "scale=0; $number * 98 / 100" | bc )
        echo $percent
        dd count=`echo $percent` if=/dev/zero of=`echo $i`/zf
        /bin/sync
        sleep 15
        rm -f $i/zf
done

VolumeGroup=`$PREFIX/vgdisplay | grep Name | awk -F" " '{ print $3 }'`

for j in $VolumeGroup
do
        echo $j
        $PREFIX/lvcreate -l `$PREFIX/vgdisplay $j | grep Free | awk -F" " '{ print $5 }'` -n zero $j
        if [ -a /dev/$j/zero ]; then
                cat /dev/zero > /dev/$j/zero
                /bin/sync
                sleep 15
                $PREFIX/lvremove -f /dev/$j/zero
        fi
done

This script is partly ripped off from someone on the Internet who didn’t have a copyright note in their work (and we’ve lost track of the source – if it’s yours leave me a comment), and partly the work of my team. It basically fills each filesystem to 98% of full with the output of /dev/zero, as well as creating a logical volume to zero out the unused space in the volume groups. Why do this? Well, if you storage vMotion the template VM to another array, or to another datastore on an array without VAAI, and you specify thin provisioning, the software datamover will suck all the zeroes back out of the image, and it’ll be as small as possible. Keep in mind you can’t do this within an array using VAAI, because under VAAI the array does the copying, and the zero-sucking magic is only in the software datamover at the ESXi level. Just move it to a local disk and back to your array if that’s the case. This is also cool if you have storage that deduplicates, too, like NetApp arrays.

Why only to 98%? That way you can run it on operational VMs and it lessens the chance of causing something to crash because you filled the filesystem. 🙂 On the templates you can probably push it to 100%, just adjust the math in bc.

Keep in mind that by writing zeroes to the free space you effectively un-thin the disks, so make sure you have enough space available in your datastore.

So that’s my prep routine. It relies heavily on keeping the rest of the VM clean, and only cleans up what we can’t avoid sullying. What else am I missing here? Leave me a comment!

 

Referenece : https://lonesysadmin.net/

Motivation

VM template is used in oVirt to later create VMs with identical images and configuration as the template.

Creating identical images and configuration does not mean that we want to keep some information that is guest specific, like the VM MAC addresses.

For Handling the above we have the process of sysprep. For guests with Windows OS you can use the current sysprep mechanism we have in oVirt. For Linux guests we don’t have such process in place yet so you better seal the template manually.

The process for sealing a Linux guest template

The following is RedHat specific:

  1. SSH to the VM as root
  2. flag the system for reconfiguring
  3. touch /.unconfigured
  4. Remove ssh host keys:
  5. rm -i /etc/ssh/ssh_host_*
  6. Optionally, for environments where a host cannot determine its own name via DNS based lookups:
  7. echo “HOSTNAME=localhost.localdomain” » /etc/sysconfig/network
  8. Remove UDEV rules:
  9. rm -i /etc/udev/rules.d/70-persistent*
  10. Remove the HWADDR= line from /etc/sysconfig/network-scripts/ifcfg-*
  11. [optionally] Delete the logs from /var/log
  12. [Optionally] Delete the build logs from /root.
  13. Shut down the virtual machine.

CentOS / RHEL 7 : How to password protect GRUB2 menu entries

Why should a Linux boot loader have password protection?The following are the primary reasons for password protecting a Linux boot loader:

1. Preventing Access to Single User Mode – If an attacker can boot into single user mode, he becomes the root user.
2. Preventing Access to the GRUB Console – If the machine uses GRUB as its boot loader, an attacker can use the GRUB editor interface to change its configuration or to gather information using the cat command.
3. Preventing Access to Non-Secure Operating Systems – If it is a dual-boot system, an attacker can select at boot time an operating system, such as DOS, which ignores access controls and file permissions.

Password protecting GRUB2

Follow the steps below to password protect GRUB2 in RHEL 7.
1. Remove –unrestricted from the main CLASS= declaration in /etc/grub.d/10_linux file.
This can be done by using sed to replace the

# sed -i “/^CLASS=/s/ –unrestricted//” /etc/grub.d/10_linux
2. If a user hasn’t already been configured, use grub2-setpassword to set a password for the root user :

# grub2-setpassword
This creates a file /boot/grub2/user.cfg if not already present, which contains the hashed GRUB bootloader password. This utility only supports configurations where there is a single root user.
Example /boot/grub2/user.cfg file :

# cat /boot/grub2/user.cfg
GRUB2_PASSWORD=grub.pbkdf2.sha512.10000.CC6F56BFCFB90C49E6E16DC7234BF4DE4159982B6D121DC8EC6BF0918C7A50E8604CA40689A8B26EA01BF2A76D33F7E6C614E6289ABBAA6944ECB2B6DEB2F3CF.4B929016A827C36142CC126EB47E86F5F98E92C8C2C924AD0C98436E4699DF7536894F69BB904FDB5E609B9A5D67E28A7D79E8521C0B0AE6C031589FA0452A21
3. Recreate the grub config with grub2-mkconfig :

# grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file …
Found linux image: /boot/vmlinuz-3.10.0-327.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-327.el7.x86_64.img
Found linux image: /boot/vmlinuz-0-rescue-f9725b0c842348ce9e0bc81968cf7181
Found initrd image: /boot/initramfs-0-rescue-f9725b0c842348ce9e0bc81968cf7181.img
done
4. Reboot the server and verify.

# shutdown -r now
Note that all defined grub menu entries will now require entering user & password each time at boot; henceforth, the system will not boot any kernel without direct user intervention from the console. When prompted for user, enter “root”. When prompted for password, enter whatever was passed to the grub2-setpassword command :
Remove password protection
To remove the password protection we can add the –unrestricted text in the main CLASS= declaration in /etc/grub.d/10_linux file again. Another way is to remove the /boot/grub2/user.cfg file which stores the hashed GRUB bootloader password.

Restricting only GRUB menu entry editing
If you only want to simply prevent users from entering the grub command line and edit menu entries (as opposed to completely locking menu entries), then all that is needed is execution of grub2-setpassword command.

 

How to remove the grub password in Red Hat Enterprise Linux 7?

 

Environment

Red Hat Enterprise Linux 7

Issue

  • How to remove the grub password protection when the password is lost?

Resolution

  • Enabling grub password generates the user.cfg file
[root@localhost grub2]# ls
device.map  fonts  grub.cfg  grubenv  i386-pc  locale  themes  user.cfg
  • Remove the user.cfg file
[root@localhost grub2]# rm -rf user.cfg
  • Recreate the grub config with grub2-mkconfig

For BIOS-based machines:

grub2-mkconfig -o /boot/grub2/grub.cfg

For UEFI-based machines:

grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg
  • Reboot and test

Enabler root login in Ubuntu

Eensure you have openssh-server server installed sudo apt-get install openssh-server

sudo nano /etc/ssh/sshd_config

change

PermitRootLogin prohibit-password

to

PermitRootLogin yes

or sudo sed -i ‘s/prohibit-password/yes/’ /etc/ssh/sshd_config

in order to PAM authentication add

AllowUsers root

or sudo echo “AllowUsers root” >> /etc/ssh/sshd_config

sudo service ssh restart

works fine

in order you don’t know your root password set new with privileged user

sudo passwd root

and you may want to get rid of password prompt in safe way what may be useful approach for sth like rsync, ansible and so on, so probably

from where ever you want to connect

ssh-keygen; ssh-copy-id -i ~/.ssh/id_rsa.pub root@YOURHOST

enter the root pass you have just set and DONE

ssh root@YOURHOST

 

and enable password autthenticaiton to yes in /etc/ssh/sshd_config

& # To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes

create sftp user.

[root@ftp ~]# cat create-sftp-user.sh
#!/bin/bash
set -e
#set -x

EXPECTED_ARGS=1
E_BADARGS=65

if [ $# -ne $EXPECTED_ARGS ]
then
echo “Usage: `basename $0` <username>”
exit $E_BADARGS
fi

useradd -g sftponly -d /workspace -s /sbin/nologin $1
passwd $1
mkdir /sftp/$1
mkdir /sftp/$1/workspace
chown $1:sftponly /sftp/$1/workspace
exit 0
[root@ftp ~]#

Setting up SSL for your Nodes

To generate a new certificate:

  1. Generate a Private Key and Certificate Signing Request (CSR) using OpenSSL.

    In a Terminal window, run the following command (where my_key_name.key is the name of the unique key that you are creating and my_csr_name.csr is the name of your CSR):

    # openssl req -new -nodes -keyout my_key_name.key -out my_csr_name.csr
  2. At the prompt, enter your X.509 certificate attributes.
    Important: The Common Name field must be filled in with the fully qualified domain name of the server to be protected by SSL. If you are generating a certificate for an organization outside the U.S., go to https://www.iso.org/obp/ui/, select Country codes, and click  to view a list of two-letter ISO country codes.
    Generating a 1024 bit RSA private key
    ....................++++++
    ................++++++
    writing new private key to 'my_key_name.key'
    -----
    You are about to be asked to enter information that will be incorporated
    into your certificate request.
    What you are about to enter is what is called a Distinguished Name or a DN.
    There are quite a few fields but you can leave some blank
    For some fields there will be a default value,
    If you enter '.', the field will be left blank.
    -----
    Country Name (2 letter code) [US]:Your_2_letter_ISO_country_code
    State or Province Name (full name) [Some-State]:Your_State_Province_or_County
    Locality Name (eg, city) []:Your_City
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Your_Company
    Organizational Unit Name (eg, section) []:Your_Department
    Common Name (i.e., your server's hostname) []:secure.yourwebsite.com
    Email Address []:johndoe@yourwebsite.com
    

    You are also prompted to input “extra” attributes, including an optional challenge password.

    Note: Manually entering a challenge password when starting the server can be problematic in some situations, for example, when starting the server from the system boot scripts. Skip entering a challenge password by pressingEnter.
    ...
    Please enter the following 'extra' attributes
    to be sent with your certificate request
    A challenge password []:
    An optional company name []:
    

    After finalizing the attributes, the private key and CSR are saved to your root directory.

    Important: If you make a mistake when running the OpenSSL command, you may discard the generated files and run the command again. After successfully generating your key and CSR, be sure to guard your private key, as it cannot be re-generated.
  3. If required, send the CSR to your Certifying Authority (CA).

    Once completed, you will have a valid, signed certificate.

    Note: Some certificate authorities provide a CSR generation tool on their website. For additional information, check with your CA.
  4. If required, generate a self-signed certificate.

    You may need to generate a self-signed certificate for the following reasons:

    • You don’t plan on having your certificate signed by a CA.
    • You plan to test your new SSL implementation while the CA is signing your certificate.

    To generate a self-signed certificate through OpenSSL, run the following command:

    # openssl x509 -req -days 365 -in my_csr_name.csr -signkey my_key_name.key -out my_cert_name.crt

    This creates a certificate that is valid for 365 days.

  5. Create the .pem file.
—FYI

Your keys may already be in PEM format, but just named with .crt or .key.

If the file’s content begins with -----BEGIN and you can read it in a text editor:

The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.

If the file is in binary:

For the server.crt, you would use

openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem

For server.key, use openssl rsa in place of openssl x509.

The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.

If this is for a Web server and you cannot specify loading a separate private and public key:

You may need to concatenate the two files. For this use:

cat server.crt server.key > server.includesprivatekey.pem

I would recommend naming files with “includesprivatekey” to help you manage the permissions you keep with this file.