Tuesday, December 22, 2020

[Solved] Proxmox 6.3 error on RH2288 V3 Huawei Servers: No working lease in persistent database


Proxmox 6.x does not enter installation on RH2288 V3 servers for some reason and it drops to shell with this error:

No working lease in persistent database

Digger412 has suggested a workaround here .


Enter E key on proxmox splash page then add the following arguments :

modprobe.blacklist=nouveau amd_iommu=on video=efifb:off


then press Ctrl+x to boot. It worked pretty well for me.

p.s.

You can get internet access in proxmox debug shell by assigning your IP / Gateway to the interface on the fly:

ip addr show

ip addr add YOUR.IP.ADDRESS/PREFIX dev enp2s0f0

ip route add default via YOUR.GATEWAY.ADDRESS dev enp2s0f0


How Install kernel headers on Sangoma OS

I installed FreePBX Sangoma OS on VirtualBox and tried to install Guest Additions there:

VirtualBox -> Devices -> Insert Guest Additions CD image...

the on the VM:

yum install dkms gcc kernel-devel kernel-headers -y

mkdir /media/cdrom

mount /dev/cdrom /media/cdrom

cd /media/cdrom

./VBoxLinuxAdditions.run

it returns the following error while kernel headers are already installed: 

VirtualBox Guest Additions: Kernel headers not found for target kernel 3.10.0-1127.19.1.el7.x86_64. 

This is while we have already installed kernel-devel and kernel-headers packages. This error is because the build folder in /lib/modules/$(uname -r) is missing in the default FreePBX Sangoma installation for some reason.

To fix this problem, run the following command:

ln -s /usr/src/kernels/$(uname -r) /lib/modules/$(uname -r)/build

then run 

./VBoxLinuxAdditions.run

again to build Linux Guest Additions.


Tuesday, December 15, 2020

Install the last version of tesseract on debian 11

 Get the latest version number from here and update v variable in the following gist:

v=4.1.1

apt-get install g++ autoconf automake libtool pkg-config libpng-dev libjpeg62-turbo-dev libtiff5-dev zlib1g-dev libleptonica-dev -y

cd /usr/src

wget https://github.com/tesseract-ocr/tesseract/archive/$v.tar.gz

tar -zxvf $v.tar.gz

cd tesseract-$v

./autogen.sh

./configure --prefix=/usr/local

make

make install

wget https://github.com/tesseract-ocr/tessdata/raw/master/eng.traineddata -O /usr/local/share/tessdata/eng.traineddata


Sunday, December 13, 2020

RaspberryPI 4B+ and GSM Dongles

I managed to run 4 GSM donlges on RaspberryPi 4B+ in a stable production eventually although it was not an easy process. I had four UMG1691 GSM dongles that I wanted to use with raspberry-asterisk.

-------

Update 4: 19/June/2021:

I noticed intermittent disconnects in the dongles, it was apparently due to weak 3g signal. I suppose the operator stopped one of the antennas it had in our region which caused the weak signal problem. (RSSI <15)

I had to switch the dongles to 2G (AT^SYSCFG=13,1,3FFFFFFF,0,2) to get a better signal however dongles keep resetting frequently and it was very unstable. I had DUB H7 D-Link hub which is recommended here however I was not able to get dongles working in 2G mode with this hub.

I ordered a TP-Link UH700 USB 3.0 hub and the dongles are now working in 2G mode and they are very stable (RSSI > 23). This USB hub uses VL812 chip which I think is the reason why its compatible with 2G dongles (needs to be verified). There are some other hubs with this chipset which can be tested to confirm this.



I think a better hub choice would be TP-Link UH720 which has two 2.4A ports which can be used the also power the raspberry pi. DUB-1370 may also be compatible, it needs testing. I had tested this "4 Port USB3.0 Transparent HUB" Orico hub  and it was not compatible with 2G dongles. 

I also found that the Mode / Submode values are not important, my dongles work fine in 2G with mode/submode 3/3 or 0/0, and in 3G with mode/submode 5/4 or 0/0 . I had a dongle that was not functioning properly even when it was shown as Free in asterisk, it was a E171 dongle with firmware v21.x . 

Update 3: 26/April/2021:

