Ubuntu do nothing when laptop lid is closed
- Open the /etc/systemd/logind.conf : sudo -H gedit /etc/systemd/logind.conf
- Add a line:
HandleLidSwitch=ignore
- Restart the systemd:
sudo service systemd-logind restart
Disable auto update
# Stop checking
sudo systemctl stop apt-daily.timer
sudo systemctl disable apt-daily.timer
# sudo systemctl disable apt-daily.service # may not has
# Stop upgrade
sudo systemctl stop apt-daily-upgrade.timer
sudo systemctl disable apt-daily-upgrade.timer
# sudo systemctl disable apt-daily-upgrade.service
User Management
Add User: sudo adduser <username>
Delete User: sudo deluser <username>
Change User password: sudo passwd <username>
To change username (Need to logged in another account)
sudo usermod -l newUsername oldUsername
Then change home-folder
sudo usermod -d /home/newHomeDir -m newUsername
SSH Server
Clean apt: sudo apt clean
Update apt: sudo apt update
Remove openssh-client: sudo apt remove openssh-client
Install openssh-server: sudo apt install openssh-server
Configure the default behavior of the OpenSSH server, editing the file /etc/ssh/sshd_config
Configuration change:
# To set OpenSSH to listen on TCP port 2222 instead of the
# default TCP port 22
Port 2222
# To disallow password login
PasswordAuthentication no
# To allow public key-based login credentials using RSA keys
PubkeyAuthentication yes
# Banner display, content in file /etc/issue.net (before login successfully):
Banner /etc/issue.net
# Time for entering
LoginGraceTime 120
# Don't allow login as root
passwordPermitRootLogin no
To change content that will be displayed after login successfully, modify files that will be executed
sudo vim /etc/update-motd.d/10-help-text
To use public/private key to access SSH, generate a pair of keys, then copy/paste the public key value to file /home/username/.ssh/authorized_keys
sudo vim /home/username/.ssh/authorized_keys
sudo systemctl restart sshd
– Start the sshd.
UFW
Configuring the Uncomplicated FireWall.
sudo systemctl restart ufw
– Start the ufw.
sudo ufw status
– See rules in current ufw.
sudo ufw default deny incoming
– Define the default policies, deny all incoming requests.
sudo ufw default allow outgoing
– Define the default policies, allow all outgoing traffic.
sudo ufw allow 22/tcp
– Allow incoming traffic on port 22 (SSH), and maybe more.
sudo ufw delete allow 22/tcp
– Delete any rules that add (name need to be matched).
sudo ufw enable
– Finally, make the ufw to be active
Fail2ban
To increase security, install fail2ban to ban IP of someone when they fail to login to the server couple times via ssh.
sudo apt install fail2ban
– Install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
– Create a mirror configure file from the default conf file
sudo vim /etc/fail2ban/jail.local
– Modify the local conf file
...
ignoreip = 127.0.0.1/8 ::1 # don't ban local ip
...
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 5
bantime = -1 # ban ip forever
sudo systemctl restart fail2ban
– Restart fail2ban
sudo iptables -S
– See what IP addresses that have been rejected (which will be banned)
sudo fail2ban-client set sshd unbanip <172.123.123.123>
– To unban an IP
Git
sudo apt install git
Web Server (Apache)
Install Apache: sudo apt install apache2
Control Apache Service: sudo service apache2 [start, restart, stop, status]
Modify Apache main config file: sudo vim /etc/apache2/apache2.conf
<Directory /www/> # this folder used for root dir
Options FollowSymLinks # Forbid browsing dir
AllowOverride All # Allow path overwrite
Require all granted # grant all file access
</Directory>
Modify default root directory redirection: sudo vim /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80> # server listen on port 80
# ServerName xxx # comment out for default redirection
DocumentRoot /www # default directory
# add error page (in root folder) handling
ErrorDocument 400 /error/index.php?code=400
ErrorDocument 401 /error/index.php?code=401
ErrorDocument 403 /error/index.php?code=403
ErrorDocument 404 /error/index.php?code=404
ErrorDocument 500 /error/index.php?code=500
ErrorDocument 502 /error/index.php?code=502
ErrorDocument 503 /error/index.php?code=503
ErrorDocument 504 /error/index.php?code=504
</VirtualHost>
Modify file extension that Apache will serve.
sudo vim /etc/apache2/mods-available/dir.conf
Apache2 Enable Module. Modules that is available locate on /etc/apache2/mods-available
To enable module.
sudo a2enmod <module-name>
Enable “rewrite” module for WordPress permalink to work:
sudo a2enmod rewrite
Restart Apache2 service.
Subdomain
For adding a subdomain (suppose that the subdomain “sub.domain.com” already points to the domain “domain.com”), we can use <VirturalHost> directive to handle it.
Open the redirection config file.
sudo vim /etc/apache2/sites-available/000-default.conf
Add directives:
<VirtualHost *:80> # server listen on port 80
ServerName sub.domain.com # the subdomain name
DocumentRoot /www/subdomain # sub-directory of site
</VirtualHost>
To make the subdomain points to another web server that is running on other ports:
Enable proxy module.
sudo a2enmod proxy_http
Then add a VirtualHost directive to the directory redirection: sudo vim /etc/apache2/sites-available/000-default.conf
<VirtualHost *:80>
ServerName sub.domain.com
# setup the proxy
<Proxy *>
Order allow,deny
Allow from all
</Proxy>
# pass request to port :8080
ProxyPass / http://domain.com:8080/
ProxyPassReverse / http://domain.com:8080/
</VirtualHost>
Change Server’s Name
To change the Server header value on the response.
Installing Apache mod_security module.
sudo apt install libapache2-mod-security2
Enable Apache mod_security module.
sudo a2enmod security2
Modify Apache main config file: sudo vim /etc/apache2/apache2.conf
# Modify server's name
ServerTokens Full
SecServerSignature "KaraNoKara"
Restart Apache2 service.
Enable HTTPS
Get https for publick domain using Let’s Encrypt (is a Certificate Authority (CA)). This procedure need to use Shell to use certbot to automate certificate issuance and installation.
1. Install snap.
2. refresh snap
sudo snap install core; sudo snap refresh core
2.1. (optional) Remove certbot if installed using apt
sudo apt-get remove certbot
3. Install certbot using snap
sudo snap install --classic certbot
4. Make certbot to be common command
sudo ln -s /snap/bin/certbot /usr/bin/certbot
5. (recommanded) Run certbot to get certificate and config Apache automatically. This will check all subdomains as <VirtualHost> setting in the Apache config file to make sure to get all subdomains to be covered by https. The first domain show in the result will be the name of “Issued to” field in the certificate.
sudo certbot --apache
5.1. Run certbot to get certificate (config Apache manually)
sudo certbot certonly --apache
6. (optional) Test automatic renewal
sudo certbot renew --dry-run
7. Allow port 443 on firewall and router
8. Test https://site.com/
9. (optional) redirection all subdomain, so can make sure all responses will become https
# redirection all subdomain
<VirtualHost *:80>
ServerAlias *.karanokara.com
RedirectPermanent / http://karanokara.com/
</VirtualHost>
sudo systemctl restart apache2
MySQL Server
sudo apt-get install mysql-server
– Install mysql
When the installation is complete, run command blow to configure security (password…)
sudo mysql_secure_installation
– Configuring mysql
In cd /etc/mysql/mysql.conf.d/mysqld.cnf
, assigned PC IP address
bind-address = 192.168.0.15
sudo mysql
– Open up the mysql as root
SELECT user,authentication_string,plugin,host FROM mysql.user;
– See which host users can access
Optional, configure the root account to authenticate login with a password:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Create more users, have that user created in both the localhost and ‘%’ (this user from any remote point can access to this mysql):
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';
then, grant all privilege to the user:
GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
FLUSH PRIVILEGES;
– Reload the grant tables and put your new changes into effect
exit
– Get out of mysql
sudo service mysql restart
– Restart the mysql
PHP
sudo apt install php
sudo apt install php-mysql
– Enable php with MySQL (enable mysqli module)
sudo apt install php-xml
– Enable php using XML module for svg file
sudo vim /etc/apache2/mods-available/dir.conf
– Add .php
index page extension, in <IfModule mod_dir.c>
, move index.php
to right after the DirectoryIndex
sudo service apache2 restart
– Restart Apache Web server
Node.js
sudo apt install nodejs
– Install node js
sudo apt install npm
– Install package manager npm
sudo ufw allow 3000/tcp
– Allow firewall of port 3000 for node server
Next, go to 192.168.0.1 to allow port 3000 on router firewall.
To run a node.js app as a system service:
Create the a service file:
sudo vim /etc/systemd/system/nodeserver.service
Inside file:
[Unit]
Description=A Node.js Server
#Requires=After=mysql.service # Requires the mysql service to run first
[Service]
# a command that will be executed at startup
# using node xx.js
ExecStart=/usr/bin/node /www/note/bin/www.js
# Required on some systems
# WorkingDirectory=/www/note/bin
Restart=always
# Restart service after 30 seconds if node service crashes
RestartSec=30
# Output to syslog
StandardOutput=syslog # output is shown on service status
StandardError=syslog # run-time error is shown there now
SyslogIdentifier=App-Name
# compile-time error shown on
# ???
#User=<alternate user>
#Group=<alternate group>
Environment=NODE_ENV=production PORT=3000
[Install]
WantedBy=multi-user.target
Enable the service:
systemctl enable nodeserver.service
Start the service:
systemctl start nodeserver.service
Verify it is running:
systemctl status nodeserver.service
sudo
Java
java -version
– Java Runtime Environment (JRE). This will allow to run almost all Java softwares.
javac -version
– Java Development Kit (JDK). This allow to compile and run some specific Java-based software.
sudo apt install {default-jre | openjdk-8-jre}
– Install current version or other version of Java Runtime Environment (JRE).
sudo apt install {default-jdk | openjdk-8-jdk}
– Install current version or other version of Java Development Kit (JDK).
Setting the JAVA_HOME
Environment Variable
sudo update-alternatives --config java
– Check or change which version of Jave JRE is using now, then copy the path.
sudo vim /etc/environment
– Open file and add the path (binary folder) to the end of the file.
# At a binary folder ending as 'xx/xx/bin'
JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/bin"
echo $JAVA_HOME
– Verify that environment variable has changed (may need to log out and come back for it to take effect)
Jenkins
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
– Add key of Debian package repository of Jenkins to the system.
sudo vim /etc/apt/sources.list
– Open sources list and add the follow entry to the end of the file
deb https://pkg.jenkins.io/debian-stable binary/
sudo apt-get update
– Refresh the package source
sudo apt-get install jenkins
– Install jenkins
java -jar /usr/share/jenkins/jenkins.war --httpPort=8080
– Run the jenkin.war as a executable to be a service at port 8080
sudo ufw allow 8080/tcp
– Allow port 8080 to be accessed
Go to http://192.168.0.x:8080
to continue configuring the Jenkins
System Log
See log of a specific service:
journalctl -u service-name.service
– see all log messages
journalctl -u service-name.service -b
– see only log messages for the current boot
See how much log files taking the space of disk:
journalctl --disk-usage
Clear journal log:
sudo journalctl --vacuum-time=2d
– Delete all log 2 days ago
sudo journalctl --vacuum-time=2h
– Delete all log 2 hours ago
sudo journalctl --vacuum-size=500M
– Retain only the most new 500 MB
VPN
Step 1 — Installing OpenVPN and EasyRSA
sudo apt install openvpn
– Installing OpenVPN
mkdir ~/ca-machine
– Folder for certificate authority (CA)
mkdir ~/vpn-machine
– Folder for VPN server
wget -P ~/ https://github.com/OpenVPN/easy-rsa/releases/download/v3.0.4/EasyRSA-3.0.4.tgz
– Download the latest version of EasyRSA
tar xvf EasyRSA-3.0.4.tgz
– Unzip to both your ca-machine and vpn-machine folder
mv EasyRSA* easy-rsa
– Change folder name
Step 2 — Configuring the EasyRSA Variables and Building the CA
cd ~/ca-machine/easy*/code> - Go to CA folder
cp vars.example vars
– Make a copy of default variable file
vim vars
– Modify settings below:
set_var EASYRSA_REQ_COUNTRY "US"
set_var EASYRSA_REQ_PROVINCE "Oregon"
set_var EASYRSA_REQ_CITY "Portland"
set_var EASYRSA_REQ_ORG "karanokara"
set_var EASYRSA_REQ_EMAIL "karawakara@gmail.com"
set_var EASYRSA_REQ_OU "Communitity"
./easyrsa init-pki
– Initiate the public key infrastructure on the CA server
./easyrsa build-ca nopass
– Build the CA and create two important files — ca.crt
and ca.key
— which make up the public and private sides of an SSL certificate.
Step 3 — Creating the Server Certificate, Key, and Encryption Files
In Server folder:
./easyrsa init-pki
./easyrsa gen-req server nopass
sudo cp ~/vpn-machine/pki/private/server.key /etc/openvpn/
– Copy the server key to the /etc/openvpn/
directory
Next, move ‘server.req’ from server to ca-machine/easy-rsa
folder
In CA folder:
sudo ./easyrsa import-req from-server.req server - Import .req
– Import the server.req
file
./easyrsa sign-req server server - Sign
– Sign the request
'yes' .. 'Enter'
Next, Copy ca.crt
and server.crt
to /etc/openvpn
In Server folder:
./easyrsa gen-dh
– Create a strong Diffie-Hellman key to use during key exchange
openvpn --genkey --secret ta.key
– Generate an HMAC signature to strengthen the server’s TLS integrity verification capabilities
Copy the two new files to your /etc/openvpn/
directory:
sudo cp ~/vpn*/easy*/ta.key /etc/openvpn/
sudo cp ~/vpn*/easy*/pki/dh.pem /etc/openvpn/
Step 4 — Generating a Client Certificate and Key Pair
mkdir -p ~/vpn-client-configs/keys
– Creating a directory structure within home directory to store the client certificate and key files
./easyrsa gen-req kara nopass
cp pki/private/kara.key ~/vpn-client-configs/keys/
– copy to the /client-configs/keys/ directory
Next, copy the kara.req file to the CA-machine folder.
In CA folder:
sudo ./easyrsa import-req kara.req kara
– Import
sudo ./easyrsa sign-req client kara
– Sign
sudo cp pki/issued/kara.crt ~/vpn-cli*/keys
– copy files to client config folder
sudo cp /etc/openvpn/ta.key ~/vpn-cli*/keys/ta.key
sudo cp /etc/openvpn/ca.crt ~/vpn-cli*/keys/ca.crt
Step 5 — Configuring the OpenVPN Service
sudo cp /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz /etc/openvpn/
sudo gzip -d /etc/openvpn/server.conf.gz
sudo vim server.conf
tls-auth ta.key 0 # This file is secret
key-direction 0
cipher AES-256-CBC
auth SHA256
dh dh.pem
user nobody
group nogroup
Step 6 – Adjusting the Server Networking Configuration (Ip forwarding)
sudo vim /etc/sysctl.conf
net.ipv4.ip_forward=1
ip route | grep default
– Find public network interface
Output:
default via 203.0.113.1 dev "wlp11s0" proto static
sudo vim /etc/ufw/before.rules
– Add configurations
//In the begin:
# START OPENVPN RULES
# NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]
# Allow traffic from OpenVPN client to wlp11s0 (change to the interface you discovered!)
-A POSTROUTING -s 10.8.0.0/8 -o {wlp11s0} -j MASQUERADE
COMMIT
# END OPENVPN RULES
sudo vim /etc/default/ufw
– tell UFW to allow forwarded packets by default
DEFAULT_FORWARD_POLICY="ACCEPT"
sudo ufw allow 1194/udp
– adjust the firewall itself to allow traffic to OpenVPN
sudo ufw allow OpenSSH
sudo ufw disable
sudo ufw enable
Step 7 — Starting and Enabling the OpenVPN Service
sudo systemctl start openvpn@server
– Check out services
sudo systemctl status openvpn@server
sudo systemctl enable openvpn@server
Step 8 — Creating the Client Configuration Infrastructure
mkdir -p ~/client-configs/files
– Make folder to store client .ovpn
file
cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf ~/vpn-client-configs/base.conf
– Copy an example client configuration file into the client-configs directory
vim ~/vpn-client-configs/base.conf
– Points the client to your OpenVPN server address
remote kara.myftp.org 1194
proto udp
user nobody
group nogroup
ca ca.crt
cert client.crt
key client.key
tls-auth ta.key 1
cipher AES-256-CBC
auth SHA256
#key direction
key-direction 1
# script-security 2
# up /etc/openvpn/update-resolv-conf
# down /etc/openvpn/update-resolv-conf
vim ~/vpn-client-configs/make_config.sh
– create a simple script that will compile your base configuration with the relevant certificate, key, and encryption files and then place the generated configuration in the ~/client-configs/files
directory.
#!/bin/bash
# First argument: Client identifier
KEY_DIR=~/vpn-client-configs/keys
OUTPUT_DIR=~/vpn-client-configs/files
BASE_CONFIG=~/vpn-client-configs/base.conf
cat ${BASE_CONFIG} \
<(echo -e '<ca>') \
${KEY_DIR}/ca.crt \
<(echo -e '</ca>\n<cert>') \
${KEY_DIR}/${1}.crt \
<(echo -e '</cert>\n<key>') \
${KEY_DIR}/${1}.key \
<(echo -e '</key>\n<tls-auth>') \
${KEY_DIR}/ta.key \
<(echo -e '</tls-auth>') \
> ${OUTPUT_DIR}/${1}.ovpn
chmod 700 ~/vpn-client-configs/make_config.sh
– Mark this file as executable
Step 9 — Generating Client Configurations
cd ~/vpn-client-configs
sudo ./make_config.sh kara
– Generate a config file named kara.ovpn in ~/client-configs/files
sudo vim /etc/openvpn/server.conf
– Redirect all traffic from the vpn including web browsing, any.
push "redirect-gateway def1"
sudo systemctl restart openvpn@server
– Restart service
Torrent Client
Using Transmission
sudo apt install transmission-daemon
– Install transmission torrent client
sudo service transmission-daemon stop
– Need to stop the transmission daemon before editing config file
sudo vim /var/lib/transmission-daemon/info/settings.json
– Editting the config file
"download-queue-enable": false,
"download-dir": "/folder/download",
"incomplete-dir": "/folder/download",
"incomplete-dir-enabled": true,
"rpc-whitelist": "127.0.0.1, 192.168.0.*",
"rpc-authentication-required": false, // disable login requirement
"rpc-username": "username", // or using login
"rpc-password": "pwd", // pwd changed automatically
"rename-partial-files": false,
"umask": 2,
"speed-limit-up": 1,
"speed-limit-up-enabled": true,
"seed-queue-enable": true,
"seed-queue-size": 1,
"start-added-torrents": false,
"upload-limit": 1,
"upload-limit-enabled": 1,
sudo ufw allow 9091/tcp
– Allow Web Interface port
mkdir ~/torrent-files
– Create download folder
sudo chmod 777 ~/torrent-files
– Make it writable
sudo service transmission-daemon start
– Start the transmission daemon
Go to http://server-ip:9091
in browser
Mail Server (Postfix)
Postfix is a default MTA (Mail Transfer Agent) using SMTP (Simple Mail Transfer Protocol) in Ubuntu. It can send and receive email.
These steps will configure Postfix as a send-only SMTP server for local installed applications.
**Mail server communication will use port 25, but most of the ISP blocked port 25, so here need to use another mail server to relay, and so the final sending server will be the relaying server who send out the mails.
POP vs. IMAP: POP (Post Office Protocol) and IMAP (Internet Message Access Protocol) are two different ways to get email in your email program. We recommend using IMAP for your Comcast email. POP can cause problems when checking your mail from more than one phone or computer because POP removes the mail from our server and delivers it to your device. IMAP makes it easier to sync your email on multiple devices because your folders and mail remain on our server until you move or delete them with your device. With IMAP, the email changes you make on one device, like your smartphone, are reflected on your other devices, like your laptop.
Install Postfix. After installation finishes, Package configuration will be opened.
# mailutils includes postfix
# sudo apt install postfix
sudo apt install mailutils
(Cont.) Configuring Postfix
sudo dpkg-reconfigure postfix
Steps:
-> Internet Site
-> your.domain.com of the server
-> username to save mail for
-> your.domain.com, localhost.localdomain, localhost
-> No
-> 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 192.168.0.0/8
-> 0
-> +
-> all
Configuration file created in /etc/postfix/main.cf
To change configuration:
sudo vim /etc/postfix/main.cf
#/etc/postfix/main.cf
# listen only on the loopback interface to send and receive emails only from the itself
inet_interfaces = loopback-only
# specify the list of domains that email delivered
mydestination = localhost.$mydomain, localhost, $myhostname
# relay email to other hosts (in ISP) that support port 25
# Enables SASL authentication for postfix
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = static:your@gmail.com:password
# Disallow methods that allow anonymous authentication
smtp_sasl_security_options = noanonymous
# Enable STARTTLS encryption for SMTP
smtp_tls_security_level = encrypt
# configure Postfix use ISP mail server for SMTP relay
relayhost = [smtp.gmail.com]:587
Control mail queue:
postqueue -p
– View or see queued mail
postqueue -f
– Flush queued mail
postsuper -d {ID}
– Purge queued mail
postsuper -d ALL
– To purge all email from the queue
To restart service:
sudo systemctl restart postfix
sudo systemctl status postfix
To see log:
less /var/log/mail.log
Test sending email
echo "This is the body of the email" | mail -s "This is the subject line" other@gmail.com
sudo service {any_service} restart
– To refresh any services after any changes to them