Ops

Operation Tips #

Common Commands #

IP address #

# Public
curl ipinfo.io/ip
# Local
ip address show 

Show detail a command #

man <command>
# E.g
man vim
# Then press q to quit

Best practice before install anything #

sudo apt update
sudo apt upgrade

Show package detail #

apt show <package-name>
# E.g 
apt show ssh
E.g output
Package: ssh
Version: 1:9.6p1-3ubuntu13.5
Priority: optional
Section: net
Source: openssh
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Debian OpenSSH Maintainers <debian-ssh@lists.debian.org>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 57.3 kB
Depends: openssh-client (>= 1:9.6p1-3ubuntu13.5), openssh-server (>= 1:9.6p1-3ubuntu13.5)
Homepage: https://www.openssh.com/
Download-Size: 4,658 B
APT-Sources: http://vn.archive.ubuntu.com/ubuntu noble-updates/main amd64 Packages
Description: secure shell client and server (metapackage)
 This metapackage is a convenient way to install both the OpenSSH client
 and the OpenSSH server. It provides nothing in and of itself, so you
 may remove it if nothing depends on it.
pwd

Copy #

cp <source> <destination>
# E.g
cp readme.md readyou.md # create a copy named readyou with the same content as readme

Clear directory #

rm -rf <directory-name>

Move #

mv <source> <destination>
# E.g
mv readme.md .. # Move readme file to parent dir
mv ../readme.md . # Move readme from parent dir to current dir

Rename #

  • If you move a file within the current directory, that means you are renaming it
mv <old-name> <new-name>
# E.g
mv readme.md readyou.md

Create #

# Directory: 
mkdir <dir-name>
# File: 
touch <file-name>
cat <file-name>

Echo #

echo $USER
# E.g result: 
# >> dangpham112  

Add content to file #

echo Hello $USER > readme.md
# readme file now have a content: Hello dangpham112

Systemctl #

Restart #

systemctl restart <service-name>
# E.g
systemctl restart ssh

Check status #

systemctl status <service-name>
# E.g
systemctl status ssh

SSH #

Connect #

# Access SSH server 
ssh <username>@<ip-address || domain-name>
# Then typing password and press enter

Login with username and password #

ssh <host-username>@<host-ip || host-domain>
# -> SSH will promt you to enter the password

Login via private-key file #

# Change permissions to read-only for the private key file
chmod 400 <private-key>
# E.g 
chmod 400 MyServer

# Log in via SSH (notice host-username)
ssh -i <private-key> <host-username>@<host-ip || host-domain>
# E.g 1: If you use EC2 Ubuntu, the host-username maybe ubuntu
ssh -i MyServer.pem ubuntu@54.251.177.159
# E.g 2: If you use EC2 Amazon Linux, the host-username maybe ec2-user
ssh -i MyServer.pem ec2-user@18.141.175.126
# E.g 3: If you use GCP, the host-username is your account username
ssh -i gcp-key dangpham112000@34.55.160.169
  • Where is private-key file?
    • E.g 1: While you create EC2 instance, you can create key-pair for login in aws console, then they will give you private-key to store on your SSH-client
    • E.g 2: With GCP VM instance, you need to create your own key-pair and upload the public-key’s content to SSH-KEYS (Compute Engine > Settings > Metadata > SSH-KEYS)
# Create key-pair on SSH-Client with username is your account username
ssh-keygen -t rsa -f <keypair-name> -C <username>
# E.g
ssh-keygen -t rsa -f gcp-key -C dangpham112000

Setup passwordless authentication #

# On SSH client
# Generate a new SSH key pair using the Ed25519 algorithm
ssh-keygen -t ed25519
# -> You can leave all the command prompts empty, just press enter
# -> You should notice the location of file *.pub for further actions 

# Copy the public SSH key to the SSH server 
ssh-copy-id -i <public-key-file-location> <host-username>@<host-ip || host-domain>
# E.g
ssh-copy-id -i /root/.ssh/id_ed25519.pub ubuntu@123.213.32.1
# Test the connection
ssh <host-username>@<host-ip || host-domain>
# -> SSH server will no longer ask you a password

Disable root login #

# Open the SSH daemon configuration file
vim /etc/ssh/sshd_config
# in [sshd_config] -> Find PermitRootLogin and set it to no
PermitRootLogin no
# in [sshd_config] -> Find PasswordAuthentication and set it to no
PasswordAuthentication no
# Restart the SSH Service
systemctl restart ssh

Secure copy #

From SSH-client to SSH-server #

# On SSH-client

# From SSH-Client to SSH-Server
scp <path-to-file> <host-username>@<host-ip>:<destination>
# E.g
scp ~/Documents/readme.md ubuntu@18.141.184.34:~/Document/
# Or
scp -i <private-key>.pem <path-to-file> <host-username>@<host-ip>:<destination>
# E.g
scp -i ~/Auth/MyServer.pem ~/Documents/readme.md ubuntu@18.141.184.34:~/Document/

# From SSH-Server to SSH-Client
scp <host-username>@<host-ip>:<path-to-file> <destination-on-client>
# E.g
scp ubuntu@18.141.184.34:~/Document/readyou.md ~/Documents
# Or
scp -i <private-key>.pem <host-username>@<host-ip>:<path-to-file> <destination-on-client>
# E.g
scp -i ~/Auth/MyServer.pem ubuntu@18.141.184.34:~/Document/readyou.md ~/Documents