The four sim cards in the dongles were from 3 different network operators. I noticed that the simcards  from one of the network operators do not work stably and they reset frequently. I was getting 

ID           Group State      RSSI Mode Submode

dongle2      0     GSM not re 20   5    4 

I was getting Mode 5 Submode 4 on the dongle having the sim card. This was resolved by transferring the phone number to another network operator. Now asterisk shows a Mode 0 Submode 0 like the rest of the dongles and it is all stable.

ID           Group State      RSSI Mode Submode

dongle2      0     Free       25   0    0 

Update 2: 2/March/2021:

Although my setup from Update 1 was stable, the gsm dongles used to reset / disconnect every 10-60mins randomly, I had the following errors in dmesg: 

[14176.370665] usb 1-1.3.4-port4: Cannot enable. Maybe the USB cable is bad?

[14176.370984] hub 1-1.3:1.0: hub_ext_port_status failed (err = -110)

[14177.410797] usb 1-1.3.4-port4: cannot disable (err = -110)

[14054.689390] usb 1-1.3.4-port1: cannot reset (err = -110)

and even sometimes lsusb didnt show dongles after the above errors and a restart was required. 

I decided to try Ubuntu 20.04LTS for Raspberry PI + Asterisk 18 and it worked decently without even a single dongle disconnect / restart in 24 hours. I have published the instructions to install freepbx/asterisk 18/ ubuntu 20.04 LTS on Raspberry PI in my post here.


UPDATE 1: 23/Dec/2020:

The UMG1691 modems were not stable at all for production due to RF problems in 2G. 

I eventually dropped all these modems and went for four new 3G modems: E1550, E153, E173 and E171

They work pretty well with D-Link DUB-H7 port when set to 3G only mode :

^SYSCFG:14,2,3FFFFFFF,0,2

It is finally Stable :



-------

First, RaspberryPI 4B+ allows a Maximum total USB peripheral current draw of 1.2A. This is not enough if you are going to use four GSM dongles in which each dongle uses 0.5A, you would need a total USB current draw of 2A.

One might think to use a powered USB hub. I tried this Orico USB3 hub and this D-Link USB2 Hub however they did not work. There are some reports that GSM dongles might have problems with USB hubs and using 3G mode might fix it. In my experience, the GSM dongles got reset frequently and the OS reported errors like:

usb 1-1-port2: cannot reset (err = -110)

Second, the 4 USB ports on RaspberryPi are designed so close to each other that it makes it impossible to connect 4 dongles directly to the raspberry. You would need a USB cable extension. Casual USB2.0 extension cables won't work and it leads to 

usb 1-1-port2: Cannot enable. Maybe the USB cable is bad?

errors in dmesg. You would need to use USB3.0 extension cables even for usb2 ports to connect your dongles.

Third, after connecting all GSM dongles to the raspberry, you may get

usb usb2-port1: over-current change #1

error in dmesg. I tried three things here :

- Add max_usb_current=1 to /boot/config.txt

- Use minicom or atinout to directly send AT commands to your GSM dongles and set SYSCFG on all your dongles to 2G only which uses less power than 3G

- Use a 5V 3A USB adapter on your raspberry and check that your raspberry is not undervoltaged :

/opt/vc/bin/vcgencmd get_throttled

and also check dmesg to ensure that the usb ports did not get overcurrent:

dmesg | grep -i curr

so my setup is now stable with the above precautions and everything seems to work fine, it took me 3 weeks for to figure out all the above

- Disable wifi and bluetooth modules if you don't need them, add dtoverlay=disable-wifi and dtoverlay=disable-bt to /boot/config.txt 

and finally reboot raspberry for the changes to apply.

- I had this problem that dongles stopped receiving SMS after some time. Whenever I inserted the sim card on a mobile phone, text messages were received fine. This problem is described here and the solution is to add a cronjob in your raspberry pi to delete SMS storage of the sim card / dongle periodically. 

Monday, November 23, 2020

[Howto] Install and configure Munin on Centos 8

Install munin first:

yum install epel-release -y

yum install munin munin-cgi munin-node munin-apache munin-common munin-plugins-ruby -y


Check the services that munin has installed in systemd:

systemctl list-unit-files | grep -i munin

Enable all available munin plugins:

munin-node-configure --shell --families=contrib,auto | sh -x

