Posts Tagged ‘systemd’

How to redirect TCP port traffic from Internet Public IP host to remote local LAN server, Redirect traffic for Apache Webserver, MySQL, or other TCP service to remote host

Thursday, September 23rd, 2021






1. Use the good old times rinetd – internet “redirection server” service

Perhaps, many people who are younger wouldn't remember rinetd's use was pretty common on old Linuxes in the age where iptables was not on the scene and its predecessor ipchains was so common.
In the raise of mass internet rinetd started loosing its popularity because the service was exposed to the outer world and due to security holes and many exploits circulating the script kiddie communities
many servers get hacked "pwned" in the jargon of the script kiddies.

rinetd is still available even in modern Linuxes and over the last years I did not heard any severe security concerns regarding it, but the old paranoia perhaps and the set to oblivion makes it still unpopular soluttion for port redirect today in year 2021.
However for a local secured DMZ lans I can tell you that its use is mostly useful and I chooes to use it myself, everynow and then due to its simplicity to configure and use.
rinetd is pretty standard among unixes and is also available in old Sun OS / Solaris and BSD-es and pretty much everything on the Unix scene.

Below is excerpt from 'man rinetd':


     rinetd redirects TCP connections from one IP address and port to another. rinetd is a single-process server which handles any number of connections to the address/port pairs
     specified in the file /etc/rinetd.conf.  Since rinetd runs as a single process using nonblocking I/O, it is able to redirect a large number of connections without a severe im‐
     pact on the machine. This makes it practical to run TCP services on machines inside an IP masquerading firewall. rinetd does not redirect FTP, because FTP requires more than
     one socket.
     rinetd is typically launched at boot time, using the following syntax:      /usr/sbin/rinetd      The configuration file is found in the file /etc/rinetd.conf, unless another file is specified using the -c command line option.

To use rinetd on any LInux distro you have to install and enable it with apt or yum as usual. For example on my Debian GNU / Linux home machine to use it I had to install .deb package, enable and start it it via systemd :


server:~# apt install –yes rinetd

server:~#  systemctl enable rinetd

server:~#  systemctl start rinetd

server:~#  systemctl status rinetd
● rinetd.service
   Loaded: loaded (/etc/init.d/rinetd; generated)
   Active: active (running) since Tue 2021-09-21 10:48:20 EEST; 2 days ago
     Docs: man:systemd-sysv-generator(8)
    Tasks: 1 (limit: 4915)
   Memory: 892.0K
   CGroup: /system.slice/rinetd.service
           └─1364 /usr/sbin/rinetd

rinetd is doing the traffic redirect via a separate process daemon, in order for it to function once you have service up check daemon is up as well.

root@server:/home/hipo# ps -ef|grep -i rinet
root       359     1  0 16:10 ?        00:00:00 /usr/sbin/rinetd
root       824 26430  0 16:10 pts/0    00:00:00 grep -i rinet

+ Configuring a new port redirect with rinetd


Is pretty straight forward everything is handled via one single configuration – /etc/rinetd.conf

The format (syntax) of a forwarding rule is as follows:

     [bindaddress] [bindport] [connectaddress] [connectport]

Besides that rinetd , could be used as a primitive firewall substitute to iptables, general syntax of allow deny an IP address is done with (allow, deny) keywords:

allow 192.168.2.*

To enable logging to external file ,you'll have to include in the configuration:

# logging information
logfile /var/log/rinetd.log

Here is an example rinetd.conf configuration, redirecting tcp mysql 3306, nginx on port 80 and a second web service frontend for ILO to server reachable via port 8888 and a redirect from External IP to local IP SMTP server.


# this is the configuration file for rinetd, the internet redirection server
# you may specify global allow and deny rules here
# only ip addresses are matched, hostnames cannot be specified here
# the wildcards you may use are * and ?
# allow 192.168.2.*
# deny

# forwarding rules come here
# you may specify allow and deny rules after a specific forwarding rule
# to apply to only that forwarding rule
# bindadress    bindport  connectaddress  connectport

