Docker’s restart policy is the best way to have containers automatically start when you boot your server or computer. That should be the end of this post, but I’ll provide more details, examples, and reasons why you want to avoid other methods.
Docker’s restart policy is a flag you set when you first create a container from an image. The restart policy dictates whether the container should restart when it exits. The behavior is determined by which policy you choose. The container can automatically start again on erroneous exits or with all exit codes. The flag also affects the behavior of what happens if you manually stop a container.
Set Restart Policy
You can set the Docker restart policy when creating a container or update an existing container with a new restart policy.
The restart policy flag is --restart and has four different options. For more details, read the official Docker Restart Policy page.
Option
Details
no
Do not automatically restart the container. (the default)
on-failure
Restart the container if it exits due to an error, which manifests as a non-zero exit code.
always
Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted.
unless-stopped
Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.
The following command will create a container that will always restart. The majority of my containers use “always” or “unless-stopped.”
# docker run -d --restart always <image>
To update an existing container’s restart policy, use docker update with the policy you want. The update command can modify multiple containers at the same time.
Once you have your containers running with a restart policy, you need to enable the Docker service. If the Docker daemon doesn’t start automatically, none of your containers will start.
Depending on your system, the process to enable the Docker daemon will vary. Enable the service within systemd by using the systemctl command.
# systemctl enable docker
For other init systems, you’ll have to research how to enable services. It will likely be a single command you have to run or create a symbolic link.
You can verify that the service has been enabled by checking the enabled status using systemctl.
# systemctl is-enabled docker
You can get a more detailed status of the docker service by running the following systemctl command. The output will include a log to help solve any issues that may be arising.
# systemctl status docker
Avoid Systemd Services
Many posts online outline creating a systemd service file to start Docker containers. I recommend avoiding this unless you have a good reason to do so.
Docker’s built-in restart policy has better control of handling when the container should restart. The restart policy also reduces complexity in a few different ways. Firstly, it doesn’t require you to create a unique service file for each container. Secondly, all of your Docker services will be within the docker daemon and not scattered throughout the system.
I’ve written service files before for containers when I needed pre and post-tasks before and after the container was created and destroyed. Ideally, your container shouldn’t need any outside tasks. In the real world, there are times when you need to get something working until you can come up with a proper solution.
Setting up e-mail notifications and alerts when a user signs in through SSH requires a shell script and a small modification to PAM. Keep in mind that if you’re setting up this alert for security, then you probably want to look at locking down your system first and securing all of your services instead of just receiving alerts. This notification can be useful as an extra alert for logins, but don’t rely on it as a security feature because you won’t always be monitoring your e-mail, and once an attacker signs into your server, it’s too late.
This tutorial was tested on a Debian Stretch server using EXIM as the MTA and using the mail command from GNU Mailutils. Depending on your current Linux distribution and the services you have installed, the tutorial may vary slightly and require additional modifications.
Creating the Shell Script
The first part of this tutorial is to create a shell script that will send an e-mail. Since we are integrating the script with PAM, there are a few environment variables provided by pam_exec we have access to which will be useful to include in the e-mail. This script assumes you have EXIM configured to send outgoing e-mails. Slight modifications may be required if you are using Sendmail, Postfix, or any other MTA.
#!/bin/sh
EMAIL_TO="sysadmin@example.com"EMAIL_FROM="ssh-alert@server1.example.com"SUBJECT="SSH Login Notification"MESSAGE="
A user signed into your server through SSH.
-------------------------------------------
Username: ${PAM_USER}IP Address: ${PAM_RHOST}"if[${PAM_TYPE}="open_session"]; thenecho"${MESSAGE}" | mail -n -r "${EMAIL_FROM}" -s "${SUBJECT}""${EMAIL_TO}"fiexit0
Once your script is created, be sure to set the permissions of the script to be executable and only allow the root user to edit the file. Creating the directory /etc/pam_scripts is a nice location to store all custom scripts you add to PAM, some users opt to store the scripts directly in the /etc/pam.d folder. To test your script from the command line, you will want to comment out the if statement around the mail command by prefixing the lines with the pound symbol. Test your script and make sure you receive the e-mail notification. The test e-mail will be void of values for the username and IP address because those environment variables are not set and will only be available when PAM runs the script.
Configuring PAM
Now it’s time to configure PAM to run the script you created. By default, OpenSSH creates the file /etc/pam.d/sshd, and you will need to edit the file to include the location of the script above. Open /etc/pam.d/sshd with your favorite editor as root (nano, vim, etc) and add the following lines to the configuration file.
There is no need for a system or service restart for the script to start running after authentication. There is a lot of additional information you should read about Running Scripts after Authentication along with additional troubleshooting techniques, script and file permissions, and why using PAM is better than other techniques.
Troubleshooting
If you are running into problems with receiving an e-mail notification after a user signs in through SSH, some of the below solutions may help you out. First, you want to make sure your script is set as executable. Run the command chmod +x <script> to set the shell script to be executable.
The problem could also exist if you don’t have a MTA or your MTA doesn’t provide the sendmail command that mail from GNU Mailutils uses to send messages. First look into the log file for your MTA and check for any issues. If nothing stands out, consider changing the shell script from using the mail command to sendmail.
If your script runs fine by itself but fails to run when signing in through SSH, you will want to look at the post “Running Scripts after SSH Authentication” and follow those troubleshooting techniques. It could also be useful to read through the article even if you don’t have any issues to confirm all modifications you made to PAM and your sshd_config file are correct.
Learn how to harden your OpenSSH server to limit abuse and protect against unauthorized users. Change these few configuration options to secure your SSH server.
Learn about the interesting tool MultiSSH (MSSH) that allows you to connect to multiple SSH servers and run the same command on all of them simultaneously.
Learn how to run scripts automatically after a user signs in through SSH or any other authentication service on your server that uses the Pluggable Authentication Module PAM.
LINUXDadan — December 14, 2022 3:03 pmComments off
Otentikasi dua faktor (2FA) adalah proses login yang terdiri dari mekanisme otentikasi ganda. Implementasi yang paling dikenal mencakup SMS klasik atau konfirmasi kode email untuk browser dan perangkat baru/tidak dikenal.
Dalam skenario ini, bahkan jika seorang peretas mendapatkan password PayPal atau hosting, dia tidak akan dapat masuk tanpa kode konfirmasi yang dikirimkan ke telepon atau email korban.
Menerapkan autentikasi dua faktor adalah salah satu praktik terbaik untuk melindungi email, akun jejaring sosial, hosting, dan lainnya. Sayangnya, sistem kami tidak terkecuali.
Tutorial ini menunjukkan cara menerapkan otentikasi dua faktor untuk melindungi akses SSH Anda menggunakan Google Authenticator atau Authy-ssh. Google Authenticator memungkinkan Anda memverifikasi login menggunakan aplikasi seluler, sementara Authy-ssh dapat diterapkan tanpa aplikasi menggunakan verifikasi SMS.
Otentikasi Dua Faktor Linux Menggunakan Google Authenticator
Catatan: Sebelum melanjutkan, pastikan Anda telah menginstal Google Authenticator di perangkat seluler Anda.
Untuk memulai, jalankan perintah berikut untuk menginstal Google Authenticator (distribusi Linux berbasis Debian):
sudo apt install libpam-google-authenticator -y
Untuk menginstal Google Authenticator pada distribusi Linux berbasis Red Hat (CentOS, Fedora), jalankan perintah berikut:
sudo dnf install google-authenticator -y
Setelah terinstal, jalankan Google Authenticator seperti yang ditunjukkan pada gambar di bawah.
google-authenticator
Seperti yang Anda lihat, kode QR muncul. Anda perlu menambahkan akun baru dengan mengklik+ ikon di Aplikasi Google Authenticator seluler Anda dan pilih Scan QR code.
Google Authenticator juga akan memberikan kode cadangan yang perlu Anda cetak dan simpan jika Anda kehilangan akses ke perangkat seluler Anda.
Anda akan ditanya beberapa pertanyaan, yang dirinci di bawah ini, dan Anda dapat menerima semua opsi default dengan memilih Y untuk semua pertanyaan:
Setelah memindai kode QR, proses instalasi akan memerlukan izin untuk mengedit rumah Anda. tekanY untuk melanjutkan ke pertanyaan berikutnya.
Pertanyaan kedua merekomendasikan untuk menonaktifkan banyak login menggunakan kode verifikasi yang sama. tekanY untuk melanjutkan.
Pertanyaan ketiga mengacu pada waktu kadaluwarsa untuk setiap kode yang dihasilkan. Sekali lagi, Anda dapat membiarkan waktu condong, tekanY untuk melanjutkan.
Aktifkan pembatasan kecepatan, hingga 3 upaya masuk setiap 30 detik. tekanY untuk melanjutkan.
Setelah Google Authenticator diinstal, Anda perlu mengedit file /etc/pam.d/sshduntuk menambahkan modul otentikasi baru. Gunakan nano atau editor lain seperti yang ditunjukkan pada gambar di bawah untuk mengedit file /etc/pam.d/sshd:
nano /etc/pam.d/sshd
Tambahkan baris berikut ke /etc/pam.d/sshd seperti yang ditunjukkan pada gambar di bawah ini:
auth required pam_google_authenticator.so nullok
Catatan: Instruksi Red Hat menyebutkan baris yang mengandung#auth substack password-auth. Jika Anda menemukan baris ini di /etc/pam.d./sshd Anda, beri komentar.
Simpan /etc/pam.d./sshd dan edit filenya /etc/ssh/sshd_config seperti yang ditunjukkan pada contoh di bawah ini:
nano /etc/ssh/sshd_config
Temukan baris:
#ChallengeResponseAuthentication no
Batalkan komentar dan ganti no dengan yes:
ChallengeResponseAuthentication yes
Keluar dari penyimpanan perubahan dan mulai ulang service SSH:
sudo systemctl restart sshd.service
Anda dapat menguji otentikasi dua faktor dengan menghubungkan ke localhost Anda seperti yang ditunjukkan di bawah ini:
ssh localhost
Anda dapat menemukan kode di aplikasi seluler Google Authentication. Tanpa kode ini, tidak ada yang dapat mengakses perangkat Anda melalui SSH. Catatan: kode ini berubah setelah 30 detik. Karena itu, Anda perlu memverifikasinya dengan cepat.
Seperti yang Anda lihat, proses 2FA berhasil. Di bawah ini Anda dapat menemukan petunjuk untuk penerapan 2FA yang berbeda menggunakan SMS alih-alih aplikasi seluler.
Otentikasi Dua Faktor Linux Menggunakan Authy-ssh (SMS)
Anda juga dapat menerapkan otentikasi dua faktor menggunakan Authy (Twilio). Untuk contoh ini, aplikasi seluler tidak akan diperlukan, dan prosesnya akan dilakukan melalui verifikasi SMS.
Untuk memulai, buka https://www.twilio.com/try-twilio dan mengisi formulir pendaftaran.
Tulis dan verifikasi nomor telepon Anda:
Buka https://www.twilio.com/console/authy/applications dan klik Aplikasi yang Anda buat pada langkah sebelumnya:
Setelah dipilih, Anda akan melihat opsi di menu sebelah kiri Settings. KlikSettings dan copy PRODUCTION API KEY. Kami akan menggunakannya dalam langkah-langkah berikut:
Dari konsol, download authy-ssh menjalankan perintah berikut:
git clone https://github.com/authy/authy-ssh
Kemudian, masukkan direktori authy-ssh:
cd authy-ssh
Di dalam direktori authy-ssh jalankan:
sudo bash authy-ssh install /usr/local/bin
Anda akan diminta untuk menempelkan PRODUCTION API KEY Saya meminta Anda untuk menyalin, menempel, dan menekan ENTER untuk melanjutkan.
Ketika ditanya tentang tindakan default ketika api.authy.com tidak dapat dihubungi, pilih 1. Dan tekanENTER.
Catatan: Jika Anda menempelkan kunci API yang salah, Anda dapat mengeditnya di file/usr/local/bin/authy-ssh.confseperti yang ditunjukkan pada gambar di bawah ini. Ganti konten setelah “api_key=” dengan kunci API Anda:
Aktifkan authy-ssh dengan menjalankan:
sudo /usr/local/bin/authy-ssh enable `whoami`
Isi informasi yang diperlukan dan tekan Y:
Anda dapat menguji eksekusi authy-ssh:
authy-ssh test
Seperti yang Anda lihat, 2FA berfungsi dengan baik. Mulai ulang service SSH, jalankan:
sudo service ssh restart
Anda juga dapat mengujinya dengan menghubungkan melalui SSH ke localhost:
Seperti yang diilustrasikan, 2FA bekerja dengan sukses.
Authy menawarkan opsi 2FA tambahan, termasuk verifikasi aplikasi seluler. Anda dapat melihat semua produk yang tersedia dihttps://authy.com/.
Kesimpulan:
Seperti yang Anda lihat, 2FA dapat dengan mudah diimplementasikan oleh semua level user Linux. Kedua opsi yang disebutkan dalam tutorial ini dapat diterapkan dalam beberapa menit.
Ssh-authy adalah opsi yang sangat baik untuk user tanpa ponsel cerdas yang tidak dapat menginstal aplikasi seluler.
Implementasi verifikasi dua langkah dapat mencegah semua jenis serangan berbasis login, termasuk serangan rekayasa sosial, yang banyak di antaranya menjadi usang dengan teknologi ini karena password korban tidak cukup untuk mengakses informasi korban.
Alternatif Linux 2FA lainnya termasuk FreeOTP (Red Hat), World Authenticator, dan OTP Client, tetapi beberapa opsi ini hanya menawarkan autentikasi ganda dari perangkat yang sama.
Saya harap Anda menemukan tutorial ini bermanfaat. Ikuti terus Linux Hint untuk tips dan tutorial Linux lainnya.
This tutorial will be showing you how to set up Guacamole remote desktop on Ubuntu 22.04/20.04 server. Guacamole is a free, open-source remote desktop gateway developed by the Apache software foundation.
Guacamole Features
It allows you to access your remote desktop from a web browser. No other software needs to be installed on the client-side.
Supports standard protocols like VNC, RDP, SSH and Kubernetes.
VNC sessions can be recorded graphically.
Single Sign-on with CAS, OpenID Connect or SAML 2.0
Wake-on-LAN
Easily manage multiple remote desktop sessions.
Supports TOTP two-factor authentication.
Supports clipboard (copy and paste) and file transfer via SFTP.
Supports audio input and output
and more.
Guacamole itself is not a remote desktop protocol. It’s a proxy between the remote desktop and the client, so the remote desktop can be displayed and controlled in a web browser.
Step 1: Build the Guacamole Server From Source
Log in to your Ubuntu 22.04/20.04 server and install dependency packages.
Apache Tomcat will listen on port 8080, as can been shown with:
sudo ss -lnpt | grep java
If you have other software that listens on port 8080, then Tomcat can’t bind to port 8080. You should configure the other process to use a different port, then restart Tomcat (sudo systemctl restart tomcat9).
Add the following lines in this file. Some folks might say you don’t need to add these lines because they are the default values. I show you a basic configuration, so you can customize it when the need arises.
# Hostname and port of guacamole proxy
guacd-hostname: localhost
guacd-port: 4822
# Auth provider class (authenticates user/pass combination, needed if using the provided login screen)
auth-provider: net.sourceforge.guacamole.net.basic.BasicFileAuthenticationProvider
basic-user-mapping: /etc/guacamole/user-mapping.xml
Save and close the file. The default authentication module in Guacamole reads usernames and passwords from an XML file: /etc/guacamole/user-mapping.xml. Before creating this file, we need to generate an MD5 hash for your password with the following command. Replace your_password with your preferred password.
echo -n your_password | openssl md5
Sample output:
(stdin)= 1060b7b46a3bd36b3a0d66e0127d0517
Next, create the user mapping XML file.
sudo nano /etc/guacamole/user-mapping.xml
Add the following lines. Here we specify that the backend will use VNC (Vritual Network Computing) protocol. Replace the username and the password hash. We will create a VNC password later.
Save and close the file. Restart Tomcat and guacd.
sudo systemctl restart tomcat9 guacd
Step 4: Install a Desktop Environment on Ubuntu 22.04/20.04 Server
Since we are going to set up a remote desktop, we need a desktop environment. Make sure your server has enough RAM before installing a desktop environment. There are many desktop environments. I found the lightweight XFCE desktop environment works well with VNC, so install it with the following command.
sudo apt install xfce4 xfce4-goodies firefox
During installation, you may be asked to choose a default display manager. This choice doesn’t matter much, because you will not see the login screen in a VNC session.
Since there’s a desktop environment running on the server, it’s strongly recommended that you use a firewall like UFW to restrict access and open only the necessary ports to the public. You can read the following tutorial to learn how to enable and use UFW on Ubuntu.
Step 5: Install a VNC Server on Ubuntu 22.04/20.04 Server
There are several VNC server software available for Linux users. We are going to use TigerVNC server because it works best with Guacamole.
sudo apt install tigervnc-standalone-server
Run the following command to start the VNC server.
vncserver
When TigerVNC first starts, it asks you to set a VNC password. Note that the password should not be more than 8 characters. Then you can choose if you need a view-only password.
Now you should edit the /etc/guacamole/user-mapping.xml file and change the VNC password. Then restart Tomcat and guacd.
sudo systemctl restart tomcat9 guacd
The vncserver command creates two files under your home directory.
~/.Xauthrirty
~/.vnc/xstartup
The xstartup file specifies the applications that will be started by TigerVNC server. Edit this file.
nano ~/.vnc/xstartup
Change
#!/bin/sh
to
#!/bin/bash
Because Bash is the standard Shell on Linux. Then comment out the following lines. (Add a # character at the beginning of each line).
Next, add the following line at the bottom, which will make TigerVNC server start the LXQT desktop environment. The startxfce4 binary is installed by the xfce4-session package.
startxfce4 &
Save and close the file.
Troubleshooting
If your tigerVNC server didn’t create the ~/.vnc/xstartup file and the VNC server failed like below:
Then you can manually create the file.
nano ~/.vnc/xstartup
Add the following lines in the file.
#!/bin/sh
xrdb $HOME/.Xresources
startxfce4 &
Save and close the file.
Creating A Systemd Service
TigerVNC server doesn’t ship with any systemd service units. To make it start at boot time, we need to create a systemd service unit.
sudo nano /etc/systemd/system/vncserver@.service
Add the following lines in the file. Replace username with your real username.
[Unit]
Description=a wrapper to launch an X server for VNC
After=syslog.target network.target
[Service]
Type=forking
User=username
Group=username
WorkingDirectory=/home/username
ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 -localhost :%i
ExecStop=/usr/bin/vncserver -kill :%i
[Install]
WantedBy=multi-user.target
Save and close the file. Stop the current VNC server instance.
vncserver -kill :1
Start the VNC server with systemd.
sudo systemctl start vncserver@1.service
Enable auto-start at boot time.
sudo systemctl enable vncserver@1.service
Check its status:
systemctl status vncserver@1.service
As you can see, it’s active (running).
Now TigerVNC Server listens on port 5901.
sudo ss -lnpt | grep vnc
Step 6: Set Up a Reverse Proxy for the Guacamole Web Application
Apache Tomcat is listening on port 8080. To have an easy way to access the Guacamole web application, we can set up a reverse proxy with Apache or Nginx, so end-users will be able to use a domain name to access the web application. It also allows us to easily install a TLS certificate to encrypt the connection.
Apache
If you prefer to use Apache, then install Apache from the default Ubuntu software repository.
sudo apt install apache2
To use Apache as a reverse proxy, we need to enable the proxy modules and the header module.
Add the following lines in the file. Replace guacamole.example.com with your own domain name. Remember to create an A record for the sub-domain in your DNS manager. If you don’t have a real domain name, I recommend going to NameCheap to buy one. The price is low and they give whois privacy protection free for life.
Now you can access the Apache Guacamole login page via guacamole.example.com. If you see the “invalid request” or a similar error message, it could mean that Apache Tomcat can’t bind to port 8080, because this port is already taken by another process on the server. You should configure the other process to use a different port, then restart Tomcat.
Nginx
If you prefer to use Nginx, then install Nginx from the default Ubuntu software repository.
sudo apt install nginx
Create a server block file for Guacamole.
sudo nano /etc/nginx/conf.d/guacamole.conf
Add the following lines in the file. Replace guacamole.example.com with your own domain name. Remember to create an A record for the sub-domain in your DNS manager. If you don’t have a real domain name, I recommend going to NameCheap to buy one. The price is low and they give whois privacy protection free for life.
Save and close this file. Then test Nginx configuration.
sudo nginx -t
If the test is successful, reload Nginx for the change to take effect.
sudo systemctl reload nginx
Now you can access the Apache Guacamole login page via guacamole.example.com. If you see the “invalid request” or a similar error message, it could mean that Apache Tomcat can’t bind to port 8080, because this port is already taken by another process on the server. You should configure the other process to use a different port, then restart Tomcat.
Enable HTTPS
To encrypt the HTTP traffic when you visit the Guacamole web interface, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following command to install Let’s Encrypt client (certbot) on Ubuntu 22.04/20.04.
sudo apt install certbot
If you use Apache, then you need to install the Certbot Apache plugin.
sudo apt install python3-certbot-apache
Next, run the following command to obtain and install TLS certificate.
--hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
--staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.
The certificate should now be obtained and automatically installed.
And you can access Guacamole web interface via HTTPS. (https://guacamole.example.com).
After logging in, you will be able to use the remote desktop.
Warning: Some desktop environments will suspend the system if there’s no user activity. If you install a desktop environment on a cloud VPS, make sure you disable the suspend function in your desktop environment.
Wrapping UP
I hope this tutorial helped you set up Apache Guacamole remote desktop on Ubuntu 22.04/20.04 server. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