Start and enable munin-node which collects data on the system, we restrict this service to localhost:

sed -i /etc/munin/munin-node.conf -e "s,^host \*,#host \*,g"

sed -i /etc/munin/munin-node.conf -e "s,^#host 127.0.0.1,host 127.0.0.1,g"

systemctl enable munin-node --now

Enable munin in systemd timer:

sed -i /etc/munin/munin.conf -e "s,#graph_strategy cron,graph_strategy cron,g"

sed -i /etc/munin/munin.conf -e "s,#html_strategy cron,html_strategy cron,g"

sed -i /etc/munin/munin.conf -e "s,#htmldir,htmldir,g"

systemctl enable munin.timer --now


check if munin timer is running properly

systemctl list-timers --all


and finally add a virtualhost to apache or nginx to show the graphs. Check the examples here (Periodically generate graphs and HTML pages).

For apache: 

<VirtualHost _IP_:80>

    ServerName _IP_

    DocumentRoot /var/www/html

    Alias /munin/static/ /etc/munin/static/

    <Directory /etc/munin/static>

        Require all granted

    </Directory>

    # Disabling caching

    RewriteEngine On

    <FilesMatch "\.(html|htm|jpg|png)$">

      FileETag None

      <IfModule mod_headers.c>

        Header unset ETag

        Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"

        Header set Pragma "no-cache"

        Header set Expires "Wed, 12 Jan 1980 05:00:00 GMT"

      </IfModule>

    </FilesMatch>

    # Password protect the folder

    <Directory /var/www/html>

AuthType Basic

AuthName "restricted area"

AuthUserFile /var/www/.htpasswd

require valid-user

    </Directory>

    ScriptAlias /munin-cgi/munin-cgi-graph /var/www/html/munin/cgi/munin-cgi-graph

    # ScriptAlias /munin /var/www/html/munin/cgi/munin-cgi-html

    <Directory /var/www/html/munin/cgi>

        Require valid-user

        AuthName "restricted area"

            AuthUserFile /var/www/.htpasswd

        <IfModule mod_fcgid.c>

            SetHandler fcgid-script

        </IfModule>

        <IfModule !mod_fcgid.c>

            SetHandler cgi-script

        </IfModule>

    </Directory>

    CustomLog /var/log/httpd/munin-access.log combined

    ErrorLog  /var/log/httpd/munin-error.log

</VirtualHost>

Create your .htpasswd file :

htpasswd -c /var/www/.htpasswd monit

and reload apache.

for nginx add the following to your monit vhost: 

location = / {

    rewrite ^/$ munin/ redirect; break;

}

location /munin/static/ {

    alias /etc/munin/static/;

    expires modified +1w;

}


location /munin/ {

    auth_basic            "Restricted";

    auth_basic_user_file  /var/www/.htpasswd;

    alias /var/www/html/munin/;

    expires modified +310s;

}

location ^~ /munin-cgi/munin-cgi-graph/ {

    auth_basic            "Restricted";

    auth_basic_user_file  /var/www/.htpasswd;

    access_log off;

    fastcgi_split_path_info ^(/munin-cgi/munin-cgi-graph)(.*);

    fastcgi_param PATH_INFO $fastcgi_path_info;

    fastcgi_pass unix:/var/run/munin/munin-cgi-graph.sock;

    include fastcgi_params;

}

then run

service nginx reload

systemctl enable munin-cgi-graph.socket --now

Tuesday, September 22, 2020

[Howto] Install BigBlueButton on Centos 8 using docker

BigBlueButton only supports Ubuntu distros however it is possible to install it on almost any linux distro using docker. Here is the instruction I use to install it on Centos 8 : 

# Installing docker
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
dnf module enable container-tools
dnf install container-selinux
dnf module disable container-tools
yum install docker-ce docker-ce-cli containerd.io
curl -L "https://github.com/docker/compose/releases/download/1.27.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
mkdir -p ~/.docker
##### ONLY IF YOU NEED TO USE A PROXY FOR DOCKER CONTAINERS
echo '{
{
 "proxies":
 {
   "default":
   {
     "httpProxy": "http://X:Y",
     "httpsProxy": "http://X:Y",
     "noProxy": "216.93.246.18, YOURDOMAIN, YOURIP, localhost, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.1, 0.0.0.0, postgres, etherpad, html5, webrtc-sfu, core, host.docker.internal"
   }
 }
}
' \
> ~/.docker/config.json
###
systemctl daemon-reload
systemctl enable docker --now