# logging information
logfile /var/log/rinetd.log        80         80        3306          3306        443         443
# enable for access to ILO        8888   443    25    25 is my external ( Public )  IP internet address where,, (are the DMZ-ed Lan internal IPs) with various services.

To identify the services for which rinetd is properly configured to redirect / forward traffic you can see it with netstat or the newer ss command

root@server:/home/hipo# netstat -tap|grep -i rinet
tcp        0      0*               LISTEN      13511/rinetd      
tcp        0      0 www.pc-freak.n:http-alt*               LISTEN      21176/rinetd        
tcp        0      0*               LISTEN      21176/rinetd      


+ Using rinetd to redirect External interface IP to loopback's port (


If you have the need to redirect an External connectable living service be it apache mysql / privoxy / squid or whatever rinetd is perhaps the tool of choice (especially since there is no way to do it with iptables.

If you want to redirect all traffic which is accessed via Linux's loopback interface (localhost) to be reaching a remote host on TCP port 1083 and 1888, use below config

# bindadress    bindport  connectaddress  connectport        1083         1083        1888         1888


For a quick and dirty solution to redirect traffic rinetd is very useful, however you'll have to keep in mind that if you want to redirect traffic for tens of thousands of connections constantly originating from the internet you might end up with some disconnects as well as notice a increased use of rinetd CPU use with the incrased number of forwarded connections.


2. Redirect TCP / IP port using DNAT iptables firewall rules


Lets say you have some proxy, webservice or whatever service running on port 5900 to be redirected with iptables.
The easeiest legacy way is to simply add the redirection rules to /etc/rc.local​. In newer Linuxes rc.local so if you decide to use,
you'll have to enable rc.local , I've written earlier a short article on how to enable rc.local on newer Debian, Fedora, CentOS


# redirect 5900 TCP service 
sysctl -w net.ipv4.conf.all.route_localnet=1
iptables -t nat -I PREROUTING -p tcp –dport 5900 -j REDIRECT –to-ports 5900
iptables -t nat -I OUTPUT -p tcp -o lo –dport 5900 -j REDIRECT –to-ports 5900
iptables -t nat -A OUTPUT -o lo -d -p tcp –dport 5900 -j DNAT  –to-destination
iptables -t nat -I OUTPUT –source 0/0 –destination 0/0 -p tcp –dport 5900 -j REDIRECT –to-ports 5900


Here is another two example which redirects port 2208 (which has configured a bind listener for SSH on Internal host from External Internet IP address (XXX.YYY.ZZZ.XYZ) 

# Port redirect for SSH to VM on openxen internal Local lan server 
-A PREROUTING  -p tcp –dport 2208 -j DNAT –to-destination
-A POSTROUTING -p tcp –dst –dport 2208 -j SNAT –to-source


3. Redirect TCP traffic connections with redir tool


If you look for an easy straight forward way to redirect TCP traffic, installing and using redir (ready compiled program) might be a good idea.

root@server:~# apt-cache show redir|grep -i desc -A5 -B5
Version: 3.2-1
Installed-Size: 60
Maintainer: Lucas Kanashiro <>
Architecture: amd64
Depends: libc6 (>= 2.15)
Description-en: Redirect TCP connections
 It can run under inetd or stand alone (in which case it handles multiple
 connections).  It is 8 bit clean, not limited to line mode, is small and
 light. Supports transparency, FTP redirects, http proxying, NAT and bandwidth
 redir is all you need to redirect traffic across firewalls that authenticate
 based on an IP address etc. No need for the firewall toolkit. The
 functionality of inetd/tcpd and "redir" will allow you to do everything you
 need without screwy telnet/ftp etc gateways. (I assume you are running IP
 Masquerading of course.)

Description-md5: 2089a3403d126a5a0bcf29b22b68406d
Tag: interface::daemon, network::server, network::service, role::program,
Section: net
Priority: optional



server:~# apt-get install –yes redir

Here is a short description taken from its man page 'man redir'


     redir redirects TCP connections coming in on a local port, [SRC]:PORT, to a specified address/port combination, [DST]:PORT.  Both the SRC and DST arguments can be left out,
     redir will then use

     redir can be run either from inetd or as a standalone daemon.  In –inetd mode the listening SRC:PORT combo is handled by another process, usually inetd, and a connected
     socket is handed over to redir via stdin.  Hence only [DST]:PORT is required in –inetd mode.  In standalone mode redir can run either in the foreground, -n, or in the back‐
     ground, detached like a proper UNIX daemon.  This is the default.  When running in the foreground log messages are also printed to stderr, unless the -s flag is given.

     Depending on how redir was compiled, not all options may be available.


+ Use redir to redirect TCP traffic one time


Lets say you have a MySQL running on remote machine on some internal or external IP address, lets say and you want to redirect all traffic from remote host to the machine (, where you run your Apache Webserver, which you want to configure to use
as MySQL localhost TCP port 3306.

Assuming there are no irewall restrictions between Host A ( and Host B ( is already permitting connectivity on TCP/IP port 3306 between the two machines.

To open redirection from localhost on ->


server:~# redir –laddr= –lport=3306 –caddr= –cport=3306


If you need other third party hosts to be additionally reaching via TCP 3306.

root@server:~# redir –laddr= –lport=3306 –caddr= –cport=3306

Of course once you close, the /dev/tty or /dev/vty console the connection redirect will be cancelled.


+ Making TCP port forwarding from Host A to Host B permanent

One solution to make the redir setup rules permanent is to use –rinetd option or simply background the process, nevertheless I prefer to use instead GNU Screen.
If you don't know screen is a vVrtual Console Emulation manager with VT100/ANSI terminal emulation to so, if you don't have screen present on the host install it with whatever Linux OS package manager is present and run:


root@server:~#screen -dm bash -c 'redir –laddr= –lport=3306 –caddr= –cport=3306'


That would run it into screen session and detach so you can later connect, if you want you can make redir to also log connections via syslog with ( -s) option.

I found also useful to be able to track real time what's going on currently with the opened redirect socket by changing redir log level.

Accepted log level is:


  -l, –loglevel=LEVEL
             Set log level: none, err, notice, info, debug.  Default is notice.


root@server:/ # screen -dm bash -c 'redir –laddr= –lport=3308 –caddr= –cport=3306 -l debug'


To test connectivity works as expected use telnet:

root@server:/ # telnet localhost 3308
Connected to localhost.
Escape character is '^]'.

6#HY000Proxy header is not accepted from Connection closed by foreign host.

once you attach to screen session with


root@server:/home #  screen -r


You will get connectivity attempt from localhost logged : .

redir[10640]: listening on
redir[10640]: target is
redir[10640]: Waiting for client to connect on server socket …
redir[10640]: target is
redir[10640]: Waiting for client to connect on server socket …
redir[10793]: peer IP is
redir[10793]: peer socket is 25592
redir[10793]: target IP address is
redir[10793]: target port is 3306
redir[10793]: Connecting to
redir[10793]: Entering copyloop() – timeout is 0
redir[10793]: Disconnect after 1 sec, 165 bytes in, 4 bytes out

The downsides of using redir is redirection is handled by the separate process which is all time hanging in the process list, as well as the connection redirection speed of incoming connections might be about at least 30% slower to if you simply use a software (firewall ) redirect such as iptables. If you use something like kernel IP set ( ipsets ). If you hear of ipset for a first time and you wander whta it is below is short package description.


root@server:/root# apt-cache show ipset|grep -i description -A13 -B5
Maintainer: Debian Netfilter Packaging Team <>
Architecture: amd64
Provides: ipset-6.38
Depends: iptables, libc6 (>= 2.4), libipset11 (>= 6.38-1~)
Breaks: xtables-addons-common (<< 1.41~)
Description-en: administration tool for kernel IP sets
 IP sets are a framework inside the Linux 2.4.x and 2.6.x kernel which can be
 administered by the ipset(8) utility. Depending on the type, currently an
 IP set may store IP addresses, (TCP/UDP) port numbers or IP addresses with
 MAC addresses in a  way which ensures lightning speed when matching an
 entry against a set.
 If you want to
  * store multiple IP addresses or port numbers and match against the
    entire collection using a single iptables rule.
  * dynamically update iptables rules against IP addresses or ports without
    performance penalty.
  * express complex IP address and ports based rulesets with a single
    iptables rule and benefit from the speed of IP sets.

 then IP sets may be the proper tool for you.
Description-md5: d87e199641d9d6fbb0e52a65cf412bde
Tag: implemented-in::c, role::program
Section: net
Priority: optional
Filename: pool/main/i/ipset/ipset_6.38-1.2_amd64.deb
Size: 50684
MD5sum: 095760c5db23552a9ae180bd58bc8efb
SHA256: 2e2d1c3d494fe32755324bf040ffcb614cf180327736c22168b4ddf51d462522

Set all logs to log to to physical console /dev/tty12 (tty12) on Linux

Wednesday, August 12th, 2020

tty linux-logo how to log everything to last console terminal tty12

Those who administer servers from the days of birth of Linux and who used actively GNU / Linux over the years or any other UNIX knows how practical could be to configure logging of all running services / kernel messages / errors and warnings on a physical console.

Traditionally from the days I was learning Linux basics I was shown how to do this on an old Debian Sarge 3.0 Linux without systemd and on all Linux distributions Redhat 9.0 / Calderas and Mandrakes I've used either as a home systems or for servers. I've always configured output of all messages to go to the last easy to access console /dev/tty12 (for those who never use it console switching under Linux plain text console mode is done with key combination of CTRL + ALT + F1 .. F12.

In recent times however with the introduction of systemd pretty much things changed as messages to console are not handled by /etc/inittab which was used to add and refresh physical consoles tty1, tty2 … tty7 (the default added one on Linux were usually 7), but I had to manually include more respawn lines for each console in /etc/inittab.
Nowadays as of year 2020 Linux distros /etc/inittab is no longer there being obsoleted and console print out of INPUT / OUTPUT messages are handled by systemd.

1. Enable Physical TTYs from TTY8 till TTY12 etc.

The number of default consoles existing in most Linux distributions I've seen is still from tty1 to tty7. Hence to add more tty consoles and be ready to be able to switch out  not only towards tty7 but towards tty12 once you're connected to the server via a remote ILO (Integrated Lights Out) / IdRAC (Dell Remote Access Controller) / IPMI / IMM (Imtegrated Management Module), you have to do it by telling systemd issuing below systemctl commands:


 # systemctl enable getty@tty8.service Created symlink /etc/systemd/system/ -> /lib/systemd/system/getty@.service.

systemctl enable getty@tty9.service

Created symlink /etc/systemd/system/ -> /lib/systemd/system/getty@.service.

systemctl enable getty@tty10.service

Created symlink /etc/systemd/system/ -> /lib/systemd/system/getty@.service.

systemctl enable getty@tty11.service

Created symlink /etc/systemd/system/ -> /lib/systemd/system/getty@.service.

systemctl enable getty@tty12.service

Created symlink /etc/systemd/system/ -> /lib/systemd/system/getty@.service.

Once the TTYS tty7 to tty12 are enabled you will be able to switch to this consoles either if you have a physical LCD / CRT monitor or KVM switch connected to the machine mounted on the Rack shelf once you're in the Data Center or will be able to see it once connected remotely via the Management IP Interface (ILO) remote console.

2. Taking screenshot of the physical console TTY with fbcat

For example below is a screenshot of the 10th enabled tty10:


As you can in the screenshot I've used the nice tool fbcat that can be used to make a screenshot of remote console. This is very useful especially if remote access via a SSH client such as PuTTY / MobaXterm is not there but you have only a physical attached monitor access on a DCs that are under a heavy firewall that is preventing anyone to get to the system remotely. For example screenshotting the physical console in case if there is a major hardware failure occurs and you need to dump a hardware error message to a flash drive that will be used to later be handled to technicians to analyize it and exchange the broken server hardware part.

Screenshots of the CLI with fbcat is possible across most Linux distributions where as usual.

In Debian you have to first instal the tool via :

# apt install –yes fbcat

and on RedHats / CentOS / Fedoras

# yum install -y fbcat

Taking screenshot once tool is on the server of whatever you have printed on console is as easy as

# fbcat > tty_name.ppm

Note that you might want to convert the .ppm created picture to png with any converter such as imagemagick's convert command or if you have a GUI perhaps with GNU Image Manipulation Tool (GIMP).

3. Enabling every rsyslog handled message to log to Physical TTY12

To make everything such as errors, notices, debug, warning messages  become instantly logging towards above added new /dev/tty12.

Open /etc/rsyslog.conf and to the end of the file append below line :

   *.=notice;*.=warn   /dev/tty12

To make rsyslog load its new config restart it:


# systemctl status rsyslog




rsyslog.service – System Logging Service
   Loaded: loaded (/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2020-08-10 04:09:36 EEST; 2 days ago
     Docs: man:rsyslogd(8)
 Main PID: 671 (rsyslogd)
    Tasks: 4 (limit: 4915)
   Memory: 12.5M
   CGroup: /system.slice/rsyslog.service
           └─671 /usr/sbin/rsyslogd -n -iNONE


авг 12 00:00:05 pcfreak rsyslogd[671]:  [origin software="rsyslogd" swVersion="8.1901.0" x-pid="671" x-info="https://www.rsyslo
Warning: Journal has been rotated since unit was started. Log output is incomplete or unavailable.


systemctl restart rsyslog

That's all folks navigate by pressing simultaneously CTRL + ALT + F12 to get to TTY12 or use ALT + LEFT / ALT + RIGHT ARROW (console switch commands) till you get to the console where everything should be now logged.

Enjoy and if you like this article share to tell your sysadmin friends about this nice hack  ! 🙂




Make Laptop Sleep on LID (Monitor) close in Linux Debian and Ubuntu systemd Linux

Monday, June 22nd, 2020




I need to make my laptop automatically sleep on LID Screen close but it doesn't why?

If have used your laptop for long years with Windows or any Windows user is used to the default beavrior of Windows to automatically sleep the computer on PC close. This default behavior of automatically sleep on LID Close has been Windows standard for many years
and the reason behind that usually laptop is used for mobility and working on a discharging battery so a LID screen close puts the laptop in (SLEEP) BATTERY SUSPEND MODE aiming to make the charged battery last longer. However often for Desktop use in the Office LID close 
trigger of laptop sleep mode is annoying and undesired I've blogged earlier on that issue and how to make laptop not to sleep on LID close on M$ Windows 10 here.

This bahavior was copied and was working in many of the Linux distributions for years however in Debian GNU / Linux and Ubuntu 16.X this feature is often not properly working due to a systemd bug. Of course closing the notebook LID screen without putting
the PC in sleep mode is not a bug but a very useful feature for those who use their laptop as a Desktop machine that is non-stop running, however for most ppl default behavior to auto-suspend the computer on Laptop Monitor close is desired.

Here is how to  force the close of the laptop lid to go to suspend/sleep mode and when open the lid, it wake it up.


1. First requirement is to make sure the laptop has installed the package pm-utils, if it is not there install it with:


# apt-get install –yes pm-utils


2. Next we need to edit logind.conf and append 3 variables


# vim /etc/systemd/logind.conf

Normally the file should have a bit of commented informative lines as well as a commented variables that could be enabled like so:



These entries are usually the files that are used by default as a systemd settings.
Before starting make a copy just you happen to mess systemd.conf, e.g.:


cp -rpf /etc/systemd/logind.conf /etc/systemd/logind.conf_bak

To make the PC LID close active append in the end of file below 3 lines:





Save the file and to make systemd daemon reload restart the PC, even though theoretically systemd can be reloaded to digest its new /etc/systemd/logind.conf with:


# systemctl daemon-reexec


3. Assure yourself the Power Management LID setting of the Desktop Graphical User Interface are set to SUSPEND on close

I use MATE Desktop environment as it is simplistic and quite stable fork of GNOME 2.0, anyway depending on the GUI used on the Linux powered laptop e.g. GNOME / KDE Plasma / XFce etc. make sure the respective

Control Panel -> Power Management

settings are set to Force the Laptop Screen LID SUSPEND on Close.

Below is how this is done on MATE:



That's all folks, now close your Laptop and enjoy it going to sleep, open it up and get it awaked 🙂 Cheers !