Nano #

  • A default text editor of some OS

Open file #

nano <file-name>
# E.g
nano index.html

Save #

  1. Press Ctrl + x
  2. Press y
  3. Press enter

Setup root password #

  • If your root user does not yet have a password
# Gain root privileges
sudo su
# Set a Password
passwd root
# -> Enter and confirm the password

Nginx #

  • Capacity: 2MB

Install #

sudo apt install nginx

==> Press Tab -» Choose OK and then press enter

Open ports #

  • After installing Nginx, we may not be able to access our website because the firewall is enabled by default
  • If you use EC2, the firewall is disabled by default, but your EC2 Security Group will block access to your website
    • You must edit the inbound rules to allow traffic on HTTP (port 80) and HTTPS (port 443)

Check firewall status #

sudo ufw status
  • ufw: ubuntu firewall

Let’s firewall allow nginx #

sudo ufw allow "Nginx Full"

Locate the index file #

/var/www/html/

Locate configuration file #

/etc/nginx/sites-available/
# Activate the configuration for Nginx
sudo ln -s /etc/nginx/sites-available/<my-config>.conf /etc/nginx/sites-enabled/
# Test config syntax
sudo nginx -t
# Restart nginx
sudo systemctl restart nginx

SSL Certificate #

Let’s Encrypt SSL/TLS certificate #

  • Issued at no cost by the Let’s Encrypt Certificate Authority
  • Provides Domain Validation (DV) certificates
  • Certificates are valid for 90 days, but they can be renewed automatically with Certbot
# Install Snap
sudo apt install snapd

# Ensure stability and compatibility for all snap packages
sudo snap install core; sudo snap refresh core

# Install Certbot
sudo snap install --classic certbot

# Ensures that Certbot is accessible system-wide
sudo ln -s /snap/bin/certbot /usr/bin/certbot

# Obtain and install a certificate for a website running on Nginx
# Automatically configuring Nginx to use HTTPS
sudo certbot --nginx
# -> Certbot will prompt you to provide some information (domain, email, ads)

# Test automatic renewal
sudo certbot renew --dry-run
# -> If the dry run is successful, you'll see output similar to:
# Congratulations, all renewals succeeded
  • Certbot: A popular tool for obtaining and managing SSL/TLS certificates from the Let’s Encrypt Certificate Authority

Certificates for localhost #

Create CA certificate #

  • Generate RootCA.pem, RootCA.key, and RootCA.crt:
# Generate a Root CA Certificate
openssl req -x509 -nodes -new -sha256 -days 1024 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=US/CN=Example-Root-CA"
# -> RootCA.key & RootCA.pem

# Convert the Certificate to .crt Format
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt
# -> RootCA.crt
  • RootCA.key: Private key for the Root CA
  • RootCA.pem: Self-signed certificate for the Root CA in PEM format
  • RootCA.crt: Contains the same information as RootCA.pem, but they are often distinguished by convention

Create a configuration snippet #

  • Create a file domains.ext
# domains.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost

Generating a signed certificate for localhost #

  • Generate localhost.key, localhost.csr, and localhost.crt
# Generate a CSR (Certificate Signing Request) for localhost
openssl req -new -nodes -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/C=US/ST=YourState/L=YourCity/O=Example-Certificates/CN=localhost"
# -> localhost.key & localhost.csr

# Sign the CSR with a Root CA to generate the signed certificate
openssl x509 -req -sha256 -days 1024 -in localhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out localhost.crt
# -> localhost.crt
  • localhost.key: Private key for the certificate
  • localhost.csr: Certificate Signing Request (CSR) that can be sent to a Certificate Authority (CA) for signing
  • localhost.crt: The final signed certificate for localhost generated by your Root CA

Configure your webserver #

Nginx
server {
  listen 443 ssl default_server;
  listen [::]:443 ssl default_server;

  ssl_certificate /home/dangpham/Auth/ssl_cert/localhost.crt;
  ssl_certificate_key /home/dangpham/Auth/ssl_cert/localhost.key;

  root /var/www/html;

  index index.html index.htm index.nginx-debian.html;

  server_name localhost;

  location / {
    try_files $uri $uri/ =404;
  }
}

Nodejs
const https = require('https');
const fs = require('fs');
const path = require('path');

const certLocation = '/home/dangpham/Auth/ssl_cert';

const options = {
    key: fs.readFileSync(path.resolve(certLocation, 'localhost.key')), 
    cert: fs.readFileSync(path.resolve(certLocation, 'localhost.crt')), 
};

const server = https.createServer(options,(req, res) => {
    if (req.url === '/hello' && req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('world');
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

server.listen(443, () => {
    console.log('Server is listening on port 443');
});

Add new local CA to the trusted Root Certificate Authorities #

Chrome
  1. Browse chrome://settings/certificates
  2. Choose Authorities then Import
  3. Import RootCA.pem we created above
  4. Check all options

Firefox
  • Make Firefox trusted Root CAs:
    1. Browse about:config
    2. Type security.enterprise_roots.enabled
    3. Enable it to true
  • Import CA certificate:
    1. Browse about:preferences#privacy
    2. Find Certificats section
    3. Choose View Certificates and then Import
    4. Import RootCA.pem we created above
    5. Confirm

References #