# Install bbb-docker

cd /usr/src
git clone --recurse-submodules https://github.com/alangecker/bigbluebutton-docker.git bbb-docker
cd bbb-docker
./scripts/setup
./scripts/compose up -d

and finally proxy requests to your web server . Note that you need to forward requests to 127.0.0.1:8080 and not the IP address of greenlight vm.

Thursday, July 9, 2020

[Howto] install Icecast on Centos 8

Icecast package is not available on Centos 8 / EPEL 8 package repositories. Here is the gist I use to install this package on Centos 8:


yum groupinstall "Development Tools" -y
yum install -y curl-devel libtheora-devel libvorbis-devel libxslt-devel speex-devel  libshout libxslt-devel -y
cd /usr/src
# from https://icecast.org/download/
wget http://downloads.xiph.org/releases/icecast/icecast-2.4.4.tar.gz
tar -zxvf icecast-2.4.4.tar.gz
cd icecast-2.4.4
./configure --sysconfdir=/etc --localstatedir=/var
make
make install

useradd -s /sbin/nologin  icecast
mkdir -p /var/run/icecast
mkdir -p /var/log/icecast
chown -R icecast:icecast /var/run/icecast
chown -R icecast:icecast /var/log/icecast

sed -i /etc/icecast.xml -e "s,/usr/local/var/log/icecast,/var/log/icecast,g"

# Configure /etc/icecast.xml, update <authentication>, <changeowner>, <hostname>, <location> and <admin> sections

echo '[Unit]
Description=Icecast
After=network.target

[Service]
Type=simple
Restart=always
RestartSec=5
User=icecast
ExecStart=/usr/local/bin/icecast -c /etc/icecast.xml
ExecReload=/usr/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target' > /etc/systemd/system/icecast.service

systemctl daemon-reload
systemctl enable icecast
service icecast restart
service icecast status

Wednesday, July 8, 2020

How rebuild httpd to set suexec AP_DOC_ROOT to /home

The default suexec AP_DOC_ROOT path that is provided by rpm repositories are set to /var/www , while virtualmin uses /home/ as its docroot folder. So one needs to use the custom build httpd package provided by virtualmin which is kind of outdated, OR compile apache by themselves and correct the docroot path.

I use httpd24u package provided by IUS-repo which is up-to-date and the followings are the gist I use to recompile this package and set its suexec docroot to /home:


# Install dependencies
yum install mock brotli-devel systemd-devel xmlto rpm-build epel-rpm-macros yum-utils -y
yum group install "Development Tools" -y
useradd -s /sbin/nologin mockbuild
useradd rpm
su rpm
cd ~


# Get source
yumdownloader --source httpd24u
yum-builddep httpd24u

# Centos 8 source
# dnf download --source httpd
#wget http://vault.centos.org/8.2.2004/AppStream/Source/SPackages/httpd-2.4.37-21.module_el8.2.0+382+15b0afa8.src.rpm

rpm2cpio httpd*.src.rpm | cpio -civ '*.spec'

rpm -i httpd*.src.rpm

sed -i httpd*.spec -e "s,--with-suexec-docroot=%{docroot},--with-suexec-docroot=/home,"

rpmbuild -bb httpd*.spec

# extract suexec from our rebuilt rpm
mkdir ./usr/sbin/
rpm2cpio ./rpmbuild/RPMS/x86_64/httpd24u*.rpm | cpio -civ './usr/sbin/suexec'

# run as root:
cp ./usr/sbin/suexec /usr/sbin/suexec
chown root.apache /usr/sbin/suexec
chmod u+s /usr/sbin/suexec
ls -l /usr/sbin/suexec
chattr +ia /usr/sbin/suexec

Monday, June 22, 2020

[Resolved] suexec + fcgid : How to fix "mod_fcgid: error reading data from FastCGI server" error

If you are using php-fcgid with suexec and you get the following error :


End of script output before headers:

mod_fcgid: error reading data from FastCGI server

exit(communication error), terminated by calling exit(), return code: 109

Check the followings:

1. /usr/sbin/suexec has +s flag set (you can set it by running chmod 4550 /usr/sbin/suexec )

2. the php-cgi binary path exists in your php-fcgid script

3. mod_fcgid is installed and enabled on your server

Wednesday, June 3, 2020

Centos 8: [How-to] install Mysql 5.6/5.7/8.0 PHP 5.6/7.4 and Virtualmin

Here is the gist I use to install Virtualmin / Mysql / PHP on CentOS 8 :

# Fixing perl locale warning
echo "LANGUAGE=en_US.utf8
LC_ALL=en_US.utf-8
LANG=en_US.utf8
LC_TYPE=en_US.utf8" > /etc/environment

# Logout SSH and Login again to apply env

# Installing Mysql/Remi repo and required packages
yum install epel-release -y
yum install https://rpms.remirepo.net/enterprise/remi-release-8.rpm htop wget perl perl-DBD-MySQL screen net-tools yum-utils unzip glibc-langpack-en lsof vim-enhanced git nload iotop bind-utils tar zip telnet -y 

# Disabling default mysql mariadb php modules on centos 8
dnf module disable mysql mariadb php -y
echo "exclude=mariadb*" >> /etc/yum.conf

# Remi provides modular packages for PHP 7.2+
yum-config-manager --enable remi
dnf module enable php:remi-7.4 -y
yum update -y

## Instructions for Mysql 8.0
yum install https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm -y
yum install mysql-community-server
sed -i /etc/my.cnf -e "s,# default-authentication-plugin=mysql_native_password,default-authentication-plugin=mysql_native_password,g"
service mysqld start
echo "validate_password.policy=LOW" >> /etc/my.cnf
echo "max_allowed_packet = 100M" >> /etc/my.cnf

service mysqld restart

## Instructions for Mysql 5.7/5.6 from mysql's el7 repo
yum install https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm -y
yum-config-manager --disable mysql80-community
yum-config-manager --enable mysql57-community
yum install mysql-community-server
mysql -e "uninstall plugin validate_password;"
echo "max_allowed_packet = 100M" >> /etc/my.cnf
###

# Installing Virtualmin
echo "set nocompatible" > /root/.vimrc
wget http://software.virtualmin.com/gpl/scripts/install.sh
sh install.sh -m

# Configuring Virtualmin

