Setting up Knockd issues - ubuntu-server

I asked this question on security overflow last week, however there were no responses, so I am hoping that you can help here. The question is below:
So i'm busy setting up a knockd service on a VM to enable SSH login when the correct sequence of ports are "knocked on" using knockd and ufw.
The issue that I am currently having is that when the correct sequence of ports are selected, the user.rules for ufw is not able to write the new rule to a file.
I have tried using chmod 777 on all files within /etc/ufw as a test, however the file is still not writable.
The output for /etc/ufw/user.rules is as follows:
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/after6.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/after6.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user6.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user6.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/applications.d is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/applications.d is group writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user.rules is world writable!
Jun 14 13:13:31 Pop knockd[4780]: WARN: /etc/ufw/user.rules is group writable!
Jun 14 13:13:31 Pop knockd[4780]: ERROR: '/etc/ufw/user.rules' is not writable
Jun 14 13:13:31 Pop knockd[4780]: openSSH: command returned non-zero status code (1)
The knockd file is shown in the code block below:
[options]
logfile = /var/log/knockd.log
[openSSH]
sequence = 7000,8000,9000
seq_timeout = 5
command = ufw allow 22/tcp
tcpflags = syn
[closeSSH]
sequence = 9000,8000,7000
seq_timeout = 5
command = ufw delete allow 22/tcp
tcpflags = syn
The output for /etc/default/knockd is shown below:
# control if we start knockd at init or not
# 1 = start
# anything else = don't start
# PLEASE EDIT /etc/knockd.conf BEFORE ENABLING
START_KNOCKD=1
# command line options
KNOCKD_OPTS="-i enp0s3"
Any advice would be greatly appreciated.

First heed the warning and reset permission to all files you changed. Having write permissions for all users on your firewall rules isn't a good idea. That is do:
chmod -R ga-w /etc/ufw
Then disable (comment out or set explicit to off) ProtectSystem directive at knockd.service file (found in /lib/systemd/system/ folder).
If this works, reset it to full and put below it
ReadWritePaths=-/etc/ufw/
ProtectSystem=full mounts ro /usr, /boot and /etc for processes invoked by the unit excluding directories specified in ReadWritePaths.
If running, before restarting the service do
systemctl daemon-reload

I have hit the same problem with a knockd /etc/ufw/user.rules not writeable error. The knock packets show up in syslog and the ufw insert 1 ... command is attempted. My current best guess at the cause is the cgroups system.
Using iptables commands instead of ufw commands in /etc/knockd.conf works for me.

I had same problem but solved it by cleaning out both ip4 and ip6 tables.
In one error message it said that 'xtable' was locked by another process.
ufw disable
iptables -F
iptables -X
ip6tables -F
ip6tables -X
ufw enable
try knocking
and then check
service knockd status

Related

Issue with watchdog ping (watchdog: error opening socket (Operation not permitted))