sed -i /etc/webmin/virtual-server/*config -e "s/ Options=ExecCGI,Includes,IncludesNOEXEC,Indexes,MultiViews,SymLinksIfOwnerMatch//g"
sed -i /etc/webmin/mysql/config -e "s,mariadb,mysqld,g"
sed -i /etc/webmin/virtual-server/*config -e "s,quotas=1,quotas=0,g"
sed -i /etc/webmin/virtual-server/*config -e "s,collect_restart=0,collect_restart=1,g"
virtualmin set-global-feature --enable-feature ssl --default-on ssl

virtualmin set-global-feature --disable-feature virtualmin-dav --default-off virtualmin-dav
service webmin restart

# php 5.6
yum install php56-php-bcmath php56-php-common php56-php-gd php56-php-intl php56-php-ioncube-loader php56-php-litespeed php56-php-mbstring php56-php-mcrypt php56-php-mysqlnd php56-php-opcache php56-php-pdo php56-php-pecl-jsonc php56-php-pecl-zip php56-php-soap php56-php-xml php56-runtime php56-php-fpm php56-php-cgi php-zip -y

# php 7.3
dnf module install php:remi-7.3
dnf install php73-php-bcmath php73-php-common php73-php-gd php73-php-intl php73-php-ioncube-loader php73-php-litespeed php73-php-mbstring php73-php-mcrypt php73-php-mysqlnd php73-php-opcache php73-php-pdo php73-php-pecl-jsonc php73-php-pecl-zip php73-php-soap php73-php-xml php73-runtime php73-php-fpm php73-php-cgi php-zip -y

dnf install php-bcmath php-common php-gd php-intl php-ioncube-loader php-litespeed php-mbstring php-mcrypt php-mysqlnd php-opcache php-pdo php-pecl-zip php-soap php-xml php-zip -y

# Limit DNS recursion in named
# add to /etc/named.conf
allow-recursion { localhost; };

# Disable UseDNS in sshd
# Update /etc/ssh/sshd_config
UseDNS No

# Mysql config
# add to /etc/my.cnf
symbolic-links=0
local-infile=0
sql_mode = "NO_ENGINE_SUBSTITUTION"
collation-server = utf8mb4_unicode_ci
init-connect='SET NAMES utf8mb4'
character-set-server = utf8mb4


# Apache config:
echo '<IfModule mod_expires.c>
# Enable expirations
ExpiresActive On
# Default directive
# ExpiresDefault "access plus 15 days"
# My favicon
ExpiresByType image/x-icon "access plus 15 days.
# Images
ExpiresByType image/gif "access plus 15 days"
ExpiresByType image/png "access plus 15 days"
ExpiresByType image/jpg "access plus 15 days"
ExpiresByType image/jpeg "access plus 15 days"
# CSS
ExpiresByType text/css "access 15 days.
# Javascript
ExpiresByType application/javascript "access plus 15 days"
</IfModule>' > /etc/httpd/conf.d/expires.conf


echo '<IfModule deflate_module>
<Location />
SetOutputFilter DEFLATE
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \
\.(?:gif|jpe?g|png|swf)$ no-gzip dont-vary
</Location>
</IfModule>' > /etc/httpd/conf.d/deflate.conf

echo '<IfModule event.c>
    ServerLimit           15
    MaxClients           960
    StartServers           2
    ThreadsPerChild       64
    ThreadLimit           64
    MinSpareThreads       32
    # must be >= (MinSpareThreads + ThreadsPerChild)
    MaxSpareThreads      112
    # at 200 r/s, 20000 r results in a process lifetime of 2 minutes
    MaxRequestsPerChild 20000
</IfModule>' > /etc/httpd/conf.d/mpm.conf

# update mpm in /etc/httpd/conf.modules.d/00-mpm.conf

# high performance mpm_event /etc/httpd/conf.d/mpm.conf:

<IfModule event.c>
    ServerLimit           64
    ThreadsPerChild   256
    ThreadLimit           256
    MaxRequestWorkers   4096
    StartServers           2
    MinSpareThreads       32
    # must be >= (MinSpareThreads + ThreadsPerChild)
    MaxSpareThreads      112
    # at 200 r/s, 20000 r results in a process lifetime of 2 minutes
    MaxRequestsPerChild 20000
</IfModule>


# move /tmp to ram: /etc/fstab
tmpfs /tmp tmpfs mode=1777,nosuid,nodev 0 0


# /etc/php.ini
#update:
upload_max_filesize
post_max_size
memory_limit
max_execution_time
max_input_time


# Install Node.js 14.x
curl -sL https://rpm.nodesource.com/setup_14.x | bash -
yum install -y nodejs

# Install pm2 
npm i -g pm2

# Here is a helloworld node.js app.js 
const http = require('http');
http.createServer(function(request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end("Hello, World!\n");
}).listen(process.env.PORT);
console.log('7001');

# create a virtual server and place the app.js file then run the following commands to activate it

sudo -u $user pm2 start app.js
sudo -u $user pm2 save
sudo -u $user pm2 startup

# then proxypass requests in apache to the app
ProxyPass / http://127.0.0.1:7001/ timeout=60
ProxyPassReverse / http://127.0.0.1:7001/

# Installing ffmpeg gz 
sudo yum-config-manager --add-repo=https://negativo17.org/repos/epel-multimedia.repo
yum install ffmpeg -y

Friday, May 29, 2020

Forward Traffic from Public IP to Wireguard client behind NAT and Preserve IP

Wiregurad allows us to create virtual network interfaces between nodes that are in separate networks. This feature can be used to expose a server behind NAT with a Public IP address.

The main advantage of the method described in this post is that it preserves clients IP address, so the home server sees the real IP address of clients and can process them (e.g. block them in a firewall).

There are several posts on the internet on this topic however they are not complete, for example the method described in this post does not preserve IP address of clients and shows the wireguard server's IP address in requests instead.

Wireguard allows the Server in NAT accessible via VPS Public IP

I had an asterisk server at home on raspberry pi, and wanted to make it accessible via internet however the internet solution that was used there did not provide a public IP address. It's possible to create a SSH tunnel and forward ports using a VPS in a datacenter however  it would not preserve clients IP address. I wanted to see the real address of clients so that fail2ban can block bruteforce attacks against the asterisk server.

Steps:

VPS Server:
1. Enable net.ipv4.ip_forward on the VPS

2. Wireguard config on the VPS server is simple and does not have anything special:

[Interface]
Address = 10.0.1.1
ListenPort = <Wireguard Listen Port>
PrivateKey = <Wireguard VPS Server Private Key>

# Home
[Peer]
PublicKey = <Wireguard on Home server Public Key>
AllowedIPs = 10.0.1.2/32

where 10.0.1.1 is the local IP address of wireguard on VPS server and 10.0.1.2 is the local IP address of wireguard on Home server behind NAT.

3. Now, to forward Traffic to the VPS server, you need to use the following rules in IP tables : 

# To allow Forwarding IPs in IPtables: 
iptables -A FORWARD -i wg0 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o wg0 -j ACCEPT

# This rule can be used if it is not needed tp preserve clients IP
# iptables -t nat -A POSTROUTING -o wg0 -j MASQUERADE

This rule is needed to provide internet to Home server when preserving clients IP
iptables -t nat -A POSTROUTING -s '10.0.1.0/24' -o eth0 -j MASQUERADE

# Forward TCP / UDP ports here to the server home
# TCP Public:8080 -> Home:443
iptables -t nat -A PREROUTING -p tcp -d VPS.Public.IP.Address --dport 8080 -j DNAT --to-destination 10.0.1.2:443
# TCP Public:8822 -> Home:22
iptables -t nat -A PREROUTING -p tcp -d VPS.Public.IP.Address --dport 8822 -j DNAT --to-destination 10.0.1.2:22
# UDP Public:5060 -> Home:5060
iptables -t nat -A PREROUTING -p udp -d VPS.Public.IP.Address --dport 5060 -j DNAT --to-destination 10.0.1.2:5060
# UDP Range Public:11000-11200 -> Home:11000-11200
iptables -t nat -A PREROUTING -p udp -d VPS.Public.IP.Address --dport 11000:11200 -j DNAT --to-destination 10.0.1.2:11000-11200

Home server in NAT: 
Wireguard config on the Home server is a bit more tricky. 

[Interface]
PrivateKey = <Wireguard on Home server Private Key>
Address = 10.0.1.2

[Peer]
PublicKey = <Wireguard VPS Server Public Key>

# This rule will not preserve clients IP 
# AllowedIPs = 10.0.1.1/24
# This rule will preserve clients IP:
# This is a Sample range, you need to use the script provided below to 
# exclude you VPS IP / Local NAT IP from 0.0.0.0/0 range, then use it here
AllowedIPs = 128.0.0.0/1, 64.0.0.0/2, 32.0.0.0/3, 16.0.0.0/4, 0.0.0.0/5, 12.0.0.0/6, 10.0.0.0/7, 9.0.0.0/8, 8.128.0.0/9, 8.64.0.0/10, 8.32.0.0/11, 8.16.0.0/12, 8.0.0.0/13, 8.12.0.0/14, 8.10.0.0/15, 8.9.0.0/16, 8.8.128.0/17, 8.8.64.0/18, 8.8.32.0/19, 8.8.16.0/20, 8.8.0.0/21, 8.8.12.0/22, 8.8.10.0/23, 8.8.9.0/24, 8.8.8.128/25, 8.8.8.64/26, 8.8.8.32/27, 8.8.8.16/28, 8.8.8.0/29, 8.8.8.12/30, 8.8.8.10/31, 8.8.8.9/32
Endpoint = <VPS PUBLIC IP>:<Wireguard Listen Port>
PersistentKeepalive = 25 

AllowedIPs is the tricky part here. 

One can use AllowedIPs = 10.0.1.1/24 here with iptables -t nat -A POSTROUTING -o wg0 -j MASQUERADE  rule in iptables of the VPS, this will let the home server to be accessible through the forwarded ports, however the home server will not see the real IP address of clients, and will  see all requests coming from 10.0.1.1, the IP address of wireguard VPS instead.

To let the home server accessible through the Public IP address of VPS and make it see the real IP address of clients, it is required to route packets that arrive to server home to come back through wireguard. So basically we need to add all IP ranges to AllowedIPs Except VPS IP address and other local network addresses that we dont want to go through wireguard.

It is not possible to use AllowedIPs = 0.0.0.0/0 directly, as wireguard will not be able to connect to our VPS IP address then. We also don't want our Local NAT IP range to go through Wireguard.  So we use the following Shell script to exclude our VPS IP/Local IP range from 0.0.0.0/0 range :

#!/bin/bash
echo "enter the broader range e.g. 176.0.0.0/4"
read r1
echo "enter the exclude ip e.g. 18.20.18.8/32"
read r2
pshell=`cat <<EOF
import ipaddress
n1 = ipaddress.ip_network('$r1')
n2 = ipaddress.ip_network('$r2')
l = list(n1.address_exclude(n2))
print(l)`

python3 -c "$pshell" | sed -e "s,IPv4Network(',,g" | sed -e "s,'),,g" | sed -e "s,\[,,g" | sed -e "s,\],,g"

It requires ipaddress python3 package to work.

Thursday, April 16, 2020

VoIP / SIP Settings on different versions of Android

Android phones come with a native VoIP client that works great. The settings are placed in different paths though, in this post I'll list the path to the setting on different versions of Android:

Android 4.2.2 (Jelly Bean) - (Huawei Y330):
Dialer App -> Settings -> Internet Call

Android 5.0 (Lollipop) -  Asus Fonepad 7 FE171CG:
Settings -> Call Settings -> Phone account settings

Android 5.1.1 ((Lollipop)  - Huawei Redmi 3:
Phone App -> Settings -> Advanced Settings -> SIP Settings

Android 9 (Pie) - Mi A3 / A1:
Phone App -> Settings -> Calling Accounts

Wednesday, April 15, 2020

How to configure VoIP on GreenPacket DT-350

آموزش راه اندازی تلفن اینترنتی VoIP بر روی مودم TD-LTE DT-350 ایرانسل

Irancell TD-LTE TD-350 modem offers a hardware VoIP client and one can connect a phone to the RJ45 port on the modem to use this feature. However, VoIP settings are disabled by default and it is not possible to enable it using the admin user since this user is an Enduser and not a Superuser.

 


Thanks to this post, it is possible to find the superuser defined for Greenpacket modems. Irancell has set the username for superuser on its modems to administrator and the password is also administrator: 

User: administrator
Pass: administrator

This user has privileges to manage many more settings including VoIP settings :



And Voila! It works pretty well!




Sunday, March 29, 2020

Lantronix KVM Java error FIX: Use Latronix native client instead

Latronix KVM provides HTML5 console however its not possible to mount images there so you would need to set to Java console. I was getting the following error each time I tried to run their Java console:

"unsigned application requesting unrestricted access to system"

I tested Java 1.8, 1.7, 1.6, 1.5 and 1.4 and all failed to run spider.jnlp file of Latronix KVM and returned the above error. There was a fix suggested to run it using Java however it did not work for me either.

I managed to mount ISO image to the VM by using Latronix KVM client software SpiderView which can be downloaded on their website.

Sunday, March 1, 2020

How install Xfce4 and RealVNC on Centos 7

Xfce is a lightweight desktop environment and it's a good choice as a GUI for servers running Centos 7 . It can be installed by using the following command :

yum groupinstall "Xfce" -y

However Xfce does not start properly with RealVNC on Centos 7. The following commands are needed to fix the problem according to RealVNC website :

Create a file called /etc/vnc/xstartup.custom and make it executable (chmod +x) with the following content :

#!/bin/sh
DESKTOP_SESSION=xfce
export DESKTOP_SESSION
startxfce4
vncserver-virtual -kill $DISPLAY


Create another file called /etc/vnc/config.custom and add the following commands :

-extension RENDER


and finally use this guide to fix "xfce GDBus.Error:org.freedesktop.PolicyKit1.Error.Failed: User of caller and user of subject differs." error on xfce startup.

How to disable Debian 12 sleep on production servers

 Debian 12 has power saver enabled by default which causes your server to go to sleep if there is no mouse / keyboard interaction. To resolv...