I have an issue with my Pi 4 where it seems the networking crashes at some point. The pi still runs but network is unreachable. I tried setting the ping command in my watchdog.conf but I am getting an error watchdog: error opening socket (Operation not permitted)
Hardware: Pi 4 8GB
OS: Raspberry Pi OS Lite (64-bit)
Watchdog version: 5.16
My watchdog.conf:
# ====================================================================
# Configuration for the watchdog daemon. For more information on the
# parameters in this file use the command 'man watchdog.conf'
# ====================================================================
# =================== The hardware timer settings ====================
#
# For this daemon to be effective it really needs some hardware timer
# to back up any reboot actions. If you have a server then see if it
# has IPMI support. Otherwise for Intel-based machines try the iTCO_wdt
# module, otherwise (or if that fails) then see if any of the following
# module load and work:
#
# it87_wdt it8712f_wdt w83627hf_wdt w83877f_wdt w83977f_wdt
#
# If all else fails then 'softdog' is better than no timer at all!
# Or work your way through the modules listed under:
#
# /lib/modules/`uname -r`/kernel/drivers/watchdog/
#
# To see if they load, present /dev/watchdog, and are capable of
# resetting the system on time-out.
# Uncomment this to use the watchdog device driver access "file".
#verbose=yes
watchdog-device = /dev/watchdog
# Uncomment and edit this line for hardware timeout values that differ
# from the default of one minute.
watchdog-timeout = 15
# If your watchdog trips by itself when the first timeout interval
# elapses then try uncommenting the line below and changing the
# value to 'yes'.
#watchdog-refresh-use-settimeout = auto
# If you have a buggy watchdog device (e.g. some IPMI implementations)
# try uncommenting this line and setting it to 'yes'.
#watchdog-refresh-ignore-errors = no
# ====================== Other system settings ========================
#
# Interval between tests. Should be a couple of seconds shorter than
# the hardware time-out value.
#interval = 1
# The number of intervals skipped before a log message is written (i.e.
# a multiplier for 'interval' in terms of syslog messages)
#logtick = 1
# Directory for log files (probably best not to change this)
log-dir = /var/log/watchdog
# Email address for sending the reboot reason. This needs sendmail to
# be installed and properly configured. Maybe you should just enable
# syslog forwarding instead?
#admin = root
# Lock the daemon in to memory as a real-time process. This greatly
# decreases the chance that watchdog won't be scheduled before your
# machine is really loaded.
realtime = yes
priority = 1
# ====================== How to handle errors =======================
#
# If you have a custom binary/script to handle errors then uncomment
# this line and provide the path. For 'v1' test binary files they also
# handle error cases.
#repair-binary = /usr/sbin/repair
#repair-timeout = 60
# The retry-timeout and repair limit are used to handle errors in a
# more robust manner. Errors must persist for longer than this to
# action a repair or reboot, and if repair-maximum attempts are
# made without the test passing a reboot is initiated anyway.
#retry-timeout = 60
#repair-maximum = 1
# Configure the delay on reboot from sending SIGTERM to all processes
# and to following up with SIGKILL for any that are ignoring the polite
# request to stop.
#sigterm-delay = 5
# ====================== User-specified tests ========================
#
# Specify the directory for auto-added 'v1' test programs (any executable
# found in the 'test-directory should be listed).
#test-directory = /etc/watchdog.d
# Specify any v0 custom tests here. Multiple lines are permitted, but
# having any 'v1' programs/scripts discovered in the 'test-directory' is
# the better way.
#test-binary =
# Specify the time-out value for a test error to be reported.
#test-timeout = 60
# ====================== Typical tests ===============================
#
# Specify any IPv4 numeric addresses to be probed.
# NOTE: You should check you have permission to ping any machine before
# using it as a test. Also remember if the target goes down then this
# machine will reboot as a result!
#ping = 192.168.1.1
# Set the number of ping attempts in each 'interval' of time. Default
# is 3 and it completes on the first successful ping.
# NOTE: Round-trip delay has to be less than 'interval' / 'ping-count'
# for test success, but this is unlikely to be exceeded except possibly
# on satellite links (very unlikely case!).
# Specify any network interface to be checked for activity.
interface = eth0
# Specify any files to be checked for presence, and if desired, checked
# that they have been updated more recently than 'change' seconds.
#file = /var/log/syslog
#change = 1407
# Uncomment to enable load average tests for 1, 5 and 15 minute
# averages. Setting one of these values to '0' disables it. These
# values will hopefully never reboot your machine during normal use
# (if your machine is really hung, the loadavg will go much higher
# than 25 in most cases).
max-load-1 = 24
#max-load-5 = 18
#max-load-15 = 12
# Check available memory on the machine.
#
# The min-memory check is a passive test from reading the file
# /proc/meminfo and computed from MemFree + Buffers + Cached
# If this is below a few tens of MB you are likely to have problems.
#
# The allocatable-memory is an active test checking it can be paged
# in to use.
#
# Maximum swap should be based on normal use, probably a large part of
# available swap but paging 1GB of swap can take tens of seconds.
#
# NOTE: This is the number of pages, to get the real size, check how
# large the pagesize is on your machine (typically 4kB for x86 hardware).
#min-memory = 1
#allocatable-memory = 1
#max-swap = 0
# Check for over-temperature. Typically the temperature-sensor is a
# 'virtual file' under /sys and it contains the temperature in
# milli-Celsius. Usually these are generated by the 'sensors' package,
# but take care as device enumeration may not be fixed.
#temperature-sensor =
#max-temperature = 90
# Check for a running process/daemon by its PID file. For example,
# check if rsyslogd is still running by enabling the following line:
#pidfile = /var/run/rsyslogd.pid
This runs fine checking the status of the service:
pi#raspberrypi:~ $ sudo service watchdog status
● watchdog.service - watchdog daemon
Loaded: loaded (/lib/systemd/system/watchdog.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2022-04-12 08:01:53 BST; 2min 17s ago
Process: 2120 ExecStartPre=/bin/sh -c [ -z "${watchdog_module}" ] || [ "${watchdog_module}" = "none" ] || /sbin/modprobe $watchdog_module (code=exited, status=0/SUCCESS)
Process: 2121 ExecStart=/bin/sh -c [ $run_watchdog != 1 ] || exec /usr/sbin/watchdog $watchdog_options (code=exited, status=0/SUCCESS)
Main PID: 2126 (watchdog)
Tasks: 1 (limit: 8986)
CPU: 59ms
CGroup: /system.slice/watchdog.service
└─2126 /usr/sbin/watchdog
Apr 12 08:01:53 raspberrypi watchdog[2126]: interface: eth0
Apr 12 08:01:53 raspberrypi watchdog[2126]: temperature: no sensors to check
Apr 12 08:01:53 raspberrypi watchdog[2126]: no test binary files
Apr 12 08:01:53 raspberrypi watchdog[2126]: no repair binary files
Apr 12 08:01:53 raspberrypi watchdog[2126]: error retry time-out = 60 seconds
Apr 12 08:01:53 raspberrypi watchdog[2126]: repair attempts = 1
Apr 12 08:01:53 raspberrypi watchdog[2126]: alive=/dev/watchdog heartbeat=[none] to=root no_act=no force=no
Apr 12 08:01:53 raspberrypi watchdog[2126]: watchdog now set to 15 seconds
Apr 12 08:01:53 raspberrypi watchdog[2126]: hardware watchdog identity: Broadcom BCM2835 Watchdog timer
Apr 12 08:01:53 raspberrypi systemd[1]: Started watchdog daemon.
However when I try to enable the ping command in the conf file (#ping = 192.168.1.1) I get the following error running watchdog -v:
watchdog -v
watchdog: String 'watchdog-device' found as '/dev/watchdog'
watchdog: Integer 'watchdog-timeout' found = 15
watchdog: String 'log-dir' found as '/var/log/watchdog'
watchdog: Variable 'realtime' found as 'yes' = 1
watchdog: Integer 'priority' found = 1
watchdog: List 'ping' added as '192.168.1.1'
watchdog: List 'interface' added as 'eth0'
watchdog: Integer 'max-load-1' found = 24
watchdog: error opening socket (Operation not permitted)
This seems to indicate that it's not permitted to do the ping test.
I googled the issue and found nothing like this anywhere yet but I did try the solutions in these articles where none of them worked:
https://discuss.linuxcontainers.org/t/even-with-root-user-im-receiving-operation-not-permitted-when-try-creating-gluster-volume-between-ubuntu-14-04-lxc-containers/2699
https://superuser.com/questions/288521/problem-with-ping-open-socket-operation-not-permitted
Anyone have any ideas?

Dnsmasq fails to start every time I reboot my VPS

Dnsmasq fails to start every time I reboot my VPS. Below is the log about it.
Aug 22 18:14:51 debian dnsmasq[776]: dnsmasq: syntax check OK.
Aug 22 18:14:51 debian dnsmasq[798]: chown: invalid user: ‘dnsmasq:nogroup’
Aug 22 18:14:51 debian systemd[1]: dnsmasq.service: Control process exited, code=exited status=2
Aug 22 18:14:51 debian systemd[1]: Failed to start dnsmasq - A lightweight DHCP and caching DNS server.
Aug 22 18:14:51 debian systemd[1]: dnsmasq.service: Unit entered failed state.
Aug 22 18:14:51 debian systemd[1]: dnsmasq.service: Failed with result 'exit-code'.
I'd set the user and group name correctly in /etc/dnsmasq.conf file. I tried to reinstall dnsmasq and then it worked. But after I reboot the VPS, it failed to start again. Then I have to reinstall again...
So, If I want to use dnsmasq, I have to not to reboot my VPS. But I want to know what causes this and how to fix it once and for all. My VPS's system is Debian 9, kernel is 4.9.0-7-amd64.
Finally, I've found the trouble and fixed it. As the system informed, chown: invalid user: ‘dnsmasq:nogroup’ is the bad code. I thought it should be dnsmasq failed to automatically add user or group that caused the error.
One solution might be manually adding a user named "dnsmasq". I didn't try it but I thought it would work. Another handling way is to looked up user "dnsmasq" in relative files and replace user "dnsmasq" with an existing user like "nobody".
There are 3 places in the /etc/init.d/dnsmasq file that need replace.
if [ ! "$DNSMASQ_USER" ]; then
DNSMASQ_USER="*dnsmasq*"
fi
# /run may be volatile, so we need to ensure that
# /run/dnsmasq exists here as well as in postinst
if [ ! -d /run/dnsmasq ]; then
mkdir /run/dnsmasq || return 2
chown *dnsmasq*:nogroup /run/dnsmasq || return 2
fi
# /run may be volatile, so we need to ensure that
# /run/dnsmasq exists here as well as in postinst
if [ ! -d /run/dnsmasq ]; then
mkdir /run/dnsmasq || return 2
chown *dnsmasq*:nogroup /run/dnsmasq || return 2
fi
Replace 3 empasized places above.
Although I'm not sure why dnsmasq failed to access account files.

Logging all connections using iptables to closed ports

In FreeBSD, there is a kernel parameter tweakable via sysctl (net.inet.tcp.log_in_vain) that provides you with logs of attempted connections to ports which are not running a service (i.e. closed ports). These messages are logged to /var/log/messages (somewhat) in the following format:
2014-06-26 13:18:58|218.77.79.43|58848|192.168.192.28|443|tcp_input: Connection attempt to closed port
Without forwarding all connections from router to my FreeBSD box, I get these messages on a regular basis. How is this happening if I haven't explicitly created port-forward rulesets redirecting traffic to this box on the router?
I'm looking to set up something similar using iptables, reducing as much noise as possible e.g. only see connections for those originating outside of my network as src and ignore any outgoing.
I was attempting to use something like the following to do this:
iptables -I INPUT -m state --state NEW -j LOG --log-prefix "New Connection: "
I'm pretty sure this syntax is fairly outdated. I come from an IPF world so I'm not quite up to speed with the latest iptables syntax conventions.
This rule is generating the type of logs I'm looking for in /var/log/messages:
Jun 28 00:38:12 kermit kernel: [ 6331.339928] New Connection: IN=eth0 OUT= MAC=ff:ff:ff:ff:ff:ff:a8:86:dd:8a:c9:26:08:00:45:00:00:48:e8:3f:00:00:40:11:8f:ec │
SRC=192.168.192.40 DST=192.168.192.255 LEN=72 TOS=0x00 PREC=0x00 TTL=64 ID=59455 PROTO=UDP SPT=57621 DPT=57621 LEN=52
Thus far, I haven't seen any connections from outside of my own network. Additionally, I can see SSH login attempts in /var/log/auth.log which are not appearing in /var/log/messages using the above iptables rule:
Jun 28 09:31:42 kermit sshd[10097]: pam_unix(sshd:auth): check pass; user unknown
Jun 28 09:31:44 kermit sshd[10097]: Failed password for invalid user admin from 116.10.191.187 port 40312 ssh2
Is it possible using iptables to create the following:
A rule/ruleset which logs all incoming connections to my box to /var/log/messages
Don't log any connections originating from within my own network
Don't log any outgoing connections
Am I required to forward all connections on the router to my box in order to get similar log messages as I did in FreeBSD? (i.e. port-forward all ports)
I found the following (basic) rulset did what I was looking for:
# Generated by iptables-save v1.4.14 on Sat Jun 28 14:02:33 2014
*filter
:INPUT ACCEPT [586:43405]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [367:72794]
:LOGNDROP - [0:0]
-A INPUT ! -s 192.168.192.0/24 -p tcp -m state --state NEW -j LOG --log-prefix "[New Connection]: "
COMMIT
# Completed on Sat Jun 28 14:02:33 2014

rsyslog - Property-based filtering not working

I almost hate to submit a topic for this, but I haven't been able to figure it out on my own. I'm running a Federoa 17 server, and I'm attempting to log dropped packets from iptables to a separate log file via rsyslog, but it keeps sending them to /var/log/messages instead.
Snippet from my firewall script:
#!/bin/bash
iptables -F
# My accepted rules would be here
iptables -A INPUT -j LOG --log-prefix "iptables: "
iptables -A FORWARD -j LOG --log-prefix "iptables: "
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables-save > /etc/sysconfig/iptables
service iptables restart
iptables -L -v
The config file that SHOULD be catching the messages from iptables:
[root#fc17 ]# cat /etc/rsyslog.d/iptables.conf
:msg, startswith, "iptables: " /var/log/iptables.log
& ~
Snippet from my rsyslog.conf file:
#### GLOBAL DIRECTIVES ####
# Include all config files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/*.conf
#### RULES ####
# I put this in here too to see if it would work; it doesn't
:msg, startswith, "iptables: " /var/log/iptables.log
& ~
# Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.* /dev/console
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none /var/log/messages
I've restarted both iptables and rsyslog multiple times since making the changes, and no matter what, it will only only log dropped packets from iptables to /var/log/messages.
I heard running rsyslog in compatibility mode can cause various problems. Could this be the case here? Here are its run-options on my system:
[root#fc17 ]# ps -ef | grep rsyslog
root 3571 1 0 00:59 ? 00:00:00 /sbin/rsyslogd -n -c 5
startswith comparison operator didn't work,because msg didn't begin with iptables: when i checked my logs.
[root#localhost ~]# cat /etc/rsyslog.d/test.conf
:msg, startswith, "iptables:" /var/log/iptables.log
but contains comparison operator worked on my FC18
[root#localhost ~]# cat /etc/rsyslog.d/test.conf
:msg, contains, "iptables:" /var/log/iptables.log
Ref: Rsyslog site
you should add the following two line in your "/etc/rsyslogd.conf" in directives part
$klogParseKernelTimestamp on
$klogKeepKernelTimestamp off
This will remove the kernel timestamp which appears in the begining of every kernel message like "[6448.546951]" in the following log
Mar 31 14:36:14 localhost kernel: [ 6448.546951] iptables: IN=ppp0 OUT= MAC= SRC=
2019 solution. Tested with rsyslogd 8.32.0 on Ubuntu18.04.
You can still use startswith,
[root#localhost ~]# cat /etc/rsyslog.d/test.conf
:msg, startswith, " iptables:" /var/log/iptables.log
by changing the line in /etc/rsyslogd.conf
module(load="imklog" ParseKernelTimestamp="on" KeepKernelTimestamp="off")
I'm using rsyslogd 5.8.10 over centos 6, my log report show this way:
Aug 12 11:50:41 node2 kernel: [10256396.525411] IPTables-Dropped: IN=eth0 OUT= MAC=00:25:90:c3:05:40:00:24:13:10:8c:00:08:00 SRC=212.237.40.56 DST=37.153.1.29 LEN=45 TOS=0x00 PREC=0x00 TTL=244 ID=54321 PROTO=UDP SPT=45661 DPT=53413 LEN=25
I tried to disabled the timestamp with:
$klogParseKernelTimestamp on
$klogKeepKernelTimestamp off
But show:
Aug 12 11:50:22 node2 rsyslogd-3003: invalid or yet-unknown config file command - have you forgotten to load a module? [try http://www.rsyslog.com/e/3003 ]
In modules have this:
#### MODULES ####
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imklog # provides kernel logging support (previously done by rklogd)
#$ModLoad immark # provides --MARK-- message capability
Thank you advance.

Through shell, adding an user with a slash path ("/") as directory : ssh/sftp impossible, even after re-creation of it with a named directory

First, what I'm trying to do is to jail (chroot) the user in a specfic directory for sftp access. I found a great tutorial that made the job, you can find it here : http://www.thegeekstuff.com/2012/03/chroot-sftp-setup/. You should read it first (it's very short) to understand the rest.
With the example in the link, I've no problem to create sftpusers group, guestuser user and lock it to the /sftp/guestuser/incoming directory. Here is how it's done :
groupadd sftpusers
useradd -g sftpusers -d /incoming -s /sbin/nologin guestuser
passwd guestuser
chown guestuser:sftpusers /sftp/guestuser/incoming
service ssh restart
What I've tried to do after is to lock another user (we call it "test") from the same group in /sftp/test. So I've created user like this :
useradd -g sftpusers -d / -s /sbin/nologin test
You see, instead /incoming as directory, I've just put "/", then I've changed rights to /sftp/test and restart ssh. But connection fails and give me this error : Write failed: Broken pipe
I thought it was due to the wrong path "/", so I decided to delete user and re-create it with an /incoming directory :
userdel test
useradd -g sftpusers -d /incoming -s /sbin/nologin test
passwd test
chown test:sftpusers /sftp/test/incoming
service ssh restart
But even after, the test user seems to be compromise for ever, because I have the same error when I try to connect through sftp : Write failed: Broken pipe Couldn't read packet: Connection reset by peer
EDIT :
Here is the log file for sshd :
Jan 24 12:46:20 ns sshd[13786]: error: Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Jan 24 12:46:23 ns sshd[13786]: Accepted password for test from xxx.xxx.xxx.xxx port 37838 ssh2
Jan 24 12:46:23 ns sshd[13786]: pam_unix(sshd:session): session opened for user test by (uid=0)
Jan 24 12:46:24 ns sshd[13949]: fatal: bad ownership or modes for chroot directory "/sftp/test"
Jan 24 12:46:24 ns sshd[13786]: pam_unix(sshd:session): session closed for user test
Jan 24 12:48:17 ns sshd[14103]: error: Could not load host key: /etc/ssh/ssh_host_ecdsa_key
Jan 24 12:48:19 ns sshd[14103]: Invalid user brad from xxx.xxx.xxx.xxx
Jan 24 12:48:19 ns sshd[14103]: input_userauth_request: invalid user brad [preauth]
Jan 24 12:48:19 ns sshd[14103]: pam_unix(sshd:auth): check pass; user unknown
Jan 24 12:48:19 ns sshd[14103]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=xxx.xxx.xxx.xxx
Jan 24 12:48:22 ns sshd[14103]: Failed password for invalid user brad from xxx.xxx.xxx.xxx port 42756 ssh2
Jan 24 12:48:22 ns sshd[14103]: Received disconnect from xxx.xxx.xxx.xxx: 11: Bye Bye [preauth]
Check the debug log for sshd. You'll likely find it complain about the home directory for user test not being secure.
The sshd is very strict about access to the user's credentials in $HOME/.ssh and will disconnect when it cannot access the directory, or when it detects permissions that would allow any other account to access it.
sshd[13949]: fatal: bad ownership or modes for chroot directory "/sftp/test"
Make sure that the owner of the directory is the only account that can modify any file in $HOME and below. Pay attention specifically to the group settings

